Перейти к основному содержанию

Параметры

Этот метод не принимает параметров.

Ответ

result
number
Наивысший слот, который может быть вставлен в базу данных shred

Примеры кода

Базовый запрос

curl https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY -X POST -H "Content-Type: application/json" -d '{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getMaxShredInsertSlot"
}'

Использование web3.js

import { Connection } from '@solana/web3.js';

const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY');

// Get max shred insert slot
const maxShredInsertSlot = await connection.getMaxShredInsertSlot();
console.log('Max shred insert slot:', maxShredInsertSlot);

// Check if a slot can be inserted
async function canInsertSlot(slot: number) {
  const maxShredInsertSlot = await connection.getMaxShredInsertSlot();
  return slot <= maxShredInsertSlot;
}

// Get insert range
async function getInsertRange() {
  const maxShredInsertSlot = await connection.getMaxShredInsertSlot();
  const firstAvailableBlock = await connection.getFirstAvailableBlock();
  
  return {
    startSlot: firstAvailableBlock,
    endSlot: maxShredInsertSlot,
    totalSlots: maxShredInsertSlot - firstAvailableBlock + 1
  };
}

Примечания

  1. Возвращает наивысший слот, который может быть вставлен в базу данных shred
  2. Используется для определения диапазона слотов, доступных для вставки shred
  3. Ответ приходит немедленно, так как читается из текущего состояния
  4. Слоты, превышающие это значение, не могут быть вставлены
  5. Это значение может меняться по мере обработки узлом новых слотов

Рекомендации

  1. Используйте этот метод для определения доступности вставки shred
  2. Кэшируйте результаты там, где это уместно, для снижения нагрузки на RPC
  3. Учитывайте влияние обработки слотов
  4. Отслеживайте изменения максимального слота вставки shred
  5. Используйте совместно с другими методами работы со слотами

Распространённые ошибки

КодСообщениеРешение
-32601Method not foundУбедитесь, что вы подключены к узлу Solana RPC
-32007Slot information unavailableУзел может выполнять начальную загрузку или синхронизацию

Сценарии использования

  1. Планирование вставки shred
    interface InsertPlan {
      startSlot: number;
      endSlot: number;
      totalSlots: number;
      availableSlots: number[];
      unavailableSlots: number[];
    }
    
    async function planShredInsertion(
      targetSlots: number[]
    ): Promise<InsertPlan> {
      const maxShredInsertSlot = await connection.getMaxShredInsertSlot();
      const firstAvailableBlock = await connection.getFirstAvailableBlock();
      
      const availableSlots = targetSlots.filter(
        slot => slot >= firstAvailableBlock && slot <= maxShredInsertSlot
      );
      
      const unavailableSlots = targetSlots.filter(
        slot => slot < firstAvailableBlock || slot > maxShredInsertSlot
      );
      
      return {
        startSlot: firstAvailableBlock,
        endSlot: maxShredInsertSlot,
        totalSlots: maxShredInsertSlot - firstAvailableBlock + 1,
        availableSlots,
        unavailableSlots
      };
    }
    
  2. Мониторинг обработки слотов
    interface ProcessingAlert {
      type: 'lag' | 'gap' | 'unavailable';
      message: string;
      slot: number;
      maxShredInsertSlot: number;
    }
    
    class ProcessingMonitor {
      private previousMaxSlot: number | null = null;
      
      async monitorProcessing(
        targetSlots: number[]
      ): Promise<ProcessingAlert[]> {
        const maxShredInsertSlot = await connection.getMaxShredInsertSlot();
        const alerts: ProcessingAlert[] = [];
        
        // Check for processing lag
        if (this.previousMaxSlot !== null) {
          const expectedProgress = this.previousMaxSlot + 1;
          if (maxShredInsertSlot < expectedProgress) {
            alerts.push({
              type: 'lag',
              message: `Processing lag detected: expected ${expectedProgress}, got ${maxShredInsertSlot}`,
              slot: maxShredInsertSlot,
              maxShredInsertSlot
            });
          }
        }
        
        // Check target slots availability
        for (const slot of targetSlots) {
          if (slot > maxShredInsertSlot) {
            alerts.push({
              type: 'unavailable',
              message: `Slot ${slot} is beyond max shred insert slot`,
              slot,
              maxShredInsertSlot
            });
          }
        }
        
        this.previousMaxSlot = maxShredInsertSlot;
        return alerts;
      }
    }
    
  3. Управление базой данных shred
    interface ShredDatabaseMetrics {
      availableRange: {
        start: number;
        end: number;
        total: number;
      };
      processingRate: number;
      lag: number;
      metadata: {
        timestamp: number;
        maxShredInsertSlot: number;
      };
    }
    
    class ShredDatabaseManager {
      private previousMetrics: {
        timestamp: number;
        maxSlot: number;
      } | null = null;
      
      async getMetrics(): Promise<ShredDatabaseMetrics> {
        const maxShredInsertSlot = await connection.getMaxShredInsertSlot();
        const firstAvailableBlock = await connection.getFirstAvailableBlock();
        const currentTime = Date.now();
        
        let processingRate = 0;
        let lag = 0;
        
        if (this.previousMetrics !== null) {
          const timeDiff = (currentTime - this.previousMetrics.timestamp) / 1000; // seconds
          const slotDiff = maxShredInsertSlot - this.previousMetrics.maxSlot;
          processingRate = slotDiff / timeDiff;
          
          const currentSlot = await connection.getSlot();
          lag = currentSlot - maxShredInsertSlot;
        }
        
        this.previousMetrics = {
          timestamp: currentTime,
          maxSlot: maxShredInsertSlot
        };
        
        return {
          availableRange: {
            start: firstAvailableBlock,
            end: maxShredInsertSlot,
            total: maxShredInsertSlot - firstAvailableBlock + 1
          },
          processingRate,
          lag,
          metadata: {
            timestamp: currentTime,
            maxShredInsertSlot
          }
        };
      }
    }