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

# getMinimumBalanceForRentExemption

> Возвращает минимальный баланс, необходимый для освобождения аккаунта от арендной платы

## Параметры

<ResponseField name="dataLength" type="number">
  Длина данных аккаунта в байтах
</ResponseField>

<ResponseField name="config" type="object" optional>
  <Expandable title="поля config">
    <ResponseField name="commitment" type="string" optional>
      Уровень commitment (processed, confirmed, finalized)
    </ResponseField>
  </Expandable>
</ResponseField>

## Ответ

<ResponseField name="result" type="number">
  Минимальный баланс, необходимый для освобождения от арендной платы, в lamports
</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": "getMinimumBalanceForRentExemption",
  "params": [1000]
}'
```

### Использование 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 minimum balance for rent exemption
const dataLength = 1000; // bytes
const minBalance = await connection.getMinimumBalanceForRentExemption(dataLength);
console.log('Minimum balance:', minBalance);

// Calculate account creation cost
async function calculateAccountCost(
  dataLength: number,
  owner: string
) {
  const minBalance = await connection.getMinimumBalanceForRentExemption(dataLength);
  const rentExempt = minBalance;
  
  return {
    dataLength,
    minBalance,
    rentExempt,
    owner
  };
}

// Check if account has sufficient balance
async function hasSufficientBalance(
  account: string,
  dataLength: number
) {
  const [balance, minBalance] = await Promise.all([
    connection.getBalance(account),
    connection.getMinimumBalanceForRentExemption(dataLength)
  ]);
  
  return {
    account,
    currentBalance: balance,
    requiredBalance: minBalance,
    hasSufficientBalance: balance >= minBalance,
    difference: balance - minBalance
  };
}
```

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

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

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

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

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

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

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

1. **Анализ стоимости аккаунта**
   ```typescript theme={null}
   interface AccountCost {
     dataLength: number;
     minBalance: number;
     rentExempt: number;
     owner: string;
     metadata: {
       timestamp: number;
       commitment: string;
     };
   }

   async function analyzeAccountCost(
     dataLength: number,
     owner: string,
     commitment: string = 'confirmed'
   ): Promise<AccountCost> {
     const minBalance = await connection.getMinimumBalanceForRentExemption(
       dataLength,
       { commitment }
     );
     
     return {
       dataLength,
       minBalance,
       rentExempt: minBalance,
       owner,
       metadata: {
         timestamp: Date.now(),
         commitment
       }
     };
   }
   ```

2. **Мониторинг баланса**
   ```typescript theme={null}
   interface BalanceAlert {
     type: 'insufficient' | 'warning' | 'sufficient';
     message: string;
     account: string;
     currentBalance: number;
     requiredBalance: number;
     difference: number;
   }

   class BalanceMonitor {
     private previousBalances: Map<string, number> = new Map();
     
     async monitorBalance(
       account: string,
       dataLength: number,
       warningThreshold: number = 0.1 // 10% above minimum
     ): Promise<BalanceAlert[]> {
       const [balance, minBalance] = await Promise.all([
         connection.getBalance(account),
         connection.getMinimumBalanceForRentExemption(dataLength)
       ]);
       
       const alerts: BalanceAlert[] = [];
       const difference = balance - minBalance;
       const warningLevel = minBalance * warningThreshold;
       
       if (difference < 0) {
         alerts.push({
           type: 'insufficient',
           message: `Account ${account} has insufficient balance for rent exemption`,
           account,
           currentBalance: balance,
           requiredBalance: minBalance,
           difference
         });
       } else if (difference < warningLevel) {
         alerts.push({
           type: 'warning',
           message: `Account ${account} balance is close to minimum required`,
           account,
           currentBalance: balance,
           requiredBalance: minBalance,
           difference
         });
       } else {
         alerts.push({
           type: 'sufficient',
           message: `Account ${account} has sufficient balance`,
           account,
           currentBalance: balance,
           requiredBalance: minBalance,
           difference
         });
       }
       
       this.previousBalances.set(account, balance);
       return alerts;
     }
   }
   ```

3. **Планирование аккаунтов**
   ```typescript theme={null}
   interface AccountPlan {
     accounts: Array<{
       purpose: string;
       dataLength: number;
       minBalance: number;
       estimatedUsage: string;
     }>;
     totalCost: number;
     recommendations: string[];
   }

   async function planAccounts(
     accountSpecs: Array<{
       purpose: string;
       dataLength: number;
       estimatedUsage: string;
     }>
   ): Promise<AccountPlan> {
     const accounts = await Promise.all(
       accountSpecs.map(async spec => {
         const minBalance = await connection.getMinimumBalanceForRentExemption(
           spec.dataLength
         );
         
         return {
           ...spec,
           minBalance
         };
       })
     );
     
     const totalCost = accounts.reduce(
       (sum, account) => sum + account.minBalance,
       0
     );
     
     const recommendations = [];
     
     // Check for potential optimizations
     const largeAccounts = accounts.filter(
       account => account.dataLength > 10000
     );
     if (largeAccounts.length > 0) {
       recommendations.push(
         'Consider optimizing data storage for large accounts'
       );
     }
     
     const expensiveAccounts = accounts.filter(
       account => account.minBalance > 1e9 // More than 1 SOL
     );
     if (expensiveAccounts.length > 0) {
       recommendations.push(
         'Review high-cost accounts for potential optimizations'
       );
     }
     
     return {
       accounts,
       totalCost,
       recommendations
     };
   }
   ```
