> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orbitflare.com/llms.txt
> Use this file to discover all available pages before exploring further.

# getSlotLeaders

> Возвращает лидеров слотов для заданного диапазона

## Параметры

<ResponseField name="startSlot" type="number" required>
  Начальный номер слота
</ResponseField>

<ResponseField name="limit" type="number" required>
  Количество лидеров слотов для возврата
</ResponseField>

## Ответ

<ResponseField name="result" type="array">
  Массив публичных ключей лидеров слотов (закодированных в base-58)
</ResponseField>

## Примеры кода

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

```bash theme={null}
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": "getSlotLeaders",
  "params": [
    1000000,
    10
  ]
}'
```

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

```typescript theme={null}
import { Connection } from '@solana/web3.js';

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

// Get slot leaders
const slotLeaders = await connection.getSlotLeaders(1000000, 10);
console.log('Slot leaders:', slotLeaders);

// Get slot leaders with analysis
async function getSlotLeadersWithAnalysis(
  startSlot: number,
  limit: number
) {
  const slotLeaders = await connection.getSlotLeaders(startSlot, limit);
  
  return {
    slotLeaders,
    analysis: {
      uniqueLeaders: new Set(slotLeaders).size,
      leaderDistribution: slotLeaders.reduce((acc, leader) => {
        acc[leader] = (acc[leader] || 0) + 1;
        return acc;
      }, {} as Record<string, number>),
      metadata: {
        startSlot,
        endSlot: startSlot + limit - 1,
        timestamp: Date.now()
      }
    }
  };
}
```

## Примечания

1. Возвращает лидеров слотов для заданного диапазона слотов
2. Лидеры слотов отвечают за производство блоков
3. Ответ приходит немедленно, поскольку считывается из текущего состояния
4. Лидеры слотов определяются расписанием лидеров сети
5. Диапазон должен находиться в пределах текущего epoch

## Лучшие практики

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

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

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

## Примеры использования

1. **Анализ расписания лидеров**
   ```typescript theme={null}
   interface LeaderScheduleAnalysis {
     schedule: Array<{
       slot: number;
       leader: string;
     }>;
     distribution: Record<string, number>;
     metadata: {
       startSlot: number;
       endSlot: number;
       uniqueLeaders: number;
     };
   }

   async function analyzeLeaderSchedule(
     startSlot: number,
     limit: number
   ): Promise<LeaderScheduleAnalysis> {
     const slotLeaders = await connection.getSlotLeaders(startSlot, limit);
     
     const schedule = slotLeaders.map((leader, index) => ({
       slot: startSlot + index,
       leader
     }));
     
     const distribution = slotLeaders.reduce((acc, leader) => {
       acc[leader] = (acc[leader] || 0) + 1;
       return acc;
     }, {} as Record<string, number>);
     
     return {
       schedule,
       distribution,
       metadata: {
         startSlot,
         endSlot: startSlot + limit - 1,
         uniqueLeaders: Object.keys(distribution).length
       }
     };
   }
   ```

2. **Мониторинг расписания лидеров**
   ```typescript theme={null}
   interface LeaderScheduleChange {
     slot: number;
     previousLeader: string;
     currentLeader: string;
     metadata: {
       timestamp: number;
     };
   }

   class LeaderScheduleMonitor {
     private previousSchedule: Map<number, string> = new Map();
     
     async monitorLeaderSchedule(
       startSlot: number,
       limit: number,
       interval: number = 60000
     ): Promise<LeaderScheduleChange[]> {
       const slotLeaders = await connection.getSlotLeaders(startSlot, limit);
       const changes: LeaderScheduleChange[] = [];
       
       slotLeaders.forEach((leader, index) => {
         const slot = startSlot + index;
         const previousLeader = this.previousSchedule.get(slot);
         
         if (previousLeader && previousLeader !== leader) {
           changes.push({
             slot,
             previousLeader,
             currentLeader: leader,
             metadata: {
               timestamp: Date.now()
             }
           });
         }
         
         this.previousSchedule.set(slot, leader);
       });
       
       return changes;
     }
   }
   ```

3. **Планирование расписания лидеров**
   ```typescript theme={null}
   interface LeaderSchedulePlan {
     currentSlot: number;
     upcomingLeaders: Array<{
       slot: number;
       leader: string;
       estimatedTime: number;
     }>;
     metadata: {
       timestamp: number;
       slotsPerSecond: number;
     };
   }

   class LeaderSchedulePlanner {
     private readonly slotsPerSecond = 2; // Solana's target slot rate
     
     async planLeaderSchedule(
       startSlot: number,
       limit: number
     ): Promise<LeaderSchedulePlan> {
       const [slotLeaders, currentSlot] = await Promise.all([
         connection.getSlotLeaders(startSlot, limit),
         connection.getSlot()
       ]);
       
       const upcomingLeaders = slotLeaders.map((leader, index) => {
         const slot = startSlot + index;
         const slotsAhead = slot - currentSlot;
         const estimatedTime = slotsAhead / this.slotsPerSecond;
         
         return {
           slot,
           leader,
           estimatedTime
         };
       });
       
       return {
         currentSlot,
         upcomingLeaders,
         metadata: {
           timestamp: Date.now(),
           slotsPerSecond: this.slotsPerSecond
         }
       };
     }
   }
   ```
