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

# isBlockhashValid

> Возвращает, действителен ли blockhash в настоящее время или нет

## Параметры

<ResponseField name="blockhash" type="string" required>
  Blockhash для проверки (в кодировке base-58)
</ResponseField>

<ResponseField name="config" type="object" optional>
  Объект конфигурации, содержащий:

  <ResponseField name="commitment" type="string" optional>
    Уровень подтверждения (processed, confirmed, finalized)
  </ResponseField>

  <ResponseField name="minContextSlot" type="number" optional>
    Минимальный слот, при котором может быть оценён запрос
  </ResponseField>
</ResponseField>

## Ответ

<ResponseField name="result" type="boolean">
  Действителен ли blockhash (true) или нет (false)
</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": "isBlockhashValid",
  "params": [
    "J7rBdM6AecPDEZp8aPq5tPmsPzPhQG4HD6YtAcQBDfJj"
  ]
}'
```

### Использование 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');

// Check if blockhash is valid
const isValid = await connection.isBlockhashValid('J7rBdM6AecPDEZp8aPq5tPmsPzPhQG4HD6YtAcQBDfJj');
console.log('Is blockhash valid:', isValid);

// Check blockhash validity with analysis
async function checkBlockhashValidityWithAnalysis(
  blockhash: string,
  config: { 
    commitment?: string;
    minContextSlot?: number;
  }
) {
  const isValid = await connection.isBlockhashValid(blockhash, config);
  
  return {
    blockhash,
    validity: {
      isValid,
      checkedAt: Date.now()
    },
    config: {
      commitment: config.commitment,
      minContextSlot: config.minContextSlot
    }
  };
}
```

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

1. Возвращает, действителен ли blockhash в настоящее время
2. Blockhash истекают через определённое количество слотов
3. Ответ приходит немедленно, так как читается из текущего состояния
4. Недействительные blockhash не могут использоваться в транзакциях
5. Blockhash должен быть в кодировке base-58

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

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

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

| Код    | Сообщение           | Решение                                        |
| ------ | ------------------- | ---------------------------------------------- |
| -32601 | Method not found    | Убедитесь, что вы подключены к узлу Solana RPC |
| -32602 | Invalid params      | Проверьте формат blockhash                     |
| -32007 | Blockhash not found | Blockhash истёк или недействителен             |

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

1. **Валидация blockhash**
   ```typescript theme={null}
   interface BlockhashValidation {
     blockhash: string;
     validity: {
       isValid: boolean;
       checkedAt: number;
     };
     config: {
       commitment?: string;
       minContextSlot?: number;
     };
   }

   class BlockhashValidator {
     async validateBlockhash(
       blockhash: string,
       config: { 
         commitment?: string;
         minContextSlot?: number;
       }
     ): Promise<BlockhashValidation> {
       const isValid = await connection.isBlockhashValid(blockhash, config);
       
       return {
         blockhash,
         validity: {
           isValid,
           checkedAt: Date.now()
         },
         config: {
           commitment: config.commitment,
           minContextSlot: config.minContextSlot
         }
       };
     }
   }
   ```

2. **Мониторинг blockhash**
   ```typescript theme={null}
   interface BlockhashStatus {
     blockhash: string;
     status: {
       isValid: boolean;
       lastChecked: number;
       checkCount: number;
     };
     history: Array<{
       timestamp: number;
       isValid: boolean;
     }>;
   }

   class BlockhashMonitor {
     private statuses: Map<string, BlockhashStatus> = new Map();
     
     async monitorBlockhash(
       blockhash: string,
       config: { 
         commitment?: string;
         minContextSlot?: number;
       }
     ): Promise<BlockhashStatus> {
       const isValid = await connection.isBlockhashValid(blockhash, config);
       const now = Date.now();
       
       let status = this.statuses.get(blockhash);
       if (!status) {
         status = {
           blockhash,
           status: {
             isValid,
             lastChecked: now,
             checkCount: 1
           },
           history: [{
             timestamp: now,
             isValid
           }]
         };
       } else {
         status.status.isValid = isValid;
         status.status.lastChecked = now;
         status.status.checkCount++;
         status.history.push({
           timestamp: now,
           isValid
         });
       }
       
       this.statuses.set(blockhash, status);
       return status;
     }
   }
   ```

3. **Планирование транзакций**
   ```typescript theme={null}
   interface TransactionPlan {
     blockhash: string;
     validity: {
       isValid: boolean;
       checkedAt: number;
     };
     recommendations: Array<{
       type: 'proceed' | 'retry' | 'abort';
       reason: string;
     }>;
     metadata: {
       timestamp: number;
     };
   }

   class TransactionPlanner {
     private readonly maxRetries = 3;
     private readonly validityCheckInterval = 1000; // 1 second
     
     async planTransaction(
       blockhash: string,
       config: { 
         commitment?: string;
         minContextSlot?: number;
       }
     ): Promise<TransactionPlan> {
       const isValid = await connection.isBlockhashValid(blockhash, config);
       const now = Date.now();
       
       const recommendations: Array<{
         type: 'proceed' | 'retry' | 'abort';
         reason: string;
       }> = [];
       
       if (isValid) {
         recommendations.push({
           type: 'proceed',
           reason: 'Blockhash is valid'
         });
       } else {
         recommendations.push({
           type: 'abort',
           reason: 'Blockhash is invalid'
         });
         
         recommendations.push({
           type: 'retry',
           reason: 'Get a new blockhash and retry'
         });
       }
       
       return {
         blockhash,
         validity: {
           isValid,
           checkedAt: now
         },
         recommendations,
         metadata: {
           timestamp: now
         }
       };
     }
     
     async waitForValidBlockhash(
       blockhash: string,
       config: { 
         commitment?: string;
         minContextSlot?: number;
       }
     ): Promise<boolean> {
       let retries = 0;
       
       while (retries < this.maxRetries) {
         const isValid = await connection.isBlockhashValid(blockhash, config);
         
         if (isValid) {
           return true;
         }
         
         retries++;
         await new Promise(resolve => setTimeout(resolve, this.validityCheckInterval));
       }
       
       return false;
     }
   }
   ```
