【问题标题】:How to reference a specific account in Solana programs with multiple accounts?如何在具有多个帐户的 Solana 程序中引用特定帐户?
【发布时间】:2022-01-11 05:40:40
【问题描述】:

此程序允许用户创建一个帐户来收款。所以“Alice”可以创建帐户 Fundraiser。在 Fundraiser 中,有一个特定的变量 amount_raised 用于跟踪向她的账户发送了多少 SOL。该程序允许多人创建新的筹款活动..SO,我如何在“捐赠”功能中引用正确的帐户?我怀疑我需要使用 PDA 或至少遍历所有程序帐户并将其与创建者的 pubkey 匹配。先感谢您。 (Sol 是在客户端发送的,我只想通过添加金额来跟踪 amount_raised)。

use super::*;

pub fn donate(ctx: Context<Donate>, amount: u32) -> ProgramResult {
    let fundraiser: &mut Account<Fundraiser> = &mut ctx.accounts.fundraiser;
    let user: &Signer = &ctx.accounts.user;
    fundraiser.amount_raised += amount;
    Ok(())
}


pub fn start_fund(ctx: Context<StartFund>, amount: u32, reason: String) -> ProgramResult {
    let fundraiser: &mut Account<Fundraiser> = &mut ctx.accounts.fundraiser;
    let author: &Signer = &ctx.accounts.author;
    let clock: Clock = Clock::get().unwrap();

    if reason.chars().count() > 350 {
        return Err(ErrorCode::ContentTooLong.into())
    }

    fundraiser.author = *author.key;
    fundraiser.amount_to_raise = amount;     
    fundraiser.timestamp = clock.unix_timestamp;
    fundraiser.reason = reason;
    Ok(())
}    

pub struct StartFund<'info> {
#[account(init, payer = author, space = 64 + 64)]
pub fundraiser: Account<'info, Fundraiser>,
#[account(mut)]
pub author: Signer<'info>,
#[account(address = system_program::ID)]
pub system_program: AccountInfo<'info>,
}    

#[derive(Accounts)]
pub struct Donate<'info> {
    #[account(mut)]
    pub fundraiser: Account<'info, Fundraiser>,
    #[account(mut)]
    pub user: Signer<'info>,
    #[account(address = system_program::ID)]
    pub system_program: AccountInfo<'info>,
    }        

#[account]
pub struct Fundraiser { 
 pub author: Pubkey,
 pub amount_to_raise: u32,
 pub amount_raised: u32,
 pub timestamp: i64,
 pub reason: String, //reason
}

} `

【问题讨论】:

    标签: rust anchor solana


    【解决方案1】:

    您几乎做对了——在您的 Donate 指令中,您还需要传入 Alice 的 author 帐户,以便您可以在期间将转账资金从 user 转移到 author Donate。所以相反,它看起来像:

    #[derive(Accounts)]
    pub struct Donate<'info> {
        #[account(mut)]
        pub fundraiser: Account<'info, Fundraiser>,
        #[account(mut)]
        pub user: Signer<'info>,
        #[account(mut)]
        pub author: AccountInfo<'info>,
        #[account(address = system_program::ID)]
        pub system_program: AccountInfo<'info>,
    }
    

    您必须检查提供的author 是否与fundraiser.author 匹配。

    【讨论】:

    • 嘿,我以为我已经弄清楚了,但它一直说“key.toBuffer 不是函数”...我正在遍历客户端的所有帐户和帐户的公钥。我是否应该迭代 solana 程序,以便获得正确的帐户来更改“amount_raised”?我不知道为什么这部分必须如此复杂。
    • 我想我在派生(帐户)部分得到了你的意思,但我对如何在指令区域进行此操作感到非常困惑。我在网上找不到任何关于它的信息
    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2018-02-19
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 2020-02-21
    相关资源
    最近更新 更多