149-Solana入门(十三)- 合约内创建账户

我们先来看一下

直接在客户端发起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);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值