在 Solana 的 Anchor 框架中,close 用于销毁账户并回收租金,将 lamports 转移并变更所有权至系统程序,而程序关闭则通过 CLI 实现且地址不可重用。
在 Solana 的 Anchor 框架中,close 是与 init 相对的操作,用于销毁账户。它将账户的 lamport 余额清零,将 lamports 转移到指定地址,并将账户的所有者变更为系统程序。本文将深入探讨账户和程序的关闭过程,结合代码示例和底层实现,阐明其工作原理及关键细节。
Anchor 中的 close 指令用于释放账户空间并回收租金。以下是 Rust 示例:
use anchor_lang::prelude::*;
use std::mem::size_of;
declare_id!("BonMtRCa3eCq6mPHFqY5aVUh3QbUnzB1e5wPaWgSNCdJ");
#[program]
pub mod close_program {
use super::*;
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
Ok(())
}
pub fn delete(ctx: Context<Delete>) -> Result<()> {
Ok(())
}
}
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(init, payer = signer, space = size_of::<ThePda>() + 8, seeds = [], bump)]
pub the_pda: Account<'info, ThePda>,
#[account(mut)]
pub signer: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct Delete<'info> {
#[account(mut, close = signer, )]
pub the_pda: Account<'info, ThePda>,
#[account(mut)]
pub signer: Signer<'info>,
}
#[account]
pub struct ThePda {
pub x: u32,
}
close = signer 宏指定 lamports 返回给交易签名者(也可指定其他地址)。这与以太坊中 selfdestruct(Dencun 升级前)的退款机制类似。回收的 SOL 数量与账户占用空间成正比。
以下是 Typescript 调用示例:
import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { CloseProgram } from "../target/types/close_program";
import { assert } from "chai";
describe("close_program", () => {
// Configure the client to use the local cluster.
anchor.setProvider(anchor.AnchorProvider.env());
const program = anchor.workspace.CloseProgram as Program<CloseProgram>;
it("Is initialized!", async () => {
let [thePda, _bump] = anchor.web3.PublicKey.findProgramAddressSync([], program.programId);
await program.methods.initialize().accounts({thePda: thePda}).rpc();
await program.methods.delete().accounts({thePda: thePda}).rpc();
let account = await program.account.thePda.fetchNullable(thePda);
console.log(account)
});
});
需要注意的是,该示例允许任何人关闭账户。在生产环境中,应添加权限验证以限制操作。
关闭账户后,其地址仍可通过 initialize 重建,但需再次支付租金。这类似于以太坊中销毁后地址可重用的特性。
Anchor 的 close 指令源码(v0.29.0)如下:
use crate::prelud...
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!