此程序允许用户创建一个帐户来接收资金。所以"爱丽丝"可以创建帐户筹款人。在"筹款人"中,有一个特定的变量amount_raised,用于跟踪有多少SOL被发送到她的账户。该计划允许多人创建新的筹款人。。那么,如何在函数"捐赠"中引用正确的帐户?我怀疑我需要使用PDA,或者至少迭代所有程序帐户,并将其与创建者的公钥匹配。提前谢谢。(Sol是在客户端发送的,我只想通过添加金额来跟踪金额(。
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
}
}`
您基本上做对了——在Donate
指令中,您还需要传入Alice的author
帐户,以便在Donate
期间将资金从user
转移到author
。因此,它看起来像:
#[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
匹配。