使用anchor程序丢弃mint权限
这篇介绍丢弃mint权限,这是常用的指令。
创建指令
在instructions
中添加revoke_mint_authority.rs
,并粘贴以下代码:
use anchor_lang::prelude::*;
use anchor_spl::token::{spl_token, Mint, SetAuthority, Token};
use anchor_spl::token::spl_token::instruction::AuthorityType;
use crate::constants::MINT_SEEDS;
use crate::errors::ErrorCode;
#[derive(Accounts)]
#[instruction(token_name: String, token_symbol: String)]
pub struct RevokeMintAuthority<'info> {
#[account(
mut,
seeds = [MINT_SEEDS.as_bytes(), token_name.as_bytes(), token_symbol.as_bytes()],
bump
)]
pub mint: Account<'info, Mint>,
#[account(mut)]
pub payer: Signer<'info>,
pub token_program: Program<'info, Token>,
}
impl<'info> RevokeMintAuthority<'info> {
pub fn revoke_mint_authority(ctx: Context<RevokeMintAuthority>, token_name: String, token_symbol: String) -> Result<()> {
require!(spl_token::ID == ctx.accounts.token_program.key(), ErrorCode::WrongTokenProgram);
if ctx.accounts.mint.freeze_authority.is_some() {
let seeds = &[MINT_SEEDS.as_bytes(), token_name.as_bytes(), token_symbol.as_bytes(), &[ctx.bumps.mint]];
let signer = [&seeds[..]];
anchor_spl::token::set_authority(
CpiContext::new_with_signer(
ctx.accounts.token_program.to_account_info(),
SetAuthority {
current_authority: ctx.accounts.mint.to_account_info(),
account_or_mint: ctx.accounts.mint.to_account_info(),
},
&signer,
),
AuthorityType::MintTokens,
None,
).map_err(|e| {
msg!("Revoke mint authority failed: {}", e);
e
})?;
msg!("Revoke mint authority successfully.");
}
Ok(())
}
}
在lib.rs中调用上面的指令
pub fn revoke_mint_authority(ctx: Context<RevokeMintAuthority>, token_name: String, token_symbol: String) -> Result<()> {
RevokeMintAuthority::revoke_mint_authority(ctx, token_name, token_symbol)
}
编译部署
anchor build && anchor deploy
编写测试代码
it("revoke mint authority", async () => {
// Prepare context for revoking mint authority
const context = {
mint: mintAccount,
payer: deployerAccount.publicKey,
tokenProgram: TOKEN_PROGRAM_ID,
};
// Call revoke_mint_authority instruction
const tx = await program.methods
.revokeMintAuthority(metadataParams.name, metadataParams.symbol)
.accounts(context)
.signers([deployerAccount])
.rpc();
console.log("Revoke mint authority transaction signature:", tx);
// Verify mint authority is revoked
const mintInfo = await provider.connection.getParsedAccountInfo(mintAccount);
console.log("Mint account after revoking mint authority:", mintInfo);
})
执行后,查看mint账户,如果MINT AUTHORITY为空,说明已经完成丢弃mint权限
丢弃了mint权限后,将无法mint任何代币。