在 Anchor 中读取账户余额:Solana 的 address(account).balance

  • 0xE
  • 发布于 2025-03-28 09:55
  • 阅读 517

本文介绍了在 Solana Anchor 中使用 Rust 读取账户余额的方法,阐释了 UncheckedAccount 的作用与安全性,解释了无需 [account] 结构体的原因,并提及账户余额与免租机制的相关注意事项。

在 Rust 中读取账户余额

在 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();
  });
});

本例引入了 UncheckedAcco...

剩余50%的内容订阅专栏后可查看

点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
0xE
0xE
0x59f6...a17e
17年进入币圈,Web3 开发者。刨根问底探链上真相,品味坎坷悟 Web3 人生。