Verified contractExactMIT
QuantumRaffleV2
Address0xa730a436ead33e5cf0c4efed707a15e79f528260
- Balance
0.091146 ETH
- Transactions
182
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,012,088
- Creation transaction
- 0x50e22836f2…22c0aa9330
2 files
src/QuantumRaffleV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/// @title QuantumRaffleV2
/// @author MaximusDAO
/// @notice A configurable raffle contract with logarithmic winner selection and adoption bonus system
/// @dev Winner positions are determined by powers of a configurable base from the end of the entry list.
/// Early adopters earn bonuses when new cohort thresholds are crossed.
contract QuantumRaffleV2 is ReentrancyGuard {
/// @notice Denominator for basis-point values (10000 = 100%)
uint256 public constant BPS_DENOMINATOR = 10000;
/// @notice Hard cap on the deposit fee in basis points (1000 = 10%)
/// @dev Prevents the host from setting an abusive fee rate
uint256 public constant MAX_DEPOSIT_FEE_BPS = 1000;
/// @notice The current host address that controls game configuration and receives leftover funds
address public host;
/// @notice The pending host address for two-step ownership transfer
address public pendingHost;
/// @notice The current game ID, incremented each time a new game starts
uint256 public gameId;
/// @notice The configuration to be used for the next game
gameConfig public nextGameConfig;
/// @notice Total deposit fees accrued so far that the host can withdraw
/// @dev Increments on every successful deposit when the active game's depositFeeBps > 0
/// and is zeroed on withdrawal. Survives across games.
uint256 public accruedDepositFees;
/// @notice Struct for batch claiming adoption bonuses
/// @param cohortId The cohort ID to claim from
/// @param entrantId The entrant ID claiming the bonus
struct IdPair {
uint256 cohortId;
uint256 entrantId;
}
/// @notice Configuration parameters for a raffle game
/// @param grandPrizeLogBase The logarithmic base for determining winner positions
/// @param grandPrizeProportion The proportion of entry fees allocated to grand prize pool
/// @param viralityBonusLogBase The logarithmic base for cohort assignment
/// @param viralityBonusProportion The proportion of entry fees allocated to adoption bonus pool
/// @param entryAmount The cost in wei for a single entry
/// @param deadline The duration in seconds after last entry before game ends
/// @param depositFeeBps The host deposit fee in basis points (0-1000, i.e. 0%-10%)
/// captured from msg.value before any entry processing.
/// LOCKED at the moment a game starts: setNextGameConfig affects
/// only the next game, never the active one.
/// @param minTicketsBeforeEnd The minimum number of entries (tickets) that must be sold
/// before the inactivity countdown is allowed to expire. Setting this
/// to 0 disables the floor. LOCKED at the moment a game starts:
/// setNextGameConfig affects only the next game, never the active one.
struct gameConfig {
uint256 grandPrizeLogBase;
uint256 grandPrizeProportion;
uint256 viralityBonusLogBase;
uint256 viralityBonusProportion;
uint256 entryAmount;
uint256 deadline;
uint256 depositFeeBps;
uint256 minTicketsBeforeEnd;
}
/// @notice Timestamp of the last entry for each game
mapping (uint256 _gameId => uint256) public lastTimestamp;
/// @notice Maps game ID and entrant ID to the entrant's address
mapping (uint256 _gameId => mapping (uint256 _entrantId => address)) public entrants;
/// @notice Total number of entrants for each game
mapping (uint256 _gameId => uint256) public entrantCount;
/// @notice Stored configuration for each game
mapping (uint256 _gameId => gameConfig) public gameConfigRecord;
/// @notice Grand prize pool amount for each game
mapping (uint256 _gameId => uint256) public prizePool;
/// @notice Calculated prize amount per winner for each game
mapping (uint256 _gameId => uint256) public prizePerWinner;
/// @notice Tracks whether an entrant has claimed their grand prize
mapping (uint256 _gameId => mapping (uint256 _entrantId => bool)) public hasClaimed;
/// @notice Optional override for where an entry's prizes are paid out
/// @dev If set to a non-zero address, all grand prize and adoption bonus payouts
/// for this entry are routed here instead of the address that paid (entrants[_gameId][_entrantId]).
/// Set by sending ETH with a 20-byte address in calldata; see fallback().
/// Lets a hot/bot wallet enter on behalf of a more securely held cold wallet.
mapping (uint256 _gameId => mapping (uint256 _entrantId => address)) public prizeRecipient;
/// @notice Adoption bonus pool for each cohort in each game
mapping (uint256 _gameId => mapping (uint256 _cohortId => uint256)) public adoptionBonusPrizePool;
/// @notice Tracks whether an entrant has claimed their adoption bonus for a specific cohort
mapping (uint256 _gameId => mapping(uint256 _cohortId => mapping (uint256 _entrantId => bool))) public hasClaimedAdoptionBonus;
/// @notice Tracks whether leftover adoption bonus has been cleared for a game
mapping (uint256 => bool) public hasLeftoverBeenCleared;
/// @notice Total ETH contributed by each participant across all games
mapping (address _participant => uint256) public participantRecord;
/// @notice Total ETH won by each participant across all games
mapping (address _participant => uint256) public leaderboard;
/// @notice Emitted when a new game starts
/// @param gameId The ID of the new game
/// @param entryAmount The cost per entry in wei
/// @param grandPrizeLogBase The log base for winner selection
/// @param viralityBonusLogBase The log base for cohort assignment
/// @param deadline The inactivity duration before game ends
/// @param grandPrizeProportion Proportion allocated to grand prize
/// @param viralityBonusProportion Proportion allocated to adoption bonus
/// @param depositFeeBps The deposit fee in basis points locked in for the entire game
/// @param minTicketsBeforeEnd Minimum tickets required before the inactivity countdown can expire (locked for the entire game)
event GameStarted(uint256 indexed gameId, uint256 entryAmount, uint256 grandPrizeLogBase, uint256 viralityBonusLogBase, uint256 deadline, uint256 grandPrizeProportion, uint256 viralityBonusProportion, uint256 depositFeeBps, uint256 minTicketsBeforeEnd);
/// @notice Emitted when a winner claims their grand prize
/// @param gameId The game ID
/// @param entrantId The winning entrant ID
/// @param prize The prize amount in wei
event PrizeClaimed(uint256 indexed gameId, uint256 indexed entrantId, uint256 prize);
/// @notice Emitted when an entrant claims an adoption bonus
/// @param game_id The game ID
/// @param recipient The address receiving the bonus
/// @param entrant_id The entrant ID claiming the bonus
/// @param cohort_id The cohort from which the bonus is claimed
/// @param prize The bonus amount in wei
event ClaimedAdoptionBonus(uint256 indexed game_id, address indexed recipient, uint256 indexed entrant_id, uint256 cohort_id, uint256 prize);
/// @notice Emitted when an adoption bonus ETH transfer fails during batch processing
/// @dev The entrant's claim state is NOT updated, allowing retry via individual claim
/// @param gameId The game ID
/// @param recipient The address that failed to receive ETH
/// @param entrantId The entrant ID whose transfer failed
/// @param cohortId The cohort ID the claim was attempted for
/// @param prize The prize amount that was not transferred (in wei)
event AdoptionBonusTransferFailed(uint256 indexed gameId, address indexed recipient, uint256 indexed entrantId, uint256 cohortId, uint256 prize);
/// @notice Emitted when a player enters the game
/// @param gameId The game ID
/// @param entrant The address of the entrant
/// @param entryAmount The effective ETH amount contributed
/// @param entrantCount The new total entrant count
/// @param timestamp The block timestamp of entry
/// @param num_winners The current number of winners
/// @param prizePool The current prize pool
/// @param num_entries The number of entries purchased
event GameEntered(uint256 indexed gameId, address indexed entrant, uint256 entryAmount, uint256 entrantCount, uint256 timestamp, uint256 num_winners, uint256 prizePool, uint256 num_entries);
/// @notice Emitted when host transfer is initiated
/// @param currentHost The current host address
/// @param pendingHost The proposed new host address
event HostTransferInitiated(address indexed currentHost, address indexed pendingHost);
/// @notice Emitted when host transfer is completed
/// @param oldHost The previous host address
/// @param newHost The new host address
event HostTransferCompleted(address indexed oldHost, address indexed newHost);
/// @notice Emitted when a pending host transfer is cancelled
/// @param cancelledPendingHost The address that was pending but is now cancelled
event HostTransferCancelled(address indexed cancelledPendingHost);
/// @notice Emitted when excess ETH is refunded to an entrant
/// @param entrant The address receiving the refund
/// @param refundAmount The amount refunded in wei
event EntryRefunded(address indexed entrant, uint256 refundAmount);
/// @notice Emitted when the host updates the next game configuration
/// @param entryAmount The new entry amount in wei
/// @param deadline The new deadline duration in seconds
/// @param grandPrizeLogBase The new log base for winner selection
/// @param viralityBonusLogBase The new log base for cohort assignment
/// @param grandPrizeProportion The new grand prize proportion
/// @param viralityBonusProportion The new adoption bonus proportion
/// @param depositFeeBps The new deposit fee in basis points (applies to next game only)
/// @param minTicketsBeforeEnd The new minimum tickets-before-end (applies to next game only)
event GameConfigUpdated(uint256 entryAmount, uint256 deadline, uint256 grandPrizeLogBase, uint256 viralityBonusLogBase, uint256 grandPrizeProportion, uint256 viralityBonusProportion, uint256 depositFeeBps, uint256 minTicketsBeforeEnd);
/// @notice Emitted when a deposit fee is skimmed from a successful entry purchase
/// @dev Emitted only when feeAmount > 0. The sum of feeAmount and poolContribution
/// equals effectiveValue (num_entries * entryAmount) — i.e. the fee comes
/// out of the entry revenue, not on top of it.
/// @param gameId The game ID the deposit is associated with
/// @param payer The address that sent the deposit
/// @param feeAmount The amount of ETH taken as fee, added to accruedDepositFees (in wei)
/// @param poolContribution The remaining ETH routed to the prize and adoption bonus pools (in wei)
event DepositFeeCollected(uint256 indexed gameId, address indexed payer, uint256 feeAmount, uint256 poolContribution);
/// @notice Emitted when the host withdraws accrued deposit fees
/// @param host The host address receiving the withdrawal
/// @param amount The amount withdrawn in wei
event DepositFeesWithdrawn(address indexed host, uint256 amount);
/// @notice Emitted when an entry is bought with a prize-recipient override
/// @dev Triggered from fallback() when the payer routes prizes to a different address
/// (e.g. a hot wallet bot funding entries for a cold wallet).
/// @param gameId The game ID
/// @param entrantId The entrant ID whose prizes are being routed
/// @param payer The address that sent the ETH (normally msg.sender of the entry)
/// @param recipient The address that will receive grand prize and adoption bonus payouts
event PrizeRecipientSet(uint256 indexed gameId, uint256 indexed entrantId, address indexed payer, address recipient);
/// @notice Thrown when a non-host attempts a host-only action
error OnlyHost();
/// @notice Thrown when ETH transfer fails
error EtherTransferFailed();
/// @notice Thrown when attempting to clear already-cleared leftover
error AlreadyClaimed();
/// @notice Thrown when claiming from an ineligible cohort
error IneligibleCohort();
/// @notice Thrown when entrant ID is invalid (0 or greater than entrant count)
error IneligibleEntrantId();
/// @notice Thrown when referencing a game that doesn't exist yet
error OnlyActiveOrPastGames();
/// @notice Thrown when claiming from a cohort that hasn't been surpassed
error OnlySurpassedCohorts();
/// @notice Thrown when a non-winner attempts to claim a prize
error NotAWinner();
/// @notice Thrown when attempting to claim before game has ended
error GameNotFinished();
/// @notice Thrown when attempting to claim a prize twice
error CanOnlyClaimOnce();
/// @notice Thrown when deadline parameter is too small (must be > 1)
error DeadlineMustBeInFuture();
/// @notice Thrown when entry amount is zero
error EntryAmountMustBePositive();
/// @notice Thrown when log base is 0 or 1 (must be > 1)
error LogBaseMustBeGreaterThanOne();
/// @notice Thrown when attempting to calculate log of zero
error CannotCalculateLogOfZero();
/// @notice Thrown when setting host to zero address
error InvalidHostAddress();
/// @notice Thrown when accepting/cancelling transfer with no pending host
error NoPendingHostTransfer();
/// @notice Thrown when non-pending address tries to accept transfer
error NotPendingHost();
/// @notice Thrown when both prize proportions are zero
error ZeroProportions();
/// @notice Thrown when ETH sent is insufficient for even one entry
error NoValidEntries();
/// @notice Thrown when cohort ID is 0 or 1 (must be >= 2)
error CohortIdTooLow();
/// @notice Thrown when exponentiation would overflow
error ExponentiationOverflow();
/// @notice Thrown when attempting to set the deposit fee above MAX_DEPOSIT_FEE_BPS
error DepositFeeTooHigh();
/// @notice Thrown when fallback() is invoked with calldata that is not exactly 20 bytes
/// @dev To route prizes to a different address, send ETH with calldata equal to the
/// raw 20-byte recipient address. Any other calldata length is rejected so
/// malformed inputs cannot silently lose prizes to an unintended address.
error InvalidRecipientCalldata();
/// @notice Thrown when the prize recipient encoded in calldata is the zero address
error InvalidPrizeRecipient();
/// @notice Creates a new QuantumRaffleV2 contract
/// @dev Sets the deployer as host and configures the first game parameters
/// @param _entryAmount The cost in wei for a single entry (must be > 0)
/// @param _deadline The inactivity duration in seconds before game ends (must be > 1)
/// @param _grandPrizeLogBase The log base for winner selection (must be > 1)
/// @param _viralityBonusLogBase The log base for cohort assignment (must be > 1)
/// @param _grandPrizeProportion Proportion of entries allocated to grand prize
/// @param _viralityBonusProportion Proportion of entries allocated to adoption bonus
/// @param _depositFeeBps Host deposit fee in basis points (must be <= MAX_DEPOSIT_FEE_BPS)
/// @param _minTicketsBeforeEnd Minimum tickets that must be sold before the countdown can expire (0 to disable)
constructor(uint256 _entryAmount, uint256 _deadline, uint _grandPrizeLogBase, uint _viralityBonusLogBase, uint256 _grandPrizeProportion, uint256 _viralityBonusProportion, uint256 _depositFeeBps, uint256 _minTicketsBeforeEnd)
nonReentrant() {
if(_deadline <= 1) revert DeadlineMustBeInFuture();
if(_entryAmount == 0) revert EntryAmountMustBePositive();
if(_grandPrizeLogBase <= 1) revert LogBaseMustBeGreaterThanOne();
if(_viralityBonusLogBase <= 1) revert LogBaseMustBeGreaterThanOne();
if(_grandPrizeProportion + _viralityBonusProportion == 0) revert ZeroProportions();
if(_depositFeeBps > MAX_DEPOSIT_FEE_BPS) revert DepositFeeTooHigh();
host = msg.sender;
nextGameConfig = gameConfig({
grandPrizeLogBase: _grandPrizeLogBase,
grandPrizeProportion: _grandPrizeProportion,
viralityBonusLogBase: _viralityBonusLogBase,
viralityBonusProportion: _viralityBonusProportion,
entryAmount: _entryAmount,
deadline: _deadline,
depositFeeBps: _depositFeeBps,
minTicketsBeforeEnd: _minTicketsBeforeEnd
});
}
/// @notice Handles incoming ETH payments to enter the raffle game
/// @dev When game is over, only host can send ETH to start a new game.
/// The sender's ETH buys whole entries at entryAmount each (dust is
/// refunded as before). The deposit fee is then skimmed from the
/// entry revenue (effectiveValue), NOT added on top of entryAmount.
/// The remainder funds the grand prize pool and adoption bonus pools.
/// Reverts if msg.value is insufficient for at least one entry.
/// Prize payouts default to msg.sender; use fallback() to route them elsewhere.
receive()
external payable nonReentrant {
_processEntry(address(0));
}
/// @notice Handles incoming ETH payments where calldata specifies a prize-recipient address
/// @dev Calldata MUST be exactly 20 bytes encoding the cold-wallet recipient address.
/// All grand prize and adoption bonus payouts for the entries bought in this tx
/// will be routed to that recipient instead of msg.sender. Refunds (dust) and
/// participantRecord still belong to msg.sender — only prize payouts are redirected.
/// This lets a hot wallet (e.g. an AI bot) act as the entrant while prizes accrue
/// to a more securely held cold wallet.
fallback()
external payable nonReentrant {
if (msg.data.length != 20) revert InvalidRecipientCalldata();
address recipient = address(bytes20(msg.data));
if (recipient == address(0)) revert InvalidPrizeRecipient();
_processEntry(recipient);
}
/// @notice Internal entry-processing logic shared by receive() and fallback()
/// @dev When _recipient is the zero address, prizes default to msg.sender (the entrant
/// address recorded in entrants[]). When non-zero, prizeRecipient[] is set so all
/// payouts for entries bought in this tx route to _recipient.
/// @param _recipient The override address for prize payouts, or address(0) for default
function _processEntry(address _recipient)
private {
if (isGameOver()){
if(msg.sender != host) revert OnlyHost();
gameId++;
gameConfigRecord[gameId] = nextGameConfig;
emit GameStarted(
gameId,
nextGameConfig.entryAmount,
nextGameConfig.grandPrizeLogBase,
nextGameConfig.viralityBonusLogBase,
nextGameConfig.deadline,
nextGameConfig.grandPrizeProportion,
nextGameConfig.viralityBonusProportion,
nextGameConfig.depositFeeBps,
nextGameConfig.minTicketsBeforeEnd
);
}
gameConfig memory config = gameConfigRecord[gameId];
// Entries are priced at entryAmount. Dust (less than one full entry)
// is refunded to the sender. The fee does NOT change the price of
// an entry; it is skimmed from the revenue generated by entries.
uint256 num_entries = msg.value / config.entryAmount;
uint256 refundAmount = msg.value % config.entryAmount;
uint256 effectiveValue = msg.value - refundAmount;
if(num_entries == 0) revert NoValidEntries();
// Skim the host fee out of effectiveValue. The rate is the one
// LOCKED IN when this game started (gameConfigRecord[gameId]) —
// setNextGameConfig cannot change the fee mid-game. The pool
// contribution is what remains after the fee is taken.
uint256 feeAmount = effectiveValue * config.depositFeeBps / BPS_DENOMINATOR;
uint256 poolContribution = effectiveValue - feeAmount;
if (feeAmount > 0) {
accruedDepositFees += feeAmount;
emit DepositFeeCollected(gameId, msg.sender, feeAmount, poolContribution);
}
uint256 viralityBonusContribution = poolContribution * config.viralityBonusProportion / (config.viralityBonusProportion + config.grandPrizeProportion);
uint256 grandPrizeContribution = poolContribution - viralityBonusContribution;
prizePool[gameId] += grandPrizeContribution;
uint256 currentCount = entrantCount[gameId];
uint256 c;
uint256 cohort_id;
for (uint256 i=0; i<num_entries; i++) {
currentCount++;
entrants[gameId][currentCount] = msg.sender;
if (_recipient != address(0)) {
prizeRecipient[gameId][currentCount] = _recipient;
emit PrizeRecipientSet(gameId, currentCount, msg.sender, _recipient);
}
c = log(config.viralityBonusLogBase, currentCount) + 1;
if (c==1) {
cohort_id = 2;
}
else {
cohort_id = c;
}
adoptionBonusPrizePool[gameId][cohort_id] += viralityBonusContribution/num_entries;
}
entrantCount[gameId] = currentCount;
uint256 num_winners = getNumWinners(gameId);
prizePerWinner[gameId] = prizePool[gameId]/num_winners;
lastTimestamp[gameId] = block.timestamp;
participantRecord[msg.sender] += effectiveValue;
emit GameEntered(gameId, msg.sender, effectiveValue, entrantCount[gameId], lastTimestamp[gameId], num_winners, prizePool[gameId], num_entries);
if (refundAmount > 0) {
sendEth(payable(msg.sender), refundAmount);
emit EntryRefunded(msg.sender, refundAmount);
}
}
/// @notice Returns the address that will receive prizes for a given entry
/// @dev Falls back to entrants[_gameId][_entrantId] when no override was set.
/// @param _gameId The game ID
/// @param _entrantId The entrant ID
/// @return The address that receives grand prize and adoption bonus payouts for this entry
function getPrizeRecipient(uint256 _gameId, uint256 _entrantId)
public view returns (address) {
address override_ = prizeRecipient[_gameId][_entrantId];
if (override_ != address(0)) return override_;
return entrants[_gameId][_entrantId];
}
/// @notice Checks if the current game has ended
/// @dev A game is over when block.timestamp exceeds lastTimestamp + deadline, or if no game exists yet.
/// If the game's locked minTicketsBeforeEnd is non-zero and entrantCount has not reached it,
/// the game is considered active regardless of the elapsed time — entries can still be made
/// and the countdown only takes effect once the floor has been hit.
/// @return isOver True if the game is over or no game exists, false otherwise
function isGameOver()
public view returns (bool isOver) {
if (gameId==0) return true;
gameConfig memory config = gameConfigRecord[gameId];
if (entrantCount[gameId] < config.minTicketsBeforeEnd) return false;
isOver=(block.timestamp>lastTimestamp[gameId]+config.deadline);
}
/// @notice Calculates the adoption bonus prize amount per team for a given game and cohort
/// @dev The adoption bonus pool for a cohort is divided among (cohortId - 1) teams
/// @param _gameId The ID of the game to check
/// @param _cohortId The cohort ID (must be >= 2)
/// @return The adoption bonus prize amount per team in wei
function getAdoptionBonusPrizePerTeam(uint256 _gameId, uint256 _cohortId)
public view returns (uint256) {
if(_cohortId <= 1) revert CohortIdTooLow();
return adoptionBonusPrizePool[_gameId][_cohortId]/(_cohortId-1);
}
/// @notice Checks if an entrant is qualified to claim an adoption bonus
/// @dev Qualification requires: valid game/entrant, unclaimed bonus, entrant's cohort < claimed cohort,
/// and the claimed cohort must have been surpassed (a later cohort exists)
/// @param _gameId The ID of the game to check
/// @param _entrantId The entrant ID to check qualification for
/// @param _cohortId The cohort ID to check qualification for
/// @return qualified True if the entrant can claim the bonus, false otherwise
function isQualifiedAdoptionBonus(uint256 _gameId, uint256 _entrantId, uint256 _cohortId)
public view returns (bool qualified) {
if(gameId < _gameId) return false;
uint256 num_entrants = entrantCount[_gameId];
if(num_entrants == 0) return false;
gameConfig memory config = gameConfigRecord[_gameId];
if(_entrantId > num_entrants || _entrantId == 0) return false;
if(hasClaimedAdoptionBonus[_gameId][_cohortId][_entrantId]) return false;
uint256 entrant_cohort = log(config.viralityBonusLogBase, _entrantId) + 1;
if(entrant_cohort >= _cohortId) return false;
uint256 currentMaxCohort = log(config.viralityBonusLogBase, num_entrants) + 1;
if(_cohortId >= currentMaxCohort) return false;
return true;
}
/// @notice Internal function to process an adoption bonus prize claim during batch processing
/// @dev Uses a 30,000 gas cap on the ETH transfer to prevent a malicious recipient from
/// consuming the caller's gas budget and DOSing the batch. If the transfer fails
/// (recipient reverts or exceeds gas cap), the claim state is NOT updated so the
/// entrant can retry via claimAdoptionBonusPrize(). The CEI inversion (interaction
/// before effect) is safe because batchClaimAdoptionBonusPrize is nonReentrant.
/// @param _gameId The ID of the game to claim from
/// @param _entrantId The entrant ID claiming the bonus
/// @param _cohortId The cohort ID being claimed from
function _claimAdoptionBonusPrize(uint256 _gameId, uint256 _entrantId, uint256 _cohortId)
private {
if(isQualifiedAdoptionBonus(_gameId, _entrantId, _cohortId)){
uint256 team_prize = getAdoptionBonusPrizePerTeam(_gameId, _cohortId);
gameConfig memory config = gameConfigRecord[_gameId];
uint256 d = log(config.viralityBonusLogBase, _entrantId) + 1;
uint256 base_d = safePow(config.viralityBonusLogBase, d);
uint256 base_d_minus_1 = safePow(config.viralityBonusLogBase, d - 1);
uint256 n = base_d - base_d_minus_1;
uint256 prize = team_prize/n;
address recipient = getPrizeRecipient(_gameId, _entrantId);
(bool sent, ) = payable(recipient).call{value: prize, gas: 30000}("");
if (sent) {
hasClaimedAdoptionBonus[_gameId][_cohortId][_entrantId] = true;
emit ClaimedAdoptionBonus(_gameId, recipient, _entrantId, _cohortId, prize);
} else {
emit AdoptionBonusTransferFailed(_gameId, recipient, _entrantId, _cohortId, prize);
}
}
}
/// @notice Batch claim adoption bonus prizes for multiple entrant/cohort combinations
/// @dev Uses a 30,000 gas cap per transfer to prevent a single reverting recipient from
/// DOSing the entire batch. Failed transfers emit AdoptionBonusTransferFailed and
/// leave the claim state unchanged so the entrant can retry via claimAdoptionBonusPrize().
/// Silently skips any claims that don't qualify.
/// @param _gameId The ID of the game to claim adoption bonuses from
/// @param identifications Array of IdPair structs with cohortId and entrantId to claim
function batchClaimAdoptionBonusPrize(uint256 _gameId, IdPair[] calldata identifications)
external nonReentrant {
for (uint256 i = 0; i < identifications.length; i++) {
_claimAdoptionBonusPrize(_gameId, identifications[i].entrantId, identifications[i].cohortId);
}
}
/// @notice Claim a single adoption bonus prize with no gas cap on the transfer
/// @dev Fallback for entrants whose wallets need more than 30,000 gas to receive ETH
/// (e.g. uncommon smart-contract wallet configurations). Uses sendEth which
/// forwards all available gas and reverts on failure. Follows checks-effects-
/// interactions: state is updated before the external call.
/// @param _gameId The ID of the game to claim from
/// @param _entrantId The entrant ID claiming the bonus
/// @param _cohortId The cohort ID being claimed from
function claimAdoptionBonusPrize(uint256 _gameId, uint256 _entrantId, uint256 _cohortId)
external nonReentrant {
if(!isQualifiedAdoptionBonus(_gameId, _entrantId, _cohortId)) revert IneligibleCohort();
uint256 team_prize = getAdoptionBonusPrizePerTeam(_gameId, _cohortId);
gameConfig memory config = gameConfigRecord[_gameId];
uint256 d = log(config.viralityBonusLogBase, _entrantId) + 1;
uint256 base_d = safePow(config.viralityBonusLogBase, d);
uint256 base_d_minus_1 = safePow(config.viralityBonusLogBase, d - 1);
uint256 n = base_d - base_d_minus_1;
uint256 prize = team_prize/n;
hasClaimedAdoptionBonus[_gameId][_cohortId][_entrantId] = true;
address recipient = getPrizeRecipient(_gameId, _entrantId);
sendEth(payable(recipient), prize);
emit ClaimedAdoptionBonus(_gameId, recipient, _entrantId, _cohortId, prize);
}
/// @notice Allows winners to claim their grand prize from a completed game
/// @dev Validates entrant ID bounds, winner status, game completion, and prevents double claims
/// @param _gameId The ID of the game to claim from
/// @param _entrantId The entrant ID claiming the prize
function claimPrize(uint256 _gameId, uint256 _entrantId)
external nonReentrant {
if(_entrantId == 0 || _entrantId > entrantCount[_gameId]) revert IneligibleEntrantId();
if(!isWinner(_gameId, _entrantId)) revert NotAWinner();
if(gameId < _gameId) revert GameNotFinished();
if (gameId==_gameId) {
if(!isGameOver()) revert GameNotFinished();
}
if(hasClaimed[_gameId][_entrantId]) revert CanOnlyClaimOnce();
uint256 prize = prizePerWinner[_gameId];
address winner = getPrizeRecipient(_gameId, _entrantId);
leaderboard[winner]+= prize;
hasClaimed[_gameId][_entrantId]=true;
sendEth(payable(winner), prize);
emit PrizeClaimed(_gameId, _entrantId, prize);
}
/// @notice Allows the host to claim leftover adoption bonus from the final cohort
/// @dev Only callable after game ends, and only once per game
/// @param _gameId The ID of the completed game to clear leftover from
function clearLeftoverAdoptionBonus(uint256 _gameId)
external nonReentrant {
if(msg.sender != host) revert OnlyHost();
if(gameId < _gameId) revert GameNotFinished();
if (gameId==_gameId) {
if(!isGameOver()) revert GameNotFinished();
}
if(hasLeftoverBeenCleared[_gameId]) revert AlreadyClaimed();
gameConfig memory config = gameConfigRecord[_gameId];
uint256 last_cohort = log(config.viralityBonusLogBase, entrantCount[_gameId]) + 1;
uint256 leftover = adoptionBonusPrizePool[_gameId][last_cohort];
hasLeftoverBeenCleared[_gameId]=true;
sendEth(payable(host), leftover);
}
/// @notice Withdraws all accrued deposit fees to the current host
/// @dev Host-only. Resets accruedDepositFees to zero before the transfer
/// (checks-effects-interactions). Safe to call when accrued amount is zero;
/// in that case it emits an event with amount=0 and no ETH is moved.
function withdrawDepositFees()
external nonReentrant {
if(msg.sender != host) revert OnlyHost();
uint256 amount = accruedDepositFees;
accruedDepositFees = 0;
if (amount > 0) {
sendEth(payable(host), amount);
}
emit DepositFeesWithdrawn(host, amount);
}
/// @notice Sends ETH to a specified address
/// @dev Uses low-level call for transfer, reverts on failure
/// @param _to The recipient address
/// @param amount The amount to send in wei
function sendEth(address payable _to, uint256 amount)
private {
(bool sent, ) = _to.call{value: amount}("");
if(!sent) revert EtherTransferFailed();
}
/// @notice Initiates a two-step host transfer to a new address
/// @dev New host must call acceptHostTransfer() to complete the transfer
/// @param _host The proposed new host address (cannot be zero address)
function initiateHostTransfer(address _host)
public nonReentrant {
if(msg.sender != host) revert OnlyHost();
if(_host == address(0)) revert InvalidHostAddress();
pendingHost = _host;
emit HostTransferInitiated(host, _host);
}
/// @notice Completes the host transfer
/// @dev Must be called by the pending host address
function acceptHostTransfer()
public nonReentrant {
if(pendingHost == address(0)) revert NoPendingHostTransfer();
if(msg.sender != pendingHost) revert NotPendingHost();
address oldHost = host;
host = pendingHost;
pendingHost = address(0);
emit HostTransferCompleted(oldHost, host);
}
/// @notice Cancels a pending host transfer
/// @dev Can only be called by the current host when a transfer is pending
function cancelHostTransfer()
public nonReentrant {
if(msg.sender != host) revert OnlyHost();
if(pendingHost == address(0)) revert NoPendingHostTransfer();
address cancelledHost = pendingHost;
pendingHost = address(0);
emit HostTransferCancelled(cancelledHost);
}
/// @notice Sets the configuration for the next game
/// @dev Only callable by host. Validates all parameters. Only affects the
/// *next* game — the active game's config (including deposit fee) is
/// locked when it starts and cannot be changed mid-raffle.
/// @param _entryAmount The cost in wei for a single entry (must be > 0)
/// @param _deadline The inactivity duration in seconds (must be > 1)
/// @param _grandPrizeLogBase The log base for winner selection (must be > 1)
/// @param _viralityBonusLogBase The log base for cohort assignment (must be > 1)
/// @param _grandPrizeProportion Proportion allocated to grand prize
/// @param _viralityBonusProportion Proportion allocated to adoption bonus
/// @param _depositFeeBps Host deposit fee in basis points (must be <= MAX_DEPOSIT_FEE_BPS)
/// @param _minTicketsBeforeEnd Minimum tickets that must be sold before the countdown can expire (0 to disable)
function setNextGameConfig(uint256 _entryAmount, uint256 _deadline, uint256 _grandPrizeLogBase, uint256 _viralityBonusLogBase, uint256 _grandPrizeProportion, uint256 _viralityBonusProportion, uint256 _depositFeeBps, uint256 _minTicketsBeforeEnd)
public nonReentrant {
if(msg.sender != host) revert OnlyHost();
if(_deadline <= 1) revert DeadlineMustBeInFuture();
if(_entryAmount == 0) revert EntryAmountMustBePositive();
if(_grandPrizeLogBase <= 1) revert LogBaseMustBeGreaterThanOne();
if(_viralityBonusLogBase <= 1) revert LogBaseMustBeGreaterThanOne();
if(_grandPrizeProportion + _viralityBonusProportion == 0) revert ZeroProportions();
if(_depositFeeBps > MAX_DEPOSIT_FEE_BPS) revert DepositFeeTooHigh();
nextGameConfig = gameConfig({
grandPrizeLogBase: _grandPrizeLogBase,
grandPrizeProportion: _grandPrizeProportion,
viralityBonusLogBase: _viralityBonusLogBase,
viralityBonusProportion: _viralityBonusProportion,
entryAmount: _entryAmount,
deadline: _deadline,
depositFeeBps: _depositFeeBps,
minTicketsBeforeEnd: _minTicketsBeforeEnd
});
emit GameConfigUpdated(_entryAmount, _deadline, _grandPrizeLogBase, _viralityBonusLogBase, _grandPrizeProportion, _viralityBonusProportion, _depositFeeBps, _minTicketsBeforeEnd);
}
/// @notice Checks if a given entrant ID is a winner for a specific game
/// @dev Winners are: the last entrant, or those whose position from end is a power of grandPrizeLogBase.
/// Returns false for invalid inputs (zero entrant count, entrantId 0, or entrantId > count).
/// @param _gameId The ID of the game to check
/// @param _entrantId The ID of the entrant to check
/// @return True if the entrant is a winner, false otherwise
function isWinner(uint256 _gameId, uint256 _entrantId)
public view
returns (bool) {
uint256 count = entrantCount[_gameId];
if(count == 0 || _entrantId == 0 || _entrantId > count) return false;
if (_entrantId == count) return true;
uint256 n = 1 + count - _entrantId;
uint256 base = gameConfigRecord[_gameId].grandPrizeLogBase;
return isPower(base, n);
}
/// @notice Checks if a number is a power of a given base (including 1 = base^0)
/// @dev Repeatedly divides by base; returns true if remainder reaches 1
/// @param base The base to check against (must be > 1)
/// @param number The number to check
/// @return True if number is a power of base, false otherwise
function isPower(uint256 base, uint256 number)
public pure
returns (bool) {
uint256 temp = number;
while (temp > 0) {
if (temp % base != 0) {
return temp == 1;
}
temp = temp / base;
}
return false;
}
/// @notice Gets the number of winners for a given game
/// @dev Number of winners equals floor(log_base(entrantCount)) + 1
/// @param _gameId The ID of the game to check
/// @return The number of winners for the specified game
function getNumWinners(uint256 _gameId)
public view returns (uint256) {
uint256 value = entrantCount[_gameId];
uint256 base = gameConfigRecord[_gameId].grandPrizeLogBase;
return log(base, value) + 1;
}
/// @notice Gets the current cohort number for a given game
/// @dev Cohort number equals floor(log_base(entrantCount)) + 1 using viralityBonusLogBase
/// @param _gameId The ID of the game to check
/// @return The current cohort number
function getCurrentCohort(uint256 _gameId)
public view returns (uint256) {
uint256 value = entrantCount[_gameId];
uint256 base = gameConfigRecord[_gameId].viralityBonusLogBase;
return log(base, value) + 1;
}
/// @notice Calculates the floor of the logarithm of a number with a given base
/// @dev Uses iterative division to compute floor(log_base(x))
/// @param base The base of the logarithm (must be > 1)
/// @param x The number to calculate the logarithm of (must be > 0)
/// @return result The floor of log_base(x)
function log(uint256 base, uint256 x)
public pure
returns (uint256 result) {
if(base <= 1) revert LogBaseMustBeGreaterThanOne();
if(x == 0) revert CannotCalculateLogOfZero();
result = 0;
uint256 value = x;
while (value >= base) {
value = value / base;
result++;
}
return result;
}
/// @notice Calculates base raised to the power of exp with overflow protection
/// @dev Uses iterative multiplication with overflow check after each step
/// @param base The base number
/// @param exp The exponent
/// @return result The result of base^exp
function safePow(uint256 base, uint256 exp)
public pure
returns (uint256 result) {
if(exp == 0) return 1;
result = 1;
for(uint256 i = 0; i < exp; i++) {
unchecked {
uint256 newResult = result * base;
if(newResult / base != result) revert ExponentiationOverflow();
result = newResult;
}
}
return result;
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.