Code: impl Participant { pub fn new(address: Pubkey, amount: u64) -> Self { Participant { address, amount } } }
// struct for AllParticipants PDA #[account] pub struct AllParticipants { pub participants: Vec, }
#[derive(Accounts)] #[instruction(name: String)] pub struct Create<'info> { #[account(init, payer=admin, space=9000, seeds=["lottery".as_ref(),name.as_ref()], bump)] pub lottery: Account<'info, Lottery>, #[account( init, payer = admin, space = AllParticipants::SIZE, seeds = ["account".as_ref(),name.as_ref()], bump )] pub all_participants: Account<'info, AllParticipants>, #[account(mut)] pub admin: Signer<'info>, pub system_program: Program<'info, System>, }
Main Functionality
for i in 0..all_participants.participants.len() { let user = &mut all_participants.participants[i]; if user.address == _winner { if deposit_amount < user.amount { return Err(ProgramError::Custom(403)); } **ctx .accounts .lottery .to_account_info() .try_borrow_mut_lamports()? -= user.amount; **admin.to_account_info().try_borrow_mut_lamports()? += user.amount; (&mut ctx.accounts.lottery).deposit_amount -= user.amount; (&mut ctx.accounts.lottery).winner = _winner; all_participants.participants.remove(i); break; }
**Code:**
impl Participant {
pub fn new(address: Pubkey, amount: u64) -> Self {
Participant { address, amount }
}
}
// struct for AllParticipants PDA
#[account]
pub struct AllParticipants {
pub participants: Vec<Participant>,
}
#[derive(Accounts)]
#[instruction(name: String)]
pub struct Create<'info> {
#[account(init, payer=admin, space=9000, seeds=["lottery".as_ref(),name.as_ref()], bump)]
pub lottery: Account<'info, Lottery>,
#[account(
init,
payer = admin,
space = AllParticipants::SIZE,
seeds = ["account".as_ref(),name.as_ref()],
bump
)]
pub all_participants: Account<'info, AllParticipants>,
#[account(mut)]
pub admin: Signer<'info>,
pub system_program: Program<'info, System>,
}
**Main Functionality**
for i in 0..all_participants.participants.len() {
let user = &mut all_participants.participants[i];
if user.address == _winner {
if deposit_amount < user.amount {
return Err(ProgramError::Custom(403));
}
**ctx
.accounts
.lottery
.to_account_info()
.try_borrow_mut_lamports()? -= user.amount;
**admin.to_account_info().try_borrow_mut_lamports()? += user.amount;
(&mut ctx.accounts.lottery).deposit_amount -= user.amount;
(&mut ctx.accounts.lottery).winner = _winner;
all_participants.participants.remove(i);
break;
}