我们先来看一下
直接在客户端发起tx然后创建账户
const tx = new anchor.web3.Transaction().add(
anchor.web3.SystemProgram.createAccount({
fromPubkey: provider.wallet.publicKey,
newAccountPubkey: keypair.publicKey,
space: MINT_SIZE,
programId: tokenProgram,
lamports,
}),
);
const res = await program.provider.sendAndConfirm(tx, [keypair]);
console.log(res)
这里就是直接在tx中加了SystemProgram的createAccount指令
参数是
from
to
space
owner
lamports
这样就可以直接创建一个账户
然后我们看一下,如何在合约中去创建账户
pub fn create(
ctx: Context<Create>,
lamports: u64,
space: u64,
owner: Pubkey,
) -> Result<()> {
let cpi_program = ctx.accounts.system_program.to_account_info();
let cpi_accounts = CreateAccount {
from: ctx.accounts.from.to_account_info(),
to: ctx.accounts.to.to_account_info(),
};
let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);
create_account(cpi_ctx, lamports, space, &owner)?;
Ok(())
}
写个handler
这边就是cpi调用SystemProgram的CreateAccount指令
也是一样的道理
前面是在客户端直接调用指令
这个是在合约中调用指令
看下Accounts
#[derive(Accounts)]
pub struct Create<'info> {
pub system_program: Program<'info, System>,
/// CHECK: This is not dangerous because we don't read or write from this account
#[account(mut)]
pub from: AccountInfo<'info>,
/// CHECK: This is not dangerous because we don't read or write from this account
#[account(mut)]
pub to: AccountInfo<'info>,
#[account(mut)]
pub signer: Signer<'info>,
}
然后我们调用一下这个create指令
//rpc
const result = await program.methods
.create(
new anchor.BN(lamports),
new anchor.BN(MINT_SIZE),
systemProgram
)
.accounts({
systemProgram: systemProgram,
from: provider.wallet.publicKey,
to: keypair.publicKey,
signer: keypair.publicKey
})
.signers([keypair])
.rpc();
console.log(result);