> ## 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.

# getRecentPerformanceSamples

> Возвращает последние образцы производительности

## Параметры

<ResponseField name="limit" type="number" optional>
  Количество возвращаемых образцов (по умолчанию: 720)
</ResponseField>

## Ответ

<ResponseField name="result" type="array">
  Массив объектов образцов производительности

  <ResponseField name="slot" type="number">
    Номер слота
  </ResponseField>

  <ResponseField name="numSlots" type="number">
    Количество слотов в образце
  </ResponseField>

  <ResponseField name="numTransactions" type="number">
    Количество транзакций в образце
  </ResponseField>

  <ResponseField name="samplePeriodSecs" type="number">
    Период выборки в секундах
  </ResponseField>

  <ResponseField name="numNonVoteTransaction" type="number">
    Количество транзакций без голосования
  </ResponseField>
</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": "getRecentPerformanceSamples",
  "params": []
}'
```

### Запрос с лимитом

```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": "getRecentPerformanceSamples",
  "params": [
    100
  ]
}'
```

### Использование 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 recent performance samples
const samples = await connection.getRecentPerformanceSamples();
console.log('Performance samples:', samples);

// Calculate average TPS
function calculateAverageTPS(samples: any[]): number {
  const totalTransactions = samples.reduce(
    (sum, sample) => sum + sample.numTransactions,
    0
  );
  const totalSeconds = samples.reduce(
    (sum, sample) => sum + sample.samplePeriodSecs,
    0
  );
  return totalTransactions / totalSeconds;
}
```

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

1. Возвращает последние образцы производительности сети
2. Каждый образец охватывает период времени (обычно 60 секунд)
3. Образцы включают количество транзакций и информацию о слотах
4. Ответ приходит немедленно, так как читается из текущего состояния
5. Лимит по умолчанию — 720 образцов (примерно 12 часов)

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

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

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

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

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

1. **Анализ производительности**
   ```typescript theme={null}
   interface PerformanceMetrics {
     averageTPS: number;
     peakTPS: number;
     totalTransactions: number;
     totalSlots: number;
     metadata: {
       timestamp: number;
       sampleCount: number;
     };
   }

   async function analyzePerformance(
     limit: number = 720
   ): Promise<PerformanceMetrics> {
     const samples = await connection.getRecentPerformanceSamples(limit);
     
     const totalTransactions = samples.reduce(
       (sum, sample) => sum + sample.numTransactions,
       0
     );
     const totalSeconds = samples.reduce(
       (sum, sample) => sum + sample.samplePeriodSecs,
       0
     );
     const peakTPS = Math.max(
       ...samples.map(sample => sample.numTransactions / sample.samplePeriodSecs)
     );
     
     return {
       averageTPS: totalTransactions / totalSeconds,
       peakTPS,
       totalTransactions,
       totalSlots: samples.reduce((sum, sample) => sum + sample.numSlots, 0),
       metadata: {
         timestamp: Date.now(),
         sampleCount: samples.length
       }
     };
   }
   ```

2. **Мониторинг производительности**
   ```typescript theme={null}
   interface PerformanceAlert {
     type: 'high_tps' | 'low_tps' | 'anomaly';
     currentTPS: number;
     threshold: number;
     metadata: {
       timestamp: number;
       slot: number;
     };
   }

   class PerformanceMonitor {
     private previousTPS: number | null = null;
     private readonly threshold = 0.2; // 20% change threshold
     
     async monitorPerformance(
       interval: number = 60000
     ): Promise<PerformanceAlert | null> {
       const samples = await connection.getRecentPerformanceSamples(1);
       const currentSample = samples[0];
       const currentTPS = currentSample.numTransactions / currentSample.samplePeriodSecs;
       
       if (this.previousTPS === null) {
         this.previousTPS = currentTPS;
         return null;
       }
       
       const change = Math.abs(currentTPS - this.previousTPS) / this.previousTPS;
       
       if (change > this.threshold) {
         const alert: PerformanceAlert = {
           type: change > 0 ? 'high_tps' : 'low_tps',
           currentTPS,
           threshold: this.threshold,
           metadata: {
             timestamp: Date.now(),
             slot: currentSample.slot
           }
         };
         
         this.previousTPS = currentTPS;
         return alert;
       }
       
       return null;
     }
   }
   ```

3. **История производительности**
   ```typescript theme={null}
   interface PerformanceHistory {
     samples: Array<{
       slot: number;
       tps: number;
       nonVoteTPS: number;
       timestamp: number;
     }>;
     summary: {
       averageTPS: number;
       peakTPS: number;
       totalTransactions: number;
     };
     metadata: {
       startTime: number;
       endTime: number;
       sampleCount: number;
     };
   }

   async function getPerformanceHistory(
     limit: number = 720
   ): Promise<PerformanceHistory> {
     const samples = await connection.getRecentPerformanceSamples(limit);
     
     const processedSamples = samples.map(sample => ({
       slot: sample.slot,
       tps: sample.numTransactions / sample.samplePeriodSecs,
       nonVoteTPS: sample.numNonVoteTransaction / sample.samplePeriodSecs,
       timestamp: Date.now() - (samples.length - samples.indexOf(sample)) * sample.samplePeriodSecs * 1000
     }));
     
     const totalTransactions = samples.reduce(
       (sum, sample) => sum + sample.numTransactions,
       0
     );
     const totalSeconds = samples.reduce(
       (sum, sample) => sum + sample.samplePeriodSecs,
       0
     );
     
     return {
       samples: processedSamples,
       summary: {
         averageTPS: totalTransactions / totalSeconds,
         peakTPS: Math.max(...processedSamples.map(sample => sample.tps)),
         totalTransactions
       },
       metadata: {
         startTime: processedSamples[0].timestamp,
         endTime: processedSamples[processedSamples.length - 1].timestamp,
         sampleCount: samples.length
       }
     };
   }
   ```
