> ## 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 fields">
    <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
     };
   }
   ```
