Verified contractExactMIT
GSwap
Address0x48294c29950a77ca0b8d044d1643f2a040715992
- Balance
0.00051 ETH
- Transactions
15
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,400,148
- Creation transaction
- 0x9c27c0e344…74b8380ee1
12 files
- src/GSwap.solmain57.67 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol4.93 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol995 B
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.26 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol3.24 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol869 B
- src/interfaces/ISwapRouter.sol647 B
- src/interfaces/IWETH9.sol346 B
src/GSwap.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {ISwapRouter} from "./interfaces/ISwapRouter.sol";
import {IWETH9} from "./interfaces/IWETH9.sol";
/// @title GSwap
/// @notice Swap router for GRANDPA with a built-in raffle. Every swap feeds a prize pot.
/// When the pot fills, a winner is drawn and paid automatically. GRANDPA holders get up to 2x
/// bonus entries. Buy-tax-aware: slippage protects what actually lands in your wallet.
/// Built for the Grandpa Ape Country Club. Deploys paused.
contract GSwap is IERC721Receiver, ReentrancyGuard {
using SafeERC20 for IERC20;
// ------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------
/// @notice Basis-point denominator (100% = 10000 bps).
uint256 public constant BPS_DENOMINATOR = 10_000;
/// @notice Maximum settable fee: 2000 bps = 20%.
uint256 public constant MAX_FEE_BPS = 2000;
/// @notice Minimum settable pot threshold: 0.01 ETH.
uint256 public constant MIN_POT_THRESHOLD = 0.01 ether;
/// @notice Token decimals. Enforced in the constructor.
uint8 public constant TOKEN_DECIMALS = 18;
/// @notice Minimum GRANDPA balance for holder bonus (10,000 tokens). Below this: 1x entries.
uint256 public constant HOLDER_BONUS_FLOOR = 10_000 * 10 ** TOKEN_DECIMALS;
/// @notice Holder bonus coefficient. ~10k tokens = 1.01x, ~1M = 1.49x, ~5M = 2x cap.
uint256 public constant HOLDER_BONUS_COEFF = 100;
/// @notice Maximum holder multiplier: 2x (20000 bps) on the BPS_DENOMINATOR (10000 = 1x) base.
uint256 public constant MAX_HOLDER_MULTIPLIER_BPS = 20_000;
/// @notice Gas for auto-paying ETH to the winner. Failed auto-pay falls back to claim().
uint256 public constant AUTO_PAY_GAS_LIMIT = 30_000;
/// @notice Gas cap for auto-paying token/NFT prizes. Falls back to claim() if exceeded.
uint256 public constant AUTO_PAY_BUNDLE_GAS_LIMIT = 500_000;
/// @notice Blocks before the owner can reclaim uncollected prizes (~30 days).
uint256 public constant RECLAIM_DELAY_BLOCKS = 216_000;
/// @notice Gas cap per prize transfer in reclaimExpired(). Bounds damage from a bad token.
uint256 public constant RECLAIM_ITEM_GAS_LIMIT = 300_000;
/// @dev Minimum gas before each reclaim transfer. Prevents under-gassed calls from stranding prizes.
uint256 private constant RECLAIM_MIN_GAS_PER_ITEM = (RECLAIM_ITEM_GAS_LIMIT * 64) / 63 + 20_000;
/// @dev Max revert reason length logged in PrizeReclaimFailed.
uint256 private constant MAX_REASON_LENGTH = 256;
// ------------------------------------------------------------------------
// Immutables / config
// ------------------------------------------------------------------------
/// @notice The underlying Uniswap V3 SwapRouter all trades are forwarded to.
ISwapRouter public immutable v3Router;
/// @notice The WETH9 contract. A buy has tokenIn == weth (paid as native ETH, wrapped by the
/// router); a sell has tokenOut == weth and the router returns WETH, which this contract
/// unwraps to native ETH before deducting the fee and paying the seller.
address public immutable weth;
/// @notice The GrandpaCoin token (symbol "GRANDPA") this router trades.
address public immutable token;
address public owner;
/// @notice Swap fee in basis points, collected from the ETH side. Default 30 bps (0.3%). Once the
/// current round has participants this value is frozen so entry pricing cannot change
/// mid-round; see pendingFeeBps.
uint256 public feeBps = 30;
/// @notice The fee that takes effect once the current round is drawn. While the current round has
/// no participants, setFeeBps applies immediately and this equals feeBps. Once the round
/// has participants, setFeeBps updates only this value, and draw() promotes it into feeBps.
uint256 public pendingFeeBps = 30;
/// @notice ETH the pot must reach before the current round becomes drawable. Default 1 ETH.
uint256 public potThreshold = 1 ether;
// ------------------------------------------------------------------------
// Pot + round storage
// ------------------------------------------------------------------------
/// @notice Uncommitted native ETH accumulated from swap fees toward the next draw. Only fee
/// collection grows the pot; raw ETH sent directly to the contract is never credited here.
uint256 public pot;
/// @notice Emergency switch. The contract deploys paused. While paused, swap() reverts entirely
/// (no fees, no entries, no auto-draw); draw(), claim(), reclaimExpired(), boostPrize(), and
/// withdrawRemaining() still work.
bool public paused;
/// @notice Count of drawn rounds with a still-owed prize, i.e. rounds where some auto-pay leg
/// failed at draw and has not yet been claimed or reclaimed. Fully auto-paid rounds never
/// count. Gates withdrawRemaining so the owner cannot reclaim funds while a winner is still
/// owed a prize.
uint256 public unclaimedRounds;
/// @notice Addresses allowed to queue ERC-20 / ERC-721 bonus prizes alongside the owner. Managed by
/// the owner via addPrizeManager / removePrizeManager. A prize manager has no other powers.
mapping(address manager => bool allowed) public prizeManager;
struct Round {
uint256 prizeETH; // ETH committed to the round (kept as history even after it is paid out)
uint256 drawnBlock;
bool drawn;
bool ethPaid; // the ETH prize has been delivered (auto-pay, claim, or reclaim)
bool tokensPaid; // the ERC-20 / ERC-721 bundle has been delivered (or there was none)
bool settled; // nothing is owed for this round: every prize leg has been delivered
address winner;
}
/// @notice The round currently accumulating entries. Always >= 1. Rounds 1..currentRound-1 have
/// been drawn; getRound(currentRound) is the open, not-yet-drawn round.
uint256 public currentRound = 1;
mapping(uint256 => Round) internal _rounds;
// Per-round bundled prizes (moved here from the queue when the round is drawn).
mapping(uint256 => address[]) internal _roundPrizeTokens;
mapping(uint256 => uint256[]) internal _roundPrizeTokenAmounts;
mapping(uint256 => address[]) internal _roundPrizeNFTs;
mapping(uint256 => uint256[]) internal _roundPrizeNFTIds;
// Owner-queued bonus prizes, indexed by the round they are earmarked for. addPrize targets the
// current round; addPrizeForRound targets a specific current-or-future round.
mapping(uint256 => address[]) internal _queuedTokens;
mapping(uint256 => uint256[]) internal _queuedTokenAmounts;
mapping(uint256 => address[]) internal _queuedNFTs;
mapping(uint256 => uint256[]) internal _queuedNFTIds;
// The set of round ids that have ever had a prize queued, so withdrawRemaining can sweep every
// parked (undrawn) bucket. Entries are never removed; consumed/empty buckets are simply skipped.
uint256[] internal _queuedRounds;
mapping(uint256 => bool) internal _roundQueued;
// Per-round entry bookkeeping.
mapping(uint256 => mapping(address => uint256)) public buyVolume;
mapping(uint256 => mapping(address => uint256)) public sellVolume;
mapping(uint256 => address[]) internal _participants;
mapping(uint256 => uint256) public totalSqrtWeight;
mapping(uint256 => uint256) internal _roundEntropy;
// Permissionless ETH prize boosts, indexed by the round they top up. Held separately from the pot so
// boosts never affect the draw threshold, earn entries, or trigger a draw; they are added to the
// prize when (and only when) that round actually draws. boostPrize only ever targets currentRound,
// and a round's boost is committed (and cleared) at its draw, so at any time the only round that can
// hold a nonzero boost is currentRound.
mapping(uint256 => uint256) internal _roundBoost;
// ------------------------------------------------------------------------
// Lifetime swap stats (tracked on every swap)
// ------------------------------------------------------------------------
mapping(address => uint256) public lifetimeVolume;
mapping(address => uint256) public swapCount;
mapping(address => uint256) public lastSwapBlock;
uint256 public totalLifetimeVolume;
uint256 public uniqueSwappers;
// ------------------------------------------------------------------------
// Events
// ------------------------------------------------------------------------
event EntryRegistered(
uint256 indexed roundId, address indexed swapper, bool isBuy, uint256 ethVolume, uint256 newWeight
);
event WinnerDrawn(uint256 indexed roundId, address indexed winner, uint256 participants, uint256 totalSqrtWeight);
event PrizeAutoPaid(
uint256 indexed roundId, address indexed winner, uint256 ethAmount, bool ethPaid, bool tokensPaid
);
event PrizeClaimed(uint256 indexed roundId, address indexed winner, uint256 ethAmount);
event PrizeReclaimed(uint256 indexed roundId, address indexed winner, address indexed to, uint256 ethAmount);
event PrizeReclaimFailed(
uint256 indexed roundId, uint256 prizeIndex, address indexed asset, bool isERC721, bytes reason
);
event PrizeQueued(uint256 indexed roundId, address indexed asset, uint256 amountOrId, bool isERC721);
event PrizeBoosted(uint256 indexed roundId, address indexed booster, uint256 amount);
event FeeCollected(address indexed swapper, bool isBuy, uint256 feeAmount, uint256 newPot);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event Paused();
event Unpaused();
event WithdrawnRemaining(address indexed to, uint256 ethAmount, uint256 tokenCount, uint256 nftCount);
event PotThresholdSet(uint256 newThreshold);
event FeeBpsSet(uint256 newFeeBps);
event FeeBpsQueued(uint256 pendingFeeBps);
event SwapTracked(address indexed swapper, uint256 amountIn, uint256 lifetimeVolume, uint256 swapCount);
event PrizeManagerAdded(address indexed manager);
event PrizeManagerRemoved(address indexed manager);
// ------------------------------------------------------------------------
// Errors
// ------------------------------------------------------------------------
error NotOwner();
error NotWinner();
error ZeroAddress();
error InvalidParams();
error UnsupportedPair();
error RoundNotDrawn();
error RoundAlreadySettled();
error NothingToClaim();
error PotBelowThreshold();
error ETHTransferFailed();
error ThresholdTooLow();
error FeeTooHigh();
error NotPaused();
error IsPaused();
error RoundInPast();
error UnclaimedRoundsExist();
error ReclaimNotReady();
error OnlySelf();
error UnsupportedDecimals();
error InsufficientOutput();
error NotPrizeManager();
error InsufficientGasForReclaim();
// ------------------------------------------------------------------------
// Modifiers
// ------------------------------------------------------------------------
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
/// @dev The owner or any address on the prizeManager allowlist.
modifier onlyPrizeManager() {
if (msg.sender != owner && !prizeManager[msg.sender]) revert NotPrizeManager();
_;
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
/// @notice Deploy GSwap for a single token/ETH pair. The contract starts paused; the owner
/// must call unpause() to enable swaps.
/// @param _v3Router The Uniswap V3 SwapRouter that swaps are forwarded to.
/// @param _weth The WETH9 contract used as the ETH-side asset of the pair.
/// @param _token The token traded against ETH (GrandpaCoin). Must have TOKEN_DECIMALS decimals.
/// @param _owner The initial owner.
constructor(address _v3Router, address _weth, address _token, address _owner) {
if (_v3Router == address(0) || _weth == address(0) || _token == address(0) || _owner == address(0)) {
revert ZeroAddress();
}
if (IERC20Metadata(_token).decimals() != TOKEN_DECIMALS) revert UnsupportedDecimals();
v3Router = ISwapRouter(_v3Router);
weth = _weth;
token = _token;
owner = _owner;
paused = true; // deploy in a paused state; owner unpauses to open swaps
emit OwnershipTransferred(address(0), _owner);
emit Paused();
}
// ------------------------------------------------------------------------
// Core swap entry-point
// ------------------------------------------------------------------------
/// @notice Forward a Uniswap V3 exactInputSingle swap of the configured pair, collect the ETH-side
/// fee into the pot, and register a sqrt-weighted entry for the current round.
/// @dev Buys are native-ETH in (msg.value == amountIn, tokenIn == weth, tokenOut == token).
/// Sells are token in / native-ETH out (tokenIn == token, tokenOut == weth).
/// @param params The Uniswap V3 exactInputSingle parameters. For a sell the recipient is overridden
/// to this contract so the WETH output can be captured, unwrapped, and the fee collected.
/// @return amountOut Token actually received by params.recipient on a buy (net of any token buy tax),
/// or net native ETH received on a sell.
function swap(ISwapRouter.ExactInputSingleParams calldata params)
external
payable
nonReentrant
returns (uint256 amountOut)
{
if (paused) revert IsPaused();
if (params.amountIn == 0) revert InvalidParams();
// ETH the contract legitimately holds before this swap (current pot + every committed,
// unclaimed round prize). After the swap it must hold exactly baseline + feeAmount; any
// excess is unspent ETH the router handed back on a buy and is refunded to the buyer.
uint256 baseline = address(this).balance - msg.value;
bool isBuy;
uint256 ethSideAmount; // gross ETH on the ETH side, used for entry weighting
uint256 feeAmount;
uint256 buyerRefund; // unspent ETH the router returned on a buy, paid back at the end
if (msg.value > 0) {
// BUY: native ETH in -> token out. Collect the fee from the ETH input before forwarding.
if (params.tokenIn != weth || params.tokenOut != token) revert UnsupportedPair();
if (msg.value != params.amountIn) revert InvalidParams();
isBuy = true;
ethSideAmount = msg.value;
feeAmount = (msg.value * feeBps) / BPS_DENOMINATOR;
uint256 forwardAmount = msg.value - feeAmount;
ISwapRouter.ExactInputSingleParams memory p = params;
p.amountIn = forwardAmount;
// GRANDPA taxes transfers out of its pools, so the router's amountOut (the pool's pre-tax
// output) overstates what the recipient gets. Measure the real delta and enforce the
// caller's minimum against it. The router still checks its own (pre-tax) minimum, which is
// always >= the post-tax delta, so that check can never be the binding one.
uint256 recipientBefore = IERC20(token).balanceOf(params.recipient);
// The router's pre-tax return is ignored on purpose. The balance delta cannot be inflated
// mid-call: the router is immutable, GRANDPA has no transfer hooks, and swap is nonReentrant.
// slither-disable-next-line unused-return,reentrancy-balance
v3Router.exactInputSingle{value: forwardAmount}(p);
amountOut = IERC20(token).balanceOf(params.recipient) - recipientBefore;
if (amountOut < params.amountOutMinimum) revert InsufficientOutput();
// Capture any ETH the router returned unspent (partial fills / rounding) now, before the
// auto-pay in _draw() can change the contract balance. After forwarding, the contract holds
// exactly baseline + feeAmount; the router's refund (which arrived via receive(), which never
// credits the pot) is everything above that. It is paid back to the buyer at the very end,
// after all state is settled.
buyerRefund = address(this).balance - baseline - feeAmount;
} else {
// SELL: token in -> native ETH out. Collect the fee from the ETH output after the swap.
if (params.tokenIn != token || params.tokenOut != weth) revert UnsupportedPair();
IERC20(token).safeTransferFrom(msg.sender, address(this), params.amountIn);
IERC20(token).forceApprove(address(v3Router), params.amountIn);
ISwapRouter.ExactInputSingleParams memory p = params;
p.recipient = address(this); // capture the WETH output so the fee can be collected
uint256 grossEthOut = v3Router.exactInputSingle(p);
// The router pays out WETH; unwrap it to native ETH so the pot stays ETH-denominated and
// the seller is paid in native ETH. The resulting ETH lands via receive(), which never
// credits the pot, so it is not double counted; it is accounted for explicitly below.
IWETH9(weth).withdraw(grossEthOut);
ethSideAmount = grossEthOut;
feeAmount = (grossEthOut * feeBps) / BPS_DENOMINATOR;
amountOut = grossEthOut - feeAmount;
// The net ETH is paid to the seller at the very end of this function (checks-effects-
// interactions): all pot, entry, and round state is finalized before that outbound call.
}
// Fee accrues to the pot.
pot += feeAmount;
emit FeeCollected(msg.sender, isBuy, feeAmount, pot);
// Lifetime swap stats update on every swap.
_trackLifetime(msg.sender, params.amountIn);
// Every swap earns an entry in the current round. Entries accumulate continuously from one
// draw to the next; the pot reaching potThreshold is what makes the round drawable, not entry.
uint256 roundId = currentRound;
_registerEntry(roundId, msg.sender, ethSideAmount, isBuy);
_roundEntropy[roundId] =
uint256(keccak256(abi.encodePacked(msg.sender, block.prevrandao, _roundEntropy[roundId])));
// Auto-draw: the swap that tips the pot over the threshold settles the round inline, so no
// separate draw() call is needed on the normal path (draw() remains a public fallback). The
// tipping swapper pays the one-time draw gas. This runs after the entry above, so the tipping
// swap is itself entered into the round it draws. _draw() does push the prize to the winner
// (auto-pay), but every outbound leg is gas-bounded and the round state is fully settled before
// it runs, so a hostile winner cannot revert the draw, reenter (the guard is held), or corrupt
// the seller payout / buyer refund below (both are paid by explicit amount, not balance diff;
// the buyer refund was captured before _draw). A paused swap never reaches here (it reverts at
// the top), so no auto-draw fires while paused.
if (pot >= potThreshold) {
_draw();
}
// Interactions last (checks-effects-interactions), after all state is settled.
if (!isBuy) {
// Pay the seller their net proceeds in native ETH (unwrapped above).
_sendETH(msg.sender, amountOut);
} else if (buyerRefund > 0) {
// Refund the unspent ETH captured right after the router call above.
_sendETH(msg.sender, buyerRefund);
}
}
// ------------------------------------------------------------------------
// Round lifecycle
// ------------------------------------------------------------------------
/// @notice Draw the current round once the pot has reached potThreshold. Public fallback for the
/// inline auto-draw in swap(): on the normal path the threshold-crossing swap settles the
/// round itself, but anyone may also call this directly. Picks a winner weighted by each
/// participant's sqrt entries times their live holder multiplier (see getHolderMultiplier),
/// commits the pot plus any permissionless prize boosts and the queued bonus prizes as the
/// prize, auto-pays the winner, and opens a fresh round with entries reset to zero. If the
/// round has no entrants (or only zero-weight dust entrants), there is no one to draw: this
/// is a no-op that carries the pot forward to the next entry rather than reverting or paying
/// anyone.
function draw() external nonReentrant {
_draw();
}
/// @dev Shared draw logic for the public draw() and the inline auto-draw in swap(). Both entry
/// points are nonReentrant, so this needs no guard of its own. Works while paused so a
/// drawable round can always settle.
function _draw() internal {
if (pot < potThreshold) revert PotBelowThreshold();
uint256 roundId = currentRound;
uint256 n = _participants[roundId].length;
// No entrants yet: there is no one to draw. Carry the pot (and any prizes queued for this round)
// forward by leaving the round open and untouched, rather than reverting (which would brick the
// inline auto-draw and so every future swap) or handing the prize to the owner. Unreachable on
// the normal path: the pot grows only from fees, each of which first registers the swapper
// as a participant, and receive() never credits raw sends. Kept as a safe no-op for any
// forced/degenerate state so the contract can never be bricked by an empty drawable round.
if (n == 0) return;
// Effective weight = sqrt entries * holder multiplier, sampled from each participant's live
// token balance at draw time. Computed once into memory so balanceOf is read only once each.
address[] storage parts = _participants[roundId];
uint256[] memory eff = new uint256[](n);
uint256 totalEff = 0;
for (uint256 i = 0; i < n; i++) {
uint256 w = (_entryWeight(roundId, parts[i]) * _holderMultiplierBps(parts[i])) / BPS_DENOMINATOR;
eff[i] = w;
totalEff += w;
}
// Every entrant has zero effective weight (e.g. only dust sells, whose sqrt weight is 0). There
// is no one to fairly draw and seeding would divide by zero, so carry the pot forward as above.
if (totalEff == 0) return;
Round storage r = _rounds[roundId];
uint256 weightSum = totalSqrtWeight[roundId];
// Commit the pot plus any permissionless prize boosts for this round as the prize. The boost is
// cleared so it is neither double-committed nor swept later; on the carry-over paths above it is
// left untouched and rides with the still-open round. A round's boost only ever exists while it
// is currentRound, so a boost can never leak across the round advance below.
uint256 boost = _roundBoost[roundId];
r.prizeETH = pot + boost;
pot = 0;
if (boost > 0) delete _roundBoost[roundId];
r.drawn = true;
r.drawnBlock = block.number;
// Bundle the bonus prizes queued for this round, then clear that round's queue. Prizes queued
// for future rounds are untouched.
_roundPrizeTokens[roundId] = _queuedTokens[roundId];
_roundPrizeTokenAmounts[roundId] = _queuedTokenAmounts[roundId];
_roundPrizeNFTs[roundId] = _queuedNFTs[roundId];
_roundPrizeNFTIds[roundId] = _queuedNFTIds[roundId];
delete _queuedTokens[roundId];
delete _queuedTokenAmounts[roundId];
delete _queuedNFTs[roundId];
delete _queuedNFTIds[roundId];
// Pick the winner weighted by effective weight.
uint256 seed = uint256(keccak256(abi.encode(block.prevrandao, _roundEntropy[roundId], roundId)));
uint256 target = seed % totalEff;
uint256 cumulative = 0;
address won;
for (uint256 i = 0; i < n; i++) {
cumulative += eff[i];
if (cumulative > target) {
won = parts[i];
break;
}
}
if (won == address(0)) won = parts[n - 1];
r.winner = won;
// A fee change requested while this round had participants takes effect now it is drawn.
if (feeBps != pendingFeeBps) {
feeBps = pendingFeeBps;
emit FeeBpsSet(feeBps);
}
// Open the next round.
currentRound = roundId + 1;
emit WinnerDrawn(roundId, won, n, weightSum);
// Auto-pay the prize to the winner. All round state above is finalized first (checks-effects-
// interactions); the outbound legs here are the only interactions and are gas-bounded, so a
// winner who cannot receive cannot revert or stall this inline draw. Anything that fails is
// left owed for claim() / reclaimExpired().
_autoPay(roundId, won);
}
/// @dev Best-effort push of a drawn round's prize to its winner. The ERC-20 / ERC-721 bundle is
/// delivered first as one all-or-nothing batch through a gas-capped self-call wrapped in
/// try/catch (so a reverting token or a griefing ERC-721 receiver hook cannot bubble up or
/// drain gas), then the ETH via a gas-capped low-level call. Each leg that lands is marked
/// paid; if anything is left owed the round is counted in unclaimedRounds for claim() to
/// finish. The whole round state is already settled by the caller, and both legs run inside the
/// caller's nonReentrant guard, so the winner's receive hook cannot reenter.
function _autoPay(uint256 roundId, address winner) internal {
Round storage r = _rounds[roundId];
bool hasBundle = _roundPrizeTokens[roundId].length > 0 || _roundPrizeNFTs[roundId].length > 0;
bool tokensPaid = !hasBundle;
if (hasBundle) {
try this.deliverBundle{gas: AUTO_PAY_BUNDLE_GAS_LIMIT}(roundId, winner) {
tokensPaid = true;
} catch {
tokensPaid = false;
}
}
uint256 ethAmount = r.prizeETH;
bool ethPaid = true;
if (ethAmount > 0) {
(ethPaid,) = payable(winner).call{value: ethAmount, gas: AUTO_PAY_GAS_LIMIT}("");
}
r.ethPaid = ethPaid;
r.tokensPaid = tokensPaid;
if (ethPaid && tokensPaid) {
r.settled = true;
} else {
// Something is still owed: track the round so withdrawRemaining stays gated and the winner
// can claim() the remainder (or the owner can reclaimExpired() it later).
unclaimedRounds += 1;
}
emit PrizeAutoPaid(roundId, winner, ethAmount, ethPaid, tokensPaid);
}
/// @notice Deliver a drawn round's bundled ERC-20 / ERC-721 prizes to `to`. Restricted to self-call
/// only: it exists purely as the try/catch boundary for the auto-pay bundle in _draw(), so a
/// single reverting item rolls back the whole batch (no partial delivery) and is caught.
/// @dev Not nonReentrant by design: it is invoked via an external self-call while the caller
/// (_draw via swap()/draw()) already holds the guard, so it must not trip the guard itself.
/// @param roundId The drawn round whose bundle to deliver.
/// @param to The recipient (the round winner).
function deliverBundle(uint256 roundId, address to) external {
if (msg.sender != address(this)) revert OnlySelf();
_deliverBundle(roundId, to);
}
/// @notice Fallback claim for a winner whose auto-pay did not fully land at draw time. Delivers
/// only the still-owed legs (any unpaid token/NFT bundle, then any unpaid ETH). On the
/// normal path the prize is auto-paid at the draw and this is never needed; it reverts with
/// NothingToClaim once a round is fully settled. Unlike the gas-capped auto-pay, this uses
/// full-gas transfers that revert on failure, so the winner gets the whole remainder atomically.
/// @param roundId The round to claim.
function claim(uint256 roundId) external nonReentrant {
Round storage r = _rounds[roundId];
if (!r.drawn) revert RoundNotDrawn();
if (msg.sender != r.winner) revert NotWinner();
if (r.settled) revert RoundAlreadySettled();
_settleOwed(roundId, msg.sender);
emit PrizeClaimed(roundId, msg.sender, r.prizeETH);
}
/// @notice Owner-only recovery for a prize a winner never collected. After RECLAIM_DELAY_BLOCKS
/// (~30 days) past the draw, the owner can sweep any still-owed legs of a drawn round to
/// themselves so a winner that can never receive (a self-destructed or perpetually
/// reverting contract) cannot strand the funds forever. Fully settled rounds cannot be
/// reclaimed, so a winner who already received (or claims first) is never rugged.
/// Unlike claim(), token/NFT prizes are delivered best-effort: each item is transferred on its
/// own, and an item whose transfer reverts is logged via PrizeReclaimFailed and abandoned,
/// so a broken or hostile prize token can never keep the round open (and with it block
/// withdrawRemaining). Abandoned items stay in the contract. The ETH leg still must succeed.
/// @param roundId The round to reclaim.
function reclaimExpired(uint256 roundId) external onlyOwner nonReentrant {
Round storage r = _rounds[roundId];
if (!r.drawn) revert RoundNotDrawn();
if (r.settled) revert RoundAlreadySettled();
if (block.number < r.drawnBlock + RECLAIM_DELAY_BLOCKS) revert ReclaimNotReady();
address recipient = owner;
(bool owedTokens, bool owedETH) = _markSettled(roundId);
if (owedTokens) {
_deliverBundleBestEffort(roundId, recipient);
}
if (owedETH) {
_sendETH(recipient, r.prizeETH);
}
emit PrizeReclaimed(roundId, r.winner, recipient, r.prizeETH);
}
/// @dev Deliver every still-owed leg of a drawn round to `to`, then mark the round settled and drop
/// it from unclaimedRounds. Transfers use full gas and revert on failure (the whole call rolls
/// back), so the recipient receives the entire remainder atomically. Used by claim(); a winner
/// whose bundle cannot be delivered right now keeps the round owed and can retry later.
function _settleOwed(uint256 roundId, address to) internal {
(bool owedTokens, bool owedETH) = _markSettled(roundId);
if (owedTokens) {
_deliverBundle(roundId, to);
}
if (owedETH) {
_sendETH(to, _rounds[roundId].prizeETH);
}
}
/// @dev Effects half of settling a round: record every leg as delivered, mark the round settled and
/// drop it from unclaimedRounds. Returns which legs the caller must now deliver. Reverts with
/// NothingToClaim if nothing is owed (callers have already excluded settled rounds, but this
/// keeps the helper self-guarding).
function _markSettled(uint256 roundId) internal returns (bool owedTokens, bool owedETH) {
Round storage r = _rounds[roundId];
owedTokens = !r.tokensPaid;
owedETH = !r.ethPaid && r.prizeETH > 0;
if (!owedTokens && !owedETH) revert NothingToClaim();
r.tokensPaid = true;
r.ethPaid = true;
r.settled = true;
unclaimedRounds -= 1;
}
/// @dev Best-effort delivery of a drawn round's bundle for reclaimExpired(). Each ERC-20 / ERC-721
/// item is sent through a gas-capped self-call wrapped in try/catch; a failing item emits
/// PrizeReclaimFailed and is skipped. Reverts with InsufficientGasForReclaim (rolling back the
/// whole reclaim, so the owner can retry with more gas) rather than let an under-gassed call
/// misrecord a good transfer as failed.
function _deliverBundleBestEffort(uint256 roundId, address to) internal {
address[] storage tks = _roundPrizeTokens[roundId];
uint256[] storage amts = _roundPrizeTokenAmounts[roundId];
for (uint256 i = 0; i < tks.length; i++) {
if (gasleft() < RECLAIM_MIN_GAS_PER_ITEM) revert InsufficientGasForReclaim();
try this.transferPrizeItem{gas: RECLAIM_ITEM_GAS_LIMIT}(tks[i], to, amts[i], false) {}
catch (bytes memory reason) {
emit PrizeReclaimFailed(roundId, i, tks[i], false, _truncate(reason));
}
}
address[] storage nfts = _roundPrizeNFTs[roundId];
uint256[] storage ids = _roundPrizeNFTIds[roundId];
for (uint256 i = 0; i < nfts.length; i++) {
if (gasleft() < RECLAIM_MIN_GAS_PER_ITEM) revert InsufficientGasForReclaim();
try this.transferPrizeItem{gas: RECLAIM_ITEM_GAS_LIMIT}(nfts[i], to, ids[i], true) {}
catch (bytes memory reason) {
emit PrizeReclaimFailed(roundId, i, nfts[i], true, _truncate(reason));
}
}
}
/// @notice Transfer a single prize item held by this contract to `to`. Restricted to self-call only:
/// it exists purely as the try/catch boundary for reclaimExpired()'s best-effort delivery,
/// since SafeERC20 / safeTransferFrom are not themselves try/catch-able and a raw transfer()
/// call would misreport success for tokens that return no data.
/// @dev Not nonReentrant by design: it is invoked via an external self-call while reclaimExpired()
/// already holds the guard.
/// @param asset The ERC-20 token or ERC-721 collection.
/// @param to The recipient.
/// @param amountOrId The ERC-20 amount, or the ERC-721 token id.
/// @param isERC721 Whether `asset` is an ERC-721 collection.
function transferPrizeItem(address asset, address to, uint256 amountOrId, bool isERC721) external {
if (msg.sender != address(this)) revert OnlySelf();
if (isERC721) {
IERC721(asset).safeTransferFrom(address(this), to, amountOrId);
} else {
IERC20(asset).safeTransfer(to, amountOrId);
}
}
/// @dev Transfer a drawn round's full bundled ERC-20 / ERC-721 prizes to `to`. Reverts on the first
/// failing transfer (SafeERC20 / safeTransferFrom semantics), rolling back the whole batch.
function _deliverBundle(uint256 roundId, address to) internal {
address[] storage tks = _roundPrizeTokens[roundId];
uint256[] storage amts = _roundPrizeTokenAmounts[roundId];
for (uint256 i = 0; i < tks.length; i++) {
IERC20(tks[i]).safeTransfer(to, amts[i]);
}
address[] storage nfts = _roundPrizeNFTs[roundId];
uint256[] storage ids = _roundPrizeNFTIds[roundId];
for (uint256 i = 0; i < nfts.length; i++) {
IERC721(nfts[i]).safeTransferFrom(address(this), to, ids[i]);
}
}
/// @notice Permissionlessly top up the current round's ETH prize. Anyone can call, including while
/// paused (so the launch round can be seeded). The sent ETH is added to the current round's
/// boost, held entirely separately from the pot, so it never affects the draw threshold,
/// never earns raffle entries, and never triggers a draw. It is folded into the prize when
/// that round draws and paid to the winner; if the round carries over (no entrants), the
/// boost stays with the still-open round rather than being lost. There is no msg.sender
/// bookkeeping and no entry side effect, so a boost cannot be used to gain selection weight.
function boostPrize() external payable {
if (msg.value == 0) revert InvalidParams();
uint256 roundId = currentRound;
_roundBoost[roundId] += msg.value;
emit PrizeBoosted(roundId, msg.sender, msg.value);
}
// ------------------------------------------------------------------------
// Prize managers (owner + allowlist): prize queue
// ------------------------------------------------------------------------
/// @notice Queue an ERC20 bonus prize for the current round (bundled into the next draw). Callable by
/// the owner or a prize manager; the prize is pulled from the caller.
/// @param prizeToken The ERC20 token to add as a prize.
/// @param amount The amount of the token to escrow.
function addPrize(address prizeToken, uint256 amount) external onlyPrizeManager {
_queuePrizeToken(currentRound, prizeToken, amount);
}
/// @notice Queue an ERC20 bonus prize for a specific current-or-future round.
/// @param prizeToken The ERC20 token to add as a prize.
/// @param amount The amount of the token to escrow.
/// @param roundId The round to earmark the prize for; must be >= currentRound.
function addPrizeForRound(address prizeToken, uint256 amount, uint256 roundId) external onlyPrizeManager {
if (roundId < currentRound) revert RoundInPast();
_queuePrizeToken(roundId, prizeToken, amount);
}
/// @notice Queue an ERC721 bonus prize for the current round (bundled into the next draw).
/// @param nft The ERC721 collection to add as a prize.
/// @param tokenId The token id to escrow.
function addNFTPrize(address nft, uint256 tokenId) external onlyPrizeManager {
_queuePrizeNFT(currentRound, nft, tokenId);
}
/// @notice Queue an ERC721 bonus prize for a specific current-or-future round.
/// @param nft The ERC721 collection to add as a prize.
/// @param tokenId The token id to escrow.
/// @param roundId The round to earmark the prize for; must be >= currentRound.
function addNFTPrizeForRound(address nft, uint256 tokenId, uint256 roundId) external onlyPrizeManager {
if (roundId < currentRound) revert RoundInPast();
_queuePrizeNFT(roundId, nft, tokenId);
}
// ------------------------------------------------------------------------
// Owner: prize-manager allowlist + config
// ------------------------------------------------------------------------
/// @notice Allow `manager` to queue bonus prizes (addPrize / addPrizeForRound / addNFTPrize /
/// addNFTPrizeForRound). Grants no other permission.
/// @param manager The address to allowlist, which must be non-zero.
function addPrizeManager(address manager) external onlyOwner {
if (manager == address(0)) revert ZeroAddress();
prizeManager[manager] = true;
emit PrizeManagerAdded(manager);
}
/// @notice Revoke `manager`'s permission to queue bonus prizes. Prizes it already queued stay queued.
/// @param manager The address to remove from the allowlist.
function removePrizeManager(address manager) external onlyOwner {
prizeManager[manager] = false;
emit PrizeManagerRemoved(manager);
}
/// @notice Set the pot threshold the pot must reach for the round to become drawable. If the new
/// threshold is at or below the current pot, the round becomes immediately drawable.
/// @param newThreshold The new threshold in wei, at least MIN_POT_THRESHOLD.
function setPotThreshold(uint256 newThreshold) external onlyOwner {
if (newThreshold < MIN_POT_THRESHOLD) revert ThresholdTooLow();
potThreshold = newThreshold;
emit PotThresholdSet(newThreshold);
}
/// @notice Set the swap fee. While the current round has no participants it applies immediately;
/// once the round has participants it is queued and only takes effect when that round is
/// drawn, so a round's entry pricing is fixed once entries start accruing.
/// @param newFeeBps The new fee in basis points, at most MAX_FEE_BPS.
function setFeeBps(uint256 newFeeBps) external onlyOwner {
if (newFeeBps > MAX_FEE_BPS) revert FeeTooHigh();
pendingFeeBps = newFeeBps;
if (_participants[currentRound].length == 0) {
feeBps = newFeeBps;
emit FeeBpsSet(newFeeBps);
} else {
emit FeeBpsQueued(newFeeBps);
}
}
/// @notice Transfer ownership to a new address.
/// @param newOwner The new owner, which must be non-zero.
function transferOwnership(address newOwner) external onlyOwner {
if (newOwner == address(0)) revert ZeroAddress();
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/// @notice Emergency stop: while paused, swap() reverts entirely. draw(), claim(), reclaimExpired(),
/// boostPrize(), and withdrawRemaining() still work so in-flight rounds settle, winners are
/// paid, and the prize can still be boosted.
function pause() external onlyOwner {
paused = true;
emit Paused();
}
/// @notice Re-open swaps after a pause().
function unpause() external onlyOwner {
paused = false;
emit Unpaused();
}
/// @notice Recover all uncommitted ETH (the pot plus any surplus from raw sends that receive() did
/// not credit) and every parked (undrawn) queued prize. Only callable while paused and only
/// once every drawn round is settled (unclaimedRounds == 0), so a winner who is still owed a
/// prize can never be rugged: at that point no owed prizeETH sits in the balance, so sweeping
/// the full balance touches only owner-recoverable funds. Prizes already bundled into a drawn
/// round are never touched here; the winner claims those.
function withdrawRemaining() external onlyOwner nonReentrant {
if (!paused) revert NotPaused();
if (unclaimedRounds != 0) revert UnclaimedRoundsExist();
// unclaimedRounds == 0 means every drawn round's prize has already been delivered, so the entire
// ETH balance is uncommitted: the pot, any uncommitted prize boost, and any surplus from raw
// external sends. Sweep all of it, and clear the boost bookkeeping for the open round so a later
// draw cannot commit a prize backed by ETH that is no longer here (only currentRound can hold a
// boost: boostPrize targets it and every draw clears the boost it commits).
pot = 0;
delete _roundBoost[currentRound];
uint256 ethAmount = address(this).balance;
uint256 tokenCount;
uint256 nftCount;
// Sweep every round bucket that still holds parked prizes (drawn rounds were cleared at draw).
uint256[] memory rounds = _queuedRounds;
for (uint256 i = 0; i < rounds.length; i++) {
uint256 rid = rounds[i];
address[] memory tks = _queuedTokens[rid];
uint256[] memory amts = _queuedTokenAmounts[rid];
address[] memory nfts = _queuedNFTs[rid];
uint256[] memory ids = _queuedNFTIds[rid];
delete _queuedTokens[rid];
delete _queuedTokenAmounts[rid];
delete _queuedNFTs[rid];
delete _queuedNFTIds[rid];
_roundQueued[rid] = false;
for (uint256 j = 0; j < tks.length; j++) {
IERC20(tks[j]).safeTransfer(owner, amts[j]);
tokenCount++;
}
for (uint256 j = 0; j < nfts.length; j++) {
IERC721(nfts[j]).safeTransferFrom(address(this), owner, ids[j]);
nftCount++;
}
}
delete _queuedRounds;
if (ethAmount > 0) {
_sendETH(owner, ethAmount);
}
emit WithdrawnRemaining(owner, ethAmount, tokenCount, nftCount);
}
// ------------------------------------------------------------------------
// Internal helpers
// ------------------------------------------------------------------------
/// @dev Pull an ERC20 prize in and earmark it for `roundId`. Tracks the round in _queuedRounds so
/// withdrawRemaining can later sweep it if the round is never drawn.
function _queuePrizeToken(uint256 roundId, address prizeToken, uint256 amount) internal {
if (prizeToken == address(0)) revert ZeroAddress();
if (amount == 0) revert InvalidParams();
IERC20(prizeToken).safeTransferFrom(msg.sender, address(this), amount);
_queuedTokens[roundId].push(prizeToken);
_queuedTokenAmounts[roundId].push(amount);
_trackQueuedRound(roundId);
emit PrizeQueued(roundId, prizeToken, amount, false);
}
/// @dev Pull an ERC721 prize in and earmark it for `roundId`.
function _queuePrizeNFT(uint256 roundId, address nft, uint256 tokenId) internal {
if (nft == address(0)) revert ZeroAddress();
IERC721(nft).safeTransferFrom(msg.sender, address(this), tokenId);
_queuedNFTs[roundId].push(nft);
_queuedNFTIds[roundId].push(tokenId);
_trackQueuedRound(roundId);
emit PrizeQueued(roundId, nft, tokenId, true);
}
/// @dev Record `roundId` once in the swept-on-withdraw set.
function _trackQueuedRound(uint256 roundId) internal {
if (!_roundQueued[roundId]) {
_roundQueued[roundId] = true;
_queuedRounds.push(roundId);
}
}
function _registerEntry(uint256 roundId, address user, uint256 ethVolume, bool isBuy) internal {
uint256 prevBuy = buyVolume[roundId][user];
uint256 prevSell = sellVolume[roundId][user];
if (prevBuy == 0 && prevSell == 0) {
_participants[roundId].push(user);
}
uint256 prevWeight = _sqrt(prevBuy) + _sqrt(prevSell) / 2;
if (isBuy) {
buyVolume[roundId][user] = prevBuy + ethVolume;
} else {
sellVolume[roundId][user] = prevSell + ethVolume;
}
uint256 newWeight = _sqrt(buyVolume[roundId][user]) + _sqrt(sellVolume[roundId][user]) / 2;
// newWeight >= prevWeight because volumes only ever increase.
totalSqrtWeight[roundId] += (newWeight - prevWeight);
emit EntryRegistered(roundId, user, isBuy, ethVolume, newWeight);
}
/// @dev Buys earn full sqrt-weighted entries; sells earn half.
function _entryWeight(uint256 roundId, address user) internal view returns (uint256) {
return _sqrt(buyVolume[roundId][user]) + _sqrt(sellVolume[roundId][user]) / 2;
}
/// @dev Holder multiplier in bps from a user's live GRANDPA balance, applied to sqrt entries at draw.
/// Balances below HOLDER_BONUS_FLOOR (10k tokens) give 1x (BPS_DENOMINATOR); above it the bonus
/// grows with the square of bitLength(balance / HOLDER_BONUS_FLOOR), capped at 2x.
function _holderMultiplierBps(address user) internal view returns (uint256) {
uint256 bits = _bitLength(IERC20(token).balanceOf(user) / HOLDER_BONUS_FLOOR);
uint256 m = BPS_DENOMINATOR + bits * bits * HOLDER_BONUS_COEFF;
return m > MAX_HOLDER_MULTIPLIER_BPS ? MAX_HOLDER_MULTIPLIER_BPS : m;
}
/// @dev Number of bits needed to represent x (floor(log2(x)) + 1); 0 for x == 0.
function _bitLength(uint256 x) internal pure returns (uint256 n) {
while (x > 0) {
n++;
x >>= 1;
}
}
function _trackLifetime(address user, uint256 amountIn) internal {
if (swapCount[user] == 0) {
uniqueSwappers += 1;
}
uint256 newLifetimeVolume = lifetimeVolume[user] + amountIn;
uint256 newSwapCount = swapCount[user] + 1;
lifetimeVolume[user] = newLifetimeVolume;
swapCount[user] = newSwapCount;
lastSwapBlock[user] = block.number;
totalLifetimeVolume += amountIn;
emit SwapTracked(user, amountIn, newLifetimeVolume, newSwapCount);
}
function _sendETH(address to, uint256 amount) internal {
(bool ok,) = payable(to).call{value: amount}("");
if (!ok) revert ETHTransferFailed();
}
/// @dev First MAX_REASON_LENGTH bytes of `data` (all of it if shorter).
function _truncate(bytes memory data) internal pure returns (bytes memory) {
if (data.length <= MAX_REASON_LENGTH) return data;
bytes memory out = new bytes(MAX_REASON_LENGTH);
for (uint256 i = 0; i < MAX_REASON_LENGTH; i++) {
out[i] = data[i];
}
return out;
}
/// @dev Babylonian integer square root.
function _sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
uint256 z = (x + 1) / 2;
uint256 y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
return y;
}
// ------------------------------------------------------------------------
// View helpers
// ------------------------------------------------------------------------
/// @notice Return the full record for a round.
/// @param roundId The round id.
/// @return The round record (zero-valued if the round has not been drawn).
function getRound(uint256 roundId) external view returns (Round memory) {
return _rounds[roundId];
}
/// @notice The permissionless prize boost currently accumulated for a round (added to the prize when
/// that round draws). Nonzero only for the open round; cleared to zero once the round draws.
/// @param roundId The round id.
/// @return The boosted ETH (wei) waiting to be folded into that round's prize.
function getRoundBoost(uint256 roundId) external view returns (uint256) {
return _roundBoost[roundId];
}
/// @notice Whether the current round can be drawn. The draw works even while paused, so this is
/// not gated by the pause flag.
/// @return True if the pot has reached potThreshold.
function drawable() external view returns (bool) {
return pot >= potThreshold;
}
/// @notice The number of rounds that have been drawn. Drawn rounds have ids 1..completedRounds();
/// the current (open) round is completedRounds() + 1 == currentRound.
/// @return The count of completed (drawn) rounds.
function completedRounds() external view returns (uint256) {
return currentRound - 1;
}
/// @notice The result of a completed round, for displaying history.
/// @param roundId The round id (1..completedRounds()).
/// @return winner The drawn winner (address(0) if the round has not been drawn).
/// @return prizeETH The ETH prize committed to that round.
/// @return participantCount The number of unique participants in that round.
/// @return drawnAtBlock The block number at which the round was drawn (0 if not drawn).
function getRoundResult(uint256 roundId)
external
view
returns (address winner, uint256 prizeETH, uint256 participantCount, uint256 drawnAtBlock)
{
Round storage r = _rounds[roundId];
return (r.winner, r.prizeETH, _participants[roundId].length, r.drawnBlock);
}
/// @notice The sqrt-weighted entry weight a user holds in a round (full for buys, half for sells).
/// @param roundId The round id.
/// @param user The participant address.
/// @return The user's current entry weight (before the holder multiplier).
function getEntries(uint256 roundId, address user) external view returns (uint256) {
return _entryWeight(roundId, user);
}
/// @notice The user's current holder multiplier in bps, derived from their live GRANDPA balance.
/// 10000 = 1x (no bonus below HOLDER_BONUS_FLOOR, ~10k tokens), rising with holdings to
/// the MAX_HOLDER_MULTIPLIER_BPS (20000 = 2x) cap around 5M tokens. Sampled at draw time,
/// so it tracks the live balance, not the balance at swap time.
/// @param user The address to price.
/// @return bps The multiplier in basis points (10000 = 1x).
function getHolderMultiplier(address user) external view returns (uint256 bps) {
return _holderMultiplierBps(user);
}
/// @notice The user's effective weight for the current round: sqrt entries times the live holder
/// multiplier. This is what the draw actually weights selection by.
/// @param user The participant address.
/// @return The user's effective (multiplier-adjusted) weight in the current round.
function getEffectiveWeight(address user) external view returns (uint256) {
return (_entryWeight(currentRound, user) * _holderMultiplierBps(user)) / BPS_DENOMINATOR;
}
/// @notice The ordered list of unique participants in a round.
/// @param roundId The round id.
/// @return The participant addresses.
function getParticipants(uint256 roundId) external view returns (address[] memory) {
return _participants[roundId];
}
/// @notice The number of unique participants in a round.
/// @param roundId The round id.
/// @return The participant count.
function getParticipantCount(uint256 roundId) external view returns (uint256) {
return _participants[roundId].length;
}
/// @notice The ERC20 bonus prizes bundled into a drawn round.
/// @param roundId The round id.
/// @return tokens The prize token addresses.
/// @return amounts The prize amounts, index-aligned with tokens.
function getRoundPrizeTokens(uint256 roundId)
external
view
returns (address[] memory tokens, uint256[] memory amounts)
{
return (_roundPrizeTokens[roundId], _roundPrizeTokenAmounts[roundId]);
}
/// @notice The ERC721 bonus prizes bundled into a drawn round.
/// @param roundId The round id.
/// @return nfts The prize collection addresses.
/// @return ids The prize token ids, index-aligned with nfts.
function getRoundPrizeNFTs(uint256 roundId) external view returns (address[] memory nfts, uint256[] memory ids) {
return (_roundPrizeNFTs[roundId], _roundPrizeNFTIds[roundId]);
}
/// @notice The ERC20 prizes currently queued for a specific round (bundled when that round draws).
/// @param roundId The round id.
/// @return tokens The queued token addresses.
/// @return amounts The queued amounts, index-aligned with tokens.
function getQueuedPrizesForRound(uint256 roundId)
external
view
returns (address[] memory tokens, uint256[] memory amounts)
{
return (_queuedTokens[roundId], _queuedTokenAmounts[roundId]);
}
/// @notice The ERC721 prizes currently queued for a specific round.
/// @param roundId The round id.
/// @return nfts The queued collection addresses.
/// @return ids The queued token ids, index-aligned with nfts.
function getQueuedNFTsForRound(uint256 roundId)
external
view
returns (address[] memory nfts, uint256[] memory ids)
{
return (_queuedNFTs[roundId], _queuedNFTIds[roundId]);
}
// ------------------------------------------------------------------------
// ETH inflow + ERC-721 receiver hook
// ------------------------------------------------------------------------
/// @notice Accept ETH but never credit the pot from a raw send. The pot grows only from fees
/// inside swap(), so nobody can push a round over the threshold (or guarantee being the sole
/// entrant who then triggers the draw) by sending ETH directly. ETH legitimately arrives
/// here during a swap, the WETH unwrap on a sell and any unspent router refund on a buy,
/// while the reentrancy guard is held; those are accounted for explicitly in swap(). Any
/// surplus from a raw external send is not lost: withdrawRemaining() sweeps the full balance
/// once every round is settled.
receive() external payable {}
/// @notice ERC721 receiver hook so the contract can accept queued NFT prizes via safeTransferFrom.
/// @return The IERC721Receiver.onERC721Received selector.
function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.20;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 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;
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/interfaces/ISwapRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// @notice Minimal subset of the Uniswap V3 ISwapRouter interface needed by Cauldron.
/// @dev Mirrors `ISwapRouter` from @uniswap/v3-periphery to avoid pulling in the full dependency.
interface ISwapRouter {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
}
src/interfaces/IWETH9.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// @notice Minimal WETH9 interface. The Uniswap V3 SwapRouter delivers WETH (not native ETH) on a
/// token to WETH swap, so Cauldron unwraps it to native ETH after a sell.
interface IWETH9 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.