本文介绍了在 Solana Anchor 中使用 Rust 读取账户余额的方法,阐释了 UncheckedAccount 的作用与安全性,解释了无需 [account] 结构体的原因,并提及账户余额与免租机制的相关注意事项。
在 Solana Anchor 程序中,可通过以下代码读取任意账户的 Lamports 余额:
use anchor_lang::prelude::*;
declare_id!("7caefaGpKb1E48AkThaVqZqV12WdxbigeVhmRJyVt1EL");
#[program]
pub mod balance {
use super::*;
pub fn read_balance(ctx: Context<ReadBalance>) -> Result<()> {
let balance = ctx.accounts.acct.to_account_info().lamports();
msg!("balance in Lamports is {}", balance);
Ok(())
}
}
#[derive(Accounts)]
pub struct ReadBalance<'info> {
/// CHECK: although we read this account's balance, we don't do anything with the information
pub acct: UncheckedAccount<'info>,
}
测试代码:
import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { Balance } from "../target/types/balance";
describe("balance", () => {
anchor.setProvider(anchor.AnchorProvider.env());
const program = anchor.workspace.Balance as Program<Balance>;
let pubkey = new anchor.web3.PublicKey("5NhLjdFKocoRMqic9sqAe5TxLagJCoCBunzg51ioMYot");
it("Tests the balance", async () => {
const tx = await program.methods.readBalance().accounts({ acct: pubkey }).rpc();
});
});
本例引入了 UncheckedAccount,与此前文章有所不同。
UncheckedAccount 是 Anchor 中的账户类型,指示不对账户的所有权进行检查。
Anchor 强制为 UncheckedAccount 添加 /// CHECK: 注释,说明无需类型检查的原因。
移除注释,anchor build 将报错:
Please add a `/// CHECK:` doc comment explaining why no checks through types are necessary.
此机制提醒开发者关注潜在风险。
#[account]
pub struct Counter {
counter: u64,
}
本例仅读取余额(lamports),不涉及数据字段,因此无需结构体。类似以太坊读取地址余额,无需解析合约状态。
根据 Solana 账户租金,账户需维持最低 Lamports 余额以保持免租状态,否则将被运行时回收。
【笔记配套代码】 https://github.com/0xE1337/rareskills_evm_to_solana 【参考资料】 https://learnblockchain.cn/column/119 https://www.rareskills.io/solana-tutorial
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!