Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure a lottery ticket can only win once #6120

Merged
merged 5 commits into from
Jul 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 48 additions & 38 deletions backend/canisters/airdrop_bot/impl/src/model/airdrops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ impl Airdrops {
let config = self.next.take()?;

let mut total_shares: u32 = 0;
let mut total_tickets: u32 = 0;
let mut user_shares: Vec<(UserId, u32, u32)> = Vec::new();
let mut ticket_holders: Vec<UserId> = Vec::new();

Expand All @@ -114,7 +113,6 @@ impl Airdrops {
let tickets = chit / config.lottery_chit_band;

total_shares += shares;
total_tickets += tickets;

user_shares.push((user_id, chit, shares));

Expand All @@ -123,49 +121,61 @@ impl Airdrops {
}
}

if total_tickets == 0 || total_shares == 0 {
if total_shares == 0 {
return None;
}

let fund = config.main_chat_fund;
let prizes = config.lottery_prizes.len();
let outcome = AirdropOutcome {
participants: user_shares
.into_iter()
.map(|(u, chit, shares)| {
(
u,
Participant {
chit,
shares,
prize: if shares > 0 {
Some(Prize {
chat_won: (fund * shares as u128) / total_shares as u128,
block_index: None,
})
} else {
None
},
},
)
})
.collect(),
lottery_winners: (0..prizes)
.map(|i| {
let winning_ticket = (rng.next_u32() % total_tickets) as usize;
let winner = ticket_holders[winning_ticket];
(
winner,
Prize {
chat_won: config.lottery_prizes[i],
block_index: None,

let participants = user_shares
.into_iter()
.map(|(u, chit, shares)| {
(
u,
Participant {
chit,
shares,
prize: if shares > 0 {
Some(Prize {
chat_won: (fund * shares as u128) / total_shares as u128,
block_index: None,
})
} else {
None
},
)
})
.collect(),
};
},
)
})
.collect();

let mut lottery_winners = Vec::new();

let airdrop = Airdrop { config, outcome };
for i in 0..prizes {
megrogan marked this conversation as resolved.
Show resolved Hide resolved
if ticket_holders.is_empty() {
break;
}

let winning_ticket = (rng.next_u32() % ticket_holders.len() as u32) as usize;

let winner = ticket_holders.remove(winning_ticket);

lottery_winners.push((
winner,
Prize {
chat_won: config.lottery_prizes[i],
block_index: None,
},
));
}

let airdrop = Airdrop {
config,
outcome: AirdropOutcome {
participants,
lottery_winners,
},
};

self.past.push(airdrop);

Expand Down
Loading