Solana Anchor:如何为/读取关联帐户创建#[account(seeds)]?

Rus*_*sso 4 rust solana

在project-serum/anchor repo的Basic-5教程中我怎样才能用这样的东西替换#[关联]:

#[account(seeds = [user_data.deposit_last.as_ref(), &[user_data.__nonce]])]
Run Code Online (Sandbox Code Playgroud)

上面有一些不正确的地方,然后 Anchor 无法读取关联帐户的值

const userData = await program.account.userData.associated(wallet1, usdcMint);
Run Code Online (Sandbox Code Playgroud)

那么,替换关联帐户结构上方即将弃用的#[关联] 的正确方法是什么?

#[associated]
#[derive(Default)]
pub struct UserData {
  pub authority: Pubkey,
  pub deposit_last: i64,
  pub shares: u64,
  pub reward_debt: u64,
}

//UserData is initialized here first
#[derive(Accounts)]
pub struct Initialize<'info> {
  #[account(init, associated = authority, with = usdc_mint)]
  pub user_data: ProgramAccount<'info, UserData>,
...
}
Run Code Online (Sandbox Code Playgroud)

yan*_*-io 6

因此,种子方法是 PDA,这实际上是 #linked 在幕后使用的

init您将需要一个使用以下内容和特征初始化种子的函数payerpayer也应该是实际支付交易费用的同一用户。

请注意,它#[instruction(bump: u8]与此处函数的签名匹配,因此您需要将签名中的凹凸作为第一个参数传递。

#[instruction(bump: u8)]
pub struct Ctx<'info> {
  #[account(init, seeds = [user_data.deposit_last.as_ref(), &[bump]], payer = payer)]
  pub user_data = ProgramAccount<'info, UserData>,
}

Run Code Online (Sandbox Code Playgroud)

稍后对于其他功能如果您只想读取帐户,您可以使用

#[account(seeds = [user_data.deposit_last.as_ref(), &[user_data.__nonce]])]
pub user_data = ProgramAccount<'info, UserData>,
Run Code Online (Sandbox Code Playgroud)

更改您的帐户数据以使用 #[account] 而不是 #[关联]

#[account]
#[derive(Default)]
pub struct UserData {
  pub authority: Pubkey,
  pub deposit_last: i64,
  pub shares: u64,
  pub reward_debt: u64,
}
Run Code Online (Sandbox Code Playgroud)

这是一个示例https://github.com/project-serum/anchor/blob/master/examples/misc/programs/misc/src/context.rs#L10

  • @yangli-io 你的示例链接给了我一个 404 错误。也许将页面内容复制到您的答案中会有帮助? (4认同)