Verified contractExactMIT
LottoETH_GEORGE_V2_2
Address0xcadbc16e244211f1aeaa68c55d48e49cfbefeda1
- Balance
0 ETH
- Transactions
97
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- paris
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,782,180
- Creation transaction
- 0x8aa47ac4c5…bdd70b319f
21 files
- contracts/LottoETH_GEORGE_V2_2.solmain47.71 KB
- @chainlink/contracts/src/v0.8/shared/access/ConfirmedOwner.sol390 B
- @chainlink/contracts/src/v0.8/shared/access/ConfirmedOwnerWithProposal.sol2.13 KB
- @chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol645 B
- @chainlink/contracts/src/v0.8/shared/interfaces/IOwnable.sol234 B
- @chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol8.27 KB
- @chainlink/contracts/src/v0.8/vrf/dev/interfaces/IVRFCoordinatorV2Plus.sol2.14 KB
- @chainlink/contracts/src/v0.8/vrf/dev/interfaces/IVRFMigratableConsumerV2Plus.sol562 B
- @chainlink/contracts/src/v0.8/vrf/dev/interfaces/IVRFSubscriptionV2Plus.sol3.95 KB
- @chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol650 B
- @openzeppelin/contracts/interfaces/IERC1363.sol4.45 KB
- @openzeppelin/contracts/interfaces/IERC165.sol193 B
- @openzeppelin/contracts/interfaces/IERC20.sol182 B
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol13.31 KB
- @openzeppelin/contracts/utils/Context.sol963 B
- @openzeppelin/contracts/utils/Pausable.sol2.71 KB
- @openzeppelin/contracts/utils/ReentrancyGuard.sol4.77 KB
- @openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 B
- contracts/GeorgeSystemInterfaces.sol1.95 KB
contracts/LottoETH_GEORGE_V2_2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
import {VRFConsumerBaseV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol";
import {VRFV2PlusClient} from "@chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol";
import "./GeorgeSystemInterfaces.sol";
contract LottoETH_GEORGE_V2_2 is VRFConsumerBaseV2Plus, ReentrancyGuard, Pausable {
using SafeERC20 for IERC20;
uint256 public constant BASIS_POINTS = 10_000;
uint256 public constant PRIZE_BPS = 6000;
uint256 public constant HOUSE_BPS = 3000;
uint256 public constant HOLDER_REWARD_BPS = 1000;
uint16 public constant MATCH6_TIER_BPS = 4300;
uint16 public constant MATCH5_TIER_BPS = 2500;
uint16 public constant MATCH4_TIER_BPS = 2000;
uint16 public constant MATCH3_TIER_BPS = 1200;
uint8 public constant MIN_NUMBER = 1;
uint8 public constant MAX_NUMBER = 49;
uint8 public constant NUMBERS_PER_TICKET = 6;
uint8 public constant TIER_COUNT = 4;
uint8 public constant MAX_TICKETS_PER_TX = 10;
uint32 public constant MAX_TICKET_GAME_RANGE = 50;
uint256 public constant MAX_WINNER_CALC_BATCH = 500;
uint256 public constant MIN_TICKET_PRICE_USD_CENTS = 1;
uint256 public constant MAX_TICKET_PRICE_USD_CENTS = 10_000;
uint256 public constant MIN_ORACLE_STALENESS_SECONDS = 5 minutes;
uint256 public constant MAX_ORACLE_STALENESS_SECONDS = 2 days;
uint256 public constant MIN_GAME_DURATION = 5 minutes;
uint256 public constant MAX_GAME_DURATION = 30 days;
uint256 public constant MIN_CLAIM_DURATION = 1 hours;
uint256 public constant MAX_CLAIM_DURATION = 90 days;
uint256 public constant RANDOMNESS_REQUEST_RECOVERY_DELAY = 24 hours;
uint256 public ticketPriceUsdCents;
uint256 public maxOracleStalenessSeconds;
uint256 public gameDuration = 1 days;
uint256 public claimDuration = 7 days;
uint256 public houseAccruedNative;
uint256 public holderRewardNativeReserve;
uint256 public totalHolderRewardNativeReserved;
uint256 public totalHolderRewardNativeProcessed;
uint256 public totalHolderRewardPayTokenForwarded;
uint256 internal pendingRolloverNative;
bytes32 public constant BUCKET_HOUSE = keccak256("HOUSE");
bytes32 public constant BUCKET_HOLDER_REWARD = keccak256("HOLDER_REWARD");
bytes32 public constant BUCKET_PENDING_ROLLOVER = keccak256("PENDING_ROLLOVER");
bytes32 public constant BUCKET_GAME_PRIZE_POOL = keccak256("GAME_PRIZE_POOL");
bytes32 public constant BUCKET_GAME_CLAIM_RESERVE = keccak256("GAME_CLAIM_RESERVE");
address payable public houseWallet;
AggregatorV3Interface public immutable ethUsdPriceFeed;
IERC20 public immutable payToken;
IGeorgeRevenueTracker public immutable dividendTracker;
IGeorgeRouter02 public immutable router;
address public immutable wrappedNative;
struct VrfConfig {
uint256 subscriptionId;
bytes32 keyHash;
uint32 callbackGasLimit;
uint16 requestConfirmations;
bool nativePayment;
}
VrfConfig public vrfConfig;
uint32 public currentGameId;
uint256 private nextTicketId = 1;
uint256 public pendingRandomnessRequestId;
uint256 public randomnessRequestTimestamp;
struct Game {
uint32 id;
uint40 startTime;
uint40 endTime;
uint40 claimDeadline;
uint8[6] winningNumbers;
uint64 winningMask;
bool drawn;
bool winnerProcessingComplete;
bool liabilityFinalized;
uint256 prizePoolNative;
uint256 drawPrizePoolNative;
uint256 totalPrizeLiabilityNative;
uint256 claimReserveNative;
uint256 rolloverableNative;
uint32[4] winnerCounts;
uint256[4] tierBucketsNative;
uint256[4] tierPayoutPerTicketNative;
uint256[4] tierRolloverNative;
uint256 totalTickets;
uint256 randomnessRequestId;
}
struct Ticket {
address owner;
uint32 gameId;
uint40 timestamp;
uint8[6] numbers;
uint8 matchCount;
bool claimed;
bool processed;
}
mapping(uint32 => Game) public games;
mapping(uint256 => Ticket) public tickets;
mapping(uint32 => uint256[]) public gameTickets;
mapping(uint32 => mapping(address => uint256[])) public playerTickets;
mapping(uint32 => uint256) public winnerCalcCursor;
mapping(uint256 => uint32) public vrfRequestToGameId;
event GameStarted(uint32 indexed gameId, uint256 startTime, uint256 endTime, uint256 seededNative);
event VrfConfigUpdated(uint256 subscriptionId, bytes32 keyHash, uint32 callbackGasLimit, uint16 requestConfirmations, bool nativePayment);
event RandomnessRequested(uint32 indexed gameId, uint256 indexed requestId);
event RandomnessRequestRecovered(uint32 indexed gameId, uint256 indexed requestId, uint256 recoveredAt);
event RandomnessFulfilled(uint32 indexed gameId, uint256 indexed requestId, uint256 randomWord);
event NumbersDrawn(uint32 indexed gameId, uint8[6] winningNumbers);
event TicketPurchasedNative(address indexed buyer, uint256 indexed ticketId, uint32 indexed gameId, uint8[6] numbers, uint256 amountPaidNative);
event TicketRevenueAllocatedNative(uint32 indexed gameId, uint256 totalPaidNative, uint256 prizeNative, uint256 houseNative, uint256 holderRewardNative);
event PrizePoolFundedNative(uint32 indexed gameId, address indexed funder, uint256 amountNative);
event WinnerProcessed(uint32 indexed gameId, uint256 indexed ticketId, address indexed player, uint8 matchCount);
event TierLiabilityFinalized(
uint32 indexed gameId,
uint8 matchCount,
uint16 tierBps,
uint256 tierBucketNative,
uint32 winnerCount,
uint256 payoutPerTicketNative,
uint256 rolloverNative
);
event GameLiabilityFinalized(uint32 indexed gameId, uint256 liability, uint256 reserve, uint256 rolloverable);
event PrizeClaimed(address indexed winner, uint256 indexed ticketId, uint32 indexed gameId, uint256 amountNative);
event ExpiredClaimReserveSweptToHouse(uint32 indexed gameId, uint256 amountNative, uint256 timestamp);
event RolloverCarriedForward(uint32 indexed fromGameId, uint32 indexed toGameId, uint256 amountNative);
event HolderRewardNativeReserved(uint256 indexed gameId, uint256 amount);
event HolderRewardReserveProcessed(uint256 amountNative, uint256 payTokenAmount);
event HouseRevenueAccrued(uint32 indexed gameId, uint256 amountNative, uint256 totalHouseAccruedNative);
event HouseRevenueWithdrawn(address indexed to, uint256 amountNative);
event TicketPriceUsdCentsUpdated(uint256 oldPriceUsdCents, uint256 newPriceUsdCents);
event OracleStalenessUpdated(uint256 oldMaxOracleStalenessSeconds, uint256 newMaxOracleStalenessSeconds);
event HouseWalletUpdated(address indexed oldHouseWallet, address indexed newHouseWallet);
event GameDurationUpdated(uint256 oldDuration, uint256 newDuration);
event ClaimWindowUpdated(uint256 oldWindow, uint256 newWindow);
event NativeSurplusWithdrawn(address indexed to, uint256 amount, uint256 accountedNative);
event ExcessNativeWithdrawn(address indexed to, uint256 amount, uint256 reservedNative);
event ERC20Rescued(address indexed token, address indexed to, uint256 amount);
event AdminNativeBucketWithdrawn(
address indexed admin,
address indexed recipient,
bytes32 indexed bucket,
uint256 amount,
bytes32 reasonHash,
uint256 timestamp
);
constructor(
address payable _houseWallet,
address _vrfCoordinator,
VrfConfig memory _vrfConfig,
address _ethUsdPriceFeed,
uint256 _ticketPriceUsdCents,
uint256 _maxOracleStalenessSeconds,
address _payToken,
address _dividendTracker,
address _router,
address _wrappedNative
) VRFConsumerBaseV2Plus(_vrfCoordinator) {
require(_houseWallet != address(0), "Zero house");
require(_vrfCoordinator != address(0), "Zero VRF coordinator");
require(_ethUsdPriceFeed != address(0), "Zero price feed");
require(_payToken != address(0), "Zero PayToken");
require(_dividendTracker != address(0), "Zero tracker");
require(_router != address(0), "Zero router");
require(_wrappedNative != address(0), "Zero wrapped native");
houseWallet = _houseWallet;
ethUsdPriceFeed = AggregatorV3Interface(_ethUsdPriceFeed);
payToken = IERC20(_payToken);
dividendTracker = IGeorgeRevenueTracker(_dividendTracker);
router = IGeorgeRouter02(_router);
wrappedNative = _wrappedNative;
_setTicketPriceUsdCents(_ticketPriceUsdCents);
_setMaxOracleStalenessSeconds(_maxOracleStalenessSeconds);
_validatedEthUsdPrice();
_setVrfConfig(_vrfConfig);
_pause();
}
receive() external payable {
require(msg.value > 0, "No ETH");
require(currentGameId > 0, "No game");
Game storage g = games[currentGameId];
require(!g.drawn && !g.liabilityFinalized, "Game closed");
g.prizePoolNative += msg.value;
emit PrizePoolFundedNative(currentGameId, msg.sender, msg.value);
}
function tierBps() external pure returns (uint16[4] memory) {
return [MATCH6_TIER_BPS, MATCH5_TIER_BPS, MATCH4_TIER_BPS, MATCH3_TIER_BPS];
}
function setTicketPriceUsdCents(uint256 newPriceUsdCents) external onlyOwner whenPaused {
_setTicketPriceUsdCents(newPriceUsdCents);
}
function setMaxOracleStalenessSeconds(uint256 newMaxOracleStalenessSeconds) external onlyOwner whenPaused {
_setMaxOracleStalenessSeconds(newMaxOracleStalenessSeconds);
}
function setHouseWallet(address payable _houseWallet) external onlyOwner whenPaused {
require(_houseWallet != address(0), "Zero house");
emit HouseWalletUpdated(houseWallet, _houseWallet);
houseWallet = _houseWallet;
}
function setVrfConfig(VrfConfig calldata _vrfConfig) external onlyOwner whenPaused {
require(pendingRandomnessRequestId == 0, "Randomness pending");
_setVrfConfig(_vrfConfig);
}
function setGameDuration(uint256 newDuration) external onlyOwner whenPaused {
_setGameDuration(newDuration);
}
function setClaimWindow(uint256 newClaimWindow) external onlyOwner whenPaused {
_setClaimWindow(newClaimWindow);
}
function setDurations(uint256 _gameDuration, uint256 _claimDuration) external onlyOwner whenPaused {
_setGameDuration(_gameDuration);
_setClaimWindow(_claimDuration);
}
function startNewGame() external onlyOwner nonReentrant whenNotPaused {
uint32 nextGameId = currentGameId + 1;
uint256 pendingSeedNative = pendingRolloverNative;
uint256 seedNative = pendingSeedNative;
pendingRolloverNative = 0;
if (currentGameId > 0) {
Game storage prev = games[currentGameId];
require(block.timestamp >= prev.endTime, "Prev running");
require(prev.drawn, "Prev not drawn");
require(prev.liabilityFinalized, "Prev liability open");
uint256 rollover = prev.rolloverableNative;
if (rollover > 0) {
prev.rolloverableNative = 0;
prev.prizePoolNative -= rollover;
seedNative += rollover;
emit RolloverCarriedForward(currentGameId, nextGameId, rollover);
}
}
if (pendingSeedNative > 0) {
emit RolloverCarriedForward(0, nextGameId, pendingSeedNative);
}
currentGameId = nextGameId;
games[currentGameId] = Game({
id: currentGameId,
startTime: uint40(block.timestamp),
endTime: uint40(block.timestamp + gameDuration),
claimDeadline: uint40(block.timestamp + gameDuration + claimDuration),
winningNumbers: [uint8(0),0,0,0,0,0],
winningMask: 0,
drawn: false,
winnerProcessingComplete: false,
liabilityFinalized: false,
prizePoolNative: seedNative,
drawPrizePoolNative: 0,
totalPrizeLiabilityNative: 0,
claimReserveNative: 0,
rolloverableNative: 0,
winnerCounts: [uint32(0),0,0,0],
tierBucketsNative: [uint256(0),0,0,0],
tierPayoutPerTicketNative: [uint256(0),0,0,0],
tierRolloverNative: [uint256(0),0,0,0],
totalTickets: 0,
randomnessRequestId: 0
});
emit GameStarted(currentGameId, block.timestamp, block.timestamp + gameDuration, seedNative);
}
function fundPrizePool() external payable onlyOwner nonReentrant {
require(msg.value > 0, "No ETH");
require(currentGameId > 0, "No game");
Game storage g = games[currentGameId];
require(!g.drawn && !g.liabilityFinalized, "Game closed");
g.prizePoolNative += msg.value;
emit PrizePoolFundedNative(currentGameId, msg.sender, msg.value);
}
function purchaseTickets(uint8[6] calldata numbers, uint256 ticketCount)
external
payable
nonReentrant
whenNotPaused
returns (uint256 firstTicketId)
{
require(ticketCount > 0 && ticketCount <= MAX_TICKETS_PER_TX, "Bad count");
require(currentGameId > 0, "No game");
Game storage g = games[currentGameId];
require(block.timestamp < g.endTime, "Ended");
require(!g.drawn, "Drawn");
_validateNumbers(numbers);
uint256 totalCost = quoteTicketPriceNative(ticketCount);
require(msg.value == totalCost, "Incorrect ETH amount");
_allocateTicketRevenue(msg.value);
firstTicketId = nextTicketId;
uint256 amountPaidPerTicket = msg.value / ticketCount;
for (uint256 i = 0; i < ticketCount; i++) {
uint256 tid = nextTicketId++;
tickets[tid] = Ticket({
owner: msg.sender,
gameId: currentGameId,
timestamp: uint40(block.timestamp),
numbers: numbers,
matchCount: 0,
claimed: false,
processed: false
});
gameTickets[currentGameId].push(tid);
playerTickets[currentGameId][msg.sender].push(tid);
emit TicketPurchasedNative(msg.sender, tid, currentGameId, numbers, amountPaidPerTicket);
}
g.totalTickets += ticketCount;
}
function drawNumbers() external onlyOwner nonReentrant whenNotPaused returns (uint256 requestId) {
Game storage g = games[currentGameId];
require(g.id > 0, "No game");
require(block.timestamp >= g.endTime, "Still running");
require(!g.drawn, "Already drawn");
require(g.randomnessRequestId == 0, "Randomness pending");
require(pendingRandomnessRequestId == 0, "Request pending");
VrfConfig memory cfg = vrfConfig;
requestId = s_vrfCoordinator.requestRandomWords(
VRFV2PlusClient.RandomWordsRequest({
keyHash: cfg.keyHash,
subId: cfg.subscriptionId,
requestConfirmations: cfg.requestConfirmations,
callbackGasLimit: cfg.callbackGasLimit,
numWords: 1,
extraArgs: VRFV2PlusClient._argsToBytes(VRFV2PlusClient.ExtraArgsV1({nativePayment: cfg.nativePayment}))
})
);
g.randomnessRequestId = requestId;
pendingRandomnessRequestId = requestId;
randomnessRequestTimestamp = block.timestamp;
vrfRequestToGameId[requestId] = currentGameId;
emit RandomnessRequested(currentGameId, requestId);
}
function recoverExpiredRandomnessRequest(uint32 gameId) external onlyOwner nonReentrant whenPaused {
uint256 requestId = pendingRandomnessRequestId;
require(requestId != 0, "No pending request");
require(randomnessRequestTimestamp != 0, "No request timestamp");
Game storage g = games[gameId];
require(g.id == gameId && gameId != 0, "Unknown game");
require(!g.drawn, "Already drawn");
require(g.randomnessRequestId == requestId, "Request mismatch");
require(vrfRequestToGameId[requestId] == gameId, "Request game mismatch");
require(block.timestamp >= randomnessRequestTimestamp + RANDOMNESS_REQUEST_RECOVERY_DELAY, "Recovery delay active");
pendingRandomnessRequestId = 0;
g.randomnessRequestId = 0;
randomnessRequestTimestamp = 0;
delete vrfRequestToGameId[requestId];
emit RandomnessRequestRecovered(gameId, requestId, block.timestamp);
}
function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) internal override {
uint32 gameId = vrfRequestToGameId[requestId];
require(gameId != 0, "Unknown request");
require(randomWords.length == 1, "Bad random words");
Game storage g = games[gameId];
require(!g.drawn, "Already drawn");
require(g.randomnessRequestId == requestId, "Request mismatch");
uint8[6] memory win;
uint256 rnd = randomWords[0];
bool[50] memory used;
for (uint8 i = 0; i < NUMBERS_PER_TICKET; i++) {
uint8 n;
do {
rnd = uint256(keccak256(abi.encode(rnd, i)));
n = uint8((rnd % 49) + 1);
} while (used[n]);
used[n] = true;
win[i] = n;
}
_sortNumbers(win);
_setWinningNumbers(gameId, requestId, randomWords[0], win);
}
function calculateWinners(uint32 gameId) external nonReentrant whenNotPaused {
Game storage g = games[gameId];
require(g.drawn, "Not drawn");
require(!g.liabilityFinalized, "Finalized");
uint256[] storage ids = gameTickets[gameId];
uint256 len = ids.length;
require(len > 0, "No tickets");
uint256 cursor = winnerCalcCursor[gameId];
require(cursor < len, "Complete");
uint256 end = cursor + MAX_WINNER_CALC_BATCH;
if (end > len) end = len;
for (uint256 i = cursor; i < end; i++) {
uint256 tid = ids[i];
Ticket storage t = tickets[tid];
if (t.processed) continue;
uint8 matches = _countMatches(t.numbers, g.winningMask);
t.matchCount = matches;
t.processed = true;
if (matches >= 3) {
uint8 idx = _tierIndex(matches);
g.winnerCounts[idx] += 1;
emit WinnerProcessed(gameId, tid, t.owner, matches);
}
}
winnerCalcCursor[gameId] = end;
if (end == len) {
g.winnerProcessingComplete = true;
}
}
function finalizeGameLiability(uint32 gameId) external onlyOwner nonReentrant {
Game storage g = games[gameId];
require(g.drawn, "Not drawn");
require(g.winnerProcessingComplete || gameTickets[gameId].length == 0, "Processing open");
require(!g.liabilityFinalized, "Already finalized");
uint16[4] memory bps = _tierBps();
uint8[4] memory matchCounts = [uint8(6), 5, 4, 3];
uint256 drawPrizePool = g.prizePoolNative;
uint256 totalBuckets;
uint256 totalLiability;
uint256 totalRollover;
g.drawPrizePoolNative = drawPrizePool;
for (uint8 i = 0; i < TIER_COUNT; i++) {
uint256 tierBucket = (drawPrizePool * bps[i]) / BASIS_POINTS;
uint256 payoutPerTicket;
uint256 tierRollover;
if (g.winnerCounts[i] > 0) {
payoutPerTicket = tierBucket / g.winnerCounts[i];
uint256 paidTotal = payoutPerTicket * g.winnerCounts[i];
tierRollover = tierBucket - paidTotal;
totalLiability += paidTotal;
} else {
tierRollover = tierBucket;
}
totalBuckets += tierBucket;
totalRollover += tierRollover;
g.tierBucketsNative[i] = tierBucket;
g.tierPayoutPerTicketNative[i] = payoutPerTicket;
g.tierRolloverNative[i] = tierRollover;
emit TierLiabilityFinalized(
gameId,
matchCounts[i],
bps[i],
tierBucket,
g.winnerCounts[i],
payoutPerTicket,
tierRollover
);
}
totalRollover += drawPrizePool - totalBuckets;
require(totalLiability + totalRollover <= drawPrizePool, "Liability overflow");
g.totalPrizeLiabilityNative = totalLiability;
g.claimReserveNative = totalLiability;
g.rolloverableNative = totalRollover;
g.liabilityFinalized = true;
emit GameLiabilityFinalized(gameId, totalLiability, totalLiability, totalRollover);
}
function claimPrize(uint256 ticketId) external nonReentrant whenNotPaused {
Ticket storage t = tickets[ticketId];
require(t.owner == msg.sender, "Not owner");
require(!t.claimed, "Claimed");
require(t.matchCount >= 3, "No prize");
Game storage g = games[t.gameId];
require(g.liabilityFinalized, "Liability not finalized");
require(block.timestamp <= g.claimDeadline, "Claim expired");
uint8 idx = _tierIndex(t.matchCount);
uint256 amount = g.tierPayoutPerTicketNative[idx];
require(amount > 0, "No prize");
require(g.claimReserveNative >= amount, "Reserve shortfall");
t.claimed = true;
g.claimReserveNative -= amount;
g.prizePoolNative -= amount;
(bool ok, ) = payable(msg.sender).call{value: amount}("");
require(ok, "Native transfer failed");
emit PrizeClaimed(msg.sender, ticketId, t.gameId, amount);
}
function sweepExpiredClaimReserveToHouse(uint32 gameId) external onlyOwner nonReentrant {
_sweepExpiredClaimReserveToHouse(gameId, bytes32(0), false);
}
/// @notice Paused-only admin movement for house native accounting.
/// @dev Intended for stuck game recovery, manipulation response, operations, or migration. Normal game flow should not use this.
function adminWithdrawHouseNative(address payable recipient, uint256 amount, bytes32 reasonHash)
external
onlyOwner
nonReentrant
whenPaused
{
require(recipient != address(0), "Zero recipient");
require(amount > 0, "Zero amount");
require(amount <= houseAccruedNative, "Exceeds house");
houseAccruedNative -= amount;
_transferNative(recipient, amount);
emit AdminNativeBucketWithdrawn(msg.sender, recipient, BUCKET_HOUSE, amount, reasonHash, block.timestamp);
}
/// @notice Paused-only admin movement for holder reward native accounting before live holder processing or during migration.
/// @dev Admin use can move ETH from reserved buckets while paused and should be disclosed in audits/docs.
function adminWithdrawHolderRewardNative(address payable recipient, uint256 amount, bytes32 reasonHash)
external
onlyOwner
nonReentrant
whenPaused
{
require(recipient != address(0), "Zero recipient");
require(amount > 0, "Zero amount");
require(amount <= holderRewardNativeReserve, "Exceeds holder reserve");
holderRewardNativeReserve -= amount;
_transferNative(recipient, amount);
emit AdminNativeBucketWithdrawn(msg.sender, recipient, BUCKET_HOLDER_REWARD, amount, reasonHash, block.timestamp);
}
/// @notice Paused-only admin movement for pending rollover native accounting.
/// @dev Intended for stuck game recovery, manipulation response, operations, or migration. Normal game flow should not use this.
function adminWithdrawPendingRolloverNative(address payable recipient, uint256 amount, bytes32 reasonHash)
external
onlyOwner
nonReentrant
whenPaused
{
require(recipient != address(0), "Zero recipient");
require(amount > 0, "Zero amount");
require(amount <= pendingRolloverNative, "Exceeds pending rollover");
pendingRolloverNative -= amount;
_transferNative(recipient, amount);
emit AdminNativeBucketWithdrawn(msg.sender, recipient, BUCKET_PENDING_ROLLOVER, amount, reasonHash, block.timestamp);
}
/// @notice Paused-only admin movement for a specific game's native prize pool accounting.
/// @dev Protects active claim reserves. Admin use can move ETH from prize buckets while paused and should be disclosed.
function adminWithdrawGamePrizePoolNative(
uint32 gameId,
address payable recipient,
uint256 amount,
bytes32 reasonHash
)
external
onlyOwner
nonReentrant
whenPaused
{
require(recipient != address(0), "Zero recipient");
require(amount > 0, "Zero amount");
Game storage g = games[gameId];
require(g.id == gameId && gameId != 0, "Unknown game");
require(amount <= g.prizePoolNative, "Exceeds prize pool");
require(g.prizePoolNative - amount >= g.claimReserveNative, "Claim reserve protected");
g.prizePoolNative -= amount;
uint256 rolloverReduction = amount;
if (rolloverReduction > g.rolloverableNative) {
rolloverReduction = g.rolloverableNative;
}
if (rolloverReduction > 0) {
g.rolloverableNative -= rolloverReduction;
}
_transferNative(recipient, amount);
emit AdminNativeBucketWithdrawn(msg.sender, recipient, BUCKET_GAME_PRIZE_POOL, amount, reasonHash, block.timestamp);
}
/// @notice Paused-only movement of expired claim reserve into house accounting without transferring ETH out.
/// @dev Intended for finalized games after claim expiry. Normal user-facing claim flow should run before this.
function adminWithdrawExpiredClaimReserveToHouse(uint32 gameId, bytes32 reasonHash)
external
onlyOwner
nonReentrant
whenPaused
{
_sweepExpiredClaimReserveToHouse(gameId, reasonHash, true);
}
function withdrawHouseRevenue(address payable to, uint256 amount) external onlyOwner nonReentrant {
require(to != address(0), "Zero recipient");
require(amount > 0 && amount <= houseAccruedNative, "Bad amount");
uint256 protectedAfter = nativeReserve() + (houseAccruedNative - amount);
require(address(this).balance >= protectedAfter + amount, "Reserve shortfall");
houseAccruedNative -= amount;
(bool ok, ) = to.call{value: amount}("");
require(ok, "Withdraw failed");
emit HouseRevenueWithdrawn(to, amount);
}
function processHolderRewardReserve(uint256 amountNative, uint256 amountOutMin, uint256 deadline)
external
onlyOwner
nonReentrant
{
require(amountNative > 0, "Zero amount");
require(amountNative <= holderRewardNativeReserve, "Exceeds holder reserve");
require(deadline >= block.timestamp, "Expired deadline");
holderRewardNativeReserve -= amountNative;
totalHolderRewardNativeProcessed += amountNative;
address[] memory path = new address[](2);
path[0] = wrappedNative;
path[1] = address(payToken);
uint256 payTokenBefore = payToken.balanceOf(address(this));
router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amountNative}(
amountOutMin,
path,
address(this),
deadline
);
uint256 receivedFromSwap = payToken.balanceOf(address(this)) - payTokenBefore;
require(receivedFromSwap > 0, "No PayToken out");
uint256 trackerBefore = payToken.balanceOf(address(dividendTracker));
payToken.safeTransfer(address(dividendTracker), receivedFromSwap);
uint256 payTokenAmount = payToken.balanceOf(address(dividendTracker)) - trackerBefore;
require(payTokenAmount > 0, "No PayToken forwarded");
totalHolderRewardPayTokenForwarded += payTokenAmount;
dividendTracker.notifyRevenue(payTokenAmount, IGeorgeRevenueTracker.RevenueType.LOTTERY_REWARDS);
emit HolderRewardReserveProcessed(amountNative, payTokenAmount);
}
function emergencyWithdrawSurplus(uint256 amount) external onlyOwner nonReentrant whenPaused {
uint256 accounted = accountedNative();
uint256 surplus = _surplusNative(accounted);
require(amount <= surplus, "Exceeds native surplus");
(bool ok, ) = payable(owner()).call{value: amount}("");
require(ok, "Withdraw failed");
emit NativeSurplusWithdrawn(owner(), amount, accounted);
}
function getCurrentGame() external view returns (
uint32 gameId,
uint256 startTime,
uint256 endTime,
uint256 claimDeadline,
bool drawn,
bool liabilityFinalized,
uint8[6] memory winningNumbers,
uint256 prizePoolNative,
uint256 drawPrizePoolNative,
uint256 totalPrizeLiabilityNative,
uint256 claimReserveNative,
uint256 rolloverableNative,
uint32[4] memory winnerCounts,
uint256 totalTickets
) {
return getGameSummary(currentGameId);
}
// Return order preserves the canonical V2.1/V2.2 frontend ABI:
// gameId, startTime, endTime, claimDeadline, drawn, liabilityFinalized,
// winningNumbers, prizePoolNative, drawPrizePoolNative, totalPrizeLiabilityNative,
// claimReserveNative, rolloverableNative, winnerCounts, totalTickets.
function getCurrentGameSummary() external view returns (
uint32 gameId_,
uint256 startTime,
uint256 endTime,
uint256 claimDeadline,
bool drawn,
bool liabilityFinalized,
uint8[6] memory winningNumbers,
uint256 prizePoolNative,
uint256 drawPrizePoolNative,
uint256 totalPrizeLiabilityNative,
uint256 claimReserveNative,
uint256 rolloverableNative,
uint32[4] memory winnerCounts,
uint256 totalTickets
) {
return getGameSummary(currentGameId);
}
// Return order preserves the canonical V2.1/V2.2 frontend ABI:
// gameId, startTime, endTime, claimDeadline, drawn, liabilityFinalized,
// winningNumbers, prizePoolNative, drawPrizePoolNative, totalPrizeLiabilityNative,
// claimReserveNative, rolloverableNative, winnerCounts, totalTickets.
function getGameSummary(uint32 gameId) public view returns (
uint32 gameId_,
uint256 startTime,
uint256 endTime,
uint256 claimDeadline,
bool drawn,
bool liabilityFinalized,
uint8[6] memory winningNumbers,
uint256 prizePoolNative,
uint256 drawPrizePoolNative,
uint256 totalPrizeLiabilityNative,
uint256 claimReserveNative,
uint256 rolloverableNative,
uint32[4] memory winnerCounts,
uint256 totalTickets
) {
Game storage g = games[gameId];
return (
g.id,
g.startTime,
g.endTime,
g.claimDeadline,
g.drawn,
g.liabilityFinalized,
g.winningNumbers,
g.prizePoolNative,
g.drawPrizePoolNative,
g.totalPrizeLiabilityNative,
g.claimReserveNative,
g.rolloverableNative,
g.winnerCounts,
g.totalTickets
);
}
function getTierSummary(uint32 gameId) external view returns (
uint16[4] memory tierBps_,
uint256[4] memory tierBuckets,
uint32[4] memory winnerCounts,
uint256[4] memory payoutPerWinningTicket,
uint256[4] memory tierRolloverDust
) {
Game storage g = games[gameId];
return (
_tierBps(),
g.tierBucketsNative,
g.winnerCounts,
g.tierPayoutPerTicketNative,
g.tierRolloverNative
);
}
function getTicket(uint256 ticketId)
external
view
returns (
address owner,
uint32 gameId,
uint40 timestamp,
uint8[6] memory numbers,
uint8 matchCount,
bool claimed,
bool processed
)
{
Ticket storage t = tickets[ticketId];
return (
t.owner,
t.gameId,
t.timestamp,
t.numbers,
t.matchCount,
t.claimed,
t.processed
);
}
function getTicketNumbers(uint256 ticketId) external view returns (uint8[6] memory numbers) {
return tickets[ticketId].numbers;
}
function getPlayerTickets(address player, uint32 gameId) external view returns (uint256[] memory) {
return playerTickets[gameId][player];
}
function getPlayerTicketIds(address player, uint32 gameId) external view returns (uint256[] memory ticketIds) {
return playerTickets[gameId][player];
}
function getPlayerTicketsWithNumbers(address player, uint32 gameId)
external
view
returns (
uint256[] memory ticketIds,
uint8[6][] memory numbers
)
{
ticketIds = playerTickets[gameId][player];
numbers = new uint8[6][](ticketIds.length);
for (uint256 i = 0; i < ticketIds.length; i++) {
numbers[i] = tickets[ticketIds[i]].numbers;
}
}
function getPlayerTicketsInGameRange(
address player,
uint32 fromGameId,
uint32 toGameId
)
external
view
returns (
uint256[] memory ticketIds,
uint32[] memory gameIds,
uint8[6][] memory numbers
)
{
require(fromGameId != 0 && toGameId >= fromGameId, "Bad range");
require(toGameId - fromGameId + 1 <= MAX_TICKET_GAME_RANGE, "Range too large");
uint256 total;
for (uint32 gid = fromGameId; gid <= toGameId; gid++) {
total += playerTickets[gid][player].length;
}
ticketIds = new uint256[](total);
gameIds = new uint32[](total);
numbers = new uint8[6][](total);
uint256 cursor;
for (uint32 gid = fromGameId; gid <= toGameId; gid++) {
uint256[] storage ids = playerTickets[gid][player];
for (uint256 i = 0; i < ids.length; i++) {
uint256 tid = ids[i];
ticketIds[cursor] = tid;
gameIds[cursor] = gid;
numbers[cursor] = tickets[tid].numbers;
cursor++;
}
}
}
function getTicketPrize(uint256 ticketId) public view returns (uint256) {
Ticket storage t = tickets[ticketId];
if (t.matchCount < 3) return 0;
Game storage g = games[t.gameId];
if (!g.liabilityFinalized) return 0;
return g.tierPayoutPerTicketNative[_tierIndex(t.matchCount)];
}
function isTicketClaimable(uint256 ticketId) external view returns (bool claimable) {
Ticket storage t = tickets[ticketId];
if (t.owner == address(0) || t.claimed || t.matchCount < 3) return false;
Game storage g = games[t.gameId];
if (!g.liabilityFinalized || block.timestamp > g.claimDeadline) return false;
uint256 prize = getTicketPrize(ticketId);
return prize > 0 && g.claimReserveNative >= prize;
}
function getPlayerClaimableTickets(address player, uint32 gameId)
external
view
returns (
uint256[] memory ticketIds,
uint256[] memory prizes
)
{
uint256[] storage ids = playerTickets[gameId][player];
uint256 count;
for (uint256 i = 0; i < ids.length; i++) {
uint256 prize = getTicketPrize(ids[i]);
Ticket storage t = tickets[ids[i]];
Game storage g = games[t.gameId];
if (prize > 0 && !t.claimed && block.timestamp <= g.claimDeadline && g.claimReserveNative >= prize) {
count++;
}
}
ticketIds = new uint256[](count);
prizes = new uint256[](count);
uint256 cursor;
for (uint256 i = 0; i < ids.length; i++) {
uint256 tid = ids[i];
uint256 prize = getTicketPrize(tid);
Ticket storage t = tickets[tid];
Game storage g = games[t.gameId];
if (prize > 0 && !t.claimed && block.timestamp <= g.claimDeadline && g.claimReserveNative >= prize) {
ticketIds[cursor] = tid;
prizes[cursor] = prize;
cursor++;
}
}
}
function getPlayerClaimSummary(address player, uint32 gameId)
external
view
returns (
uint256 totalClaimable,
uint256 claimableTicketCount,
uint256 claimedTicketCount
)
{
uint256[] storage ids = playerTickets[gameId][player];
for (uint256 i = 0; i < ids.length; i++) {
uint256 tid = ids[i];
Ticket storage t = tickets[tid];
uint256 prize = getTicketPrize(tid);
if (t.claimed) {
claimedTicketCount++;
} else if (prize > 0 && block.timestamp <= games[t.gameId].claimDeadline) {
totalClaimable += prize;
claimableTicketCount++;
}
}
}
function getGameRandomnessRequestId(uint32 gameId) external view returns (uint256) {
return games[gameId].randomnessRequestId;
}
function quoteTicketPriceNative(uint256 ticketCount) public view returns (uint256) {
require(ticketCount > 0 && ticketCount <= MAX_TICKETS_PER_TX, "Bad count");
(uint256 ethUsdPrice, uint8 feedDecimals) = _validatedEthUsdPrice();
require(feedDecimals <= 18, "Feed decimals too high");
uint256 numerator = ticketPriceUsdCents * ticketCount * 1 ether * (10 ** uint256(feedDecimals));
uint256 denominator = ethUsdPrice * 100;
return _ceilDiv(numerator, denominator);
}
function pause() external onlyOwner { _pause(); }
function unpause() external onlyOwner { _unpause(); }
function pauseContract() external onlyOwner { _pause(); }
function unpauseContract() external onlyOwner { _unpause(); }
function nativeReserve() public view returns (uint256 reserved) {
reserved = pendingRolloverNative + holderRewardNativeReserve;
for (uint32 gid = 1; gid <= currentGameId; gid++) {
reserved += games[gid].prizePoolNative;
}
}
function accountedNative() public view returns (uint256) {
return nativeReserve() + houseAccruedNative;
}
function reservedNativeBalance() public view returns (uint256) {
return accountedNative();
}
function surplusNative() external view returns (uint256) {
return _surplusNative(accountedNative());
}
function excessNativeBalance() public view returns (uint256) {
return _surplusNative(reservedNativeBalance());
}
function rescueERC20(address token, address to, uint256 amount) external onlyOwner nonReentrant {
require(token != address(0) && to != address(0), "Zero address");
require(token != address(payToken), "Protected token");
require(amount > 0, "Zero amount");
IERC20(token).safeTransfer(to, amount);
emit ERC20Rescued(token, to, amount);
}
function emergencyWithdrawExcessNative(address payable to, uint256 amount)
external
onlyOwner
nonReentrant
whenPaused
{
require(to != address(0), "Zero recipient");
require(amount > 0, "Zero amount");
uint256 reserved = reservedNativeBalance();
require(amount <= _surplusNative(reserved), "Exceeds native excess");
(bool ok, ) = to.call{value: amount}("");
require(ok, "Withdraw failed");
emit ExcessNativeWithdrawn(to, amount, reserved);
}
function _sweepExpiredClaimReserveToHouse(uint32 gameId, bytes32 reasonHash, bool emitAdminEvent) internal {
Game storage g = games[gameId];
require(g.id == gameId && gameId != 0, "Unknown game");
require(g.liabilityFinalized, "Not finalized");
require(block.timestamp > g.claimDeadline, "Claim active");
uint256 amount = g.claimReserveNative;
require(amount > 0, "Nothing to sweep");
require(g.prizePoolNative >= amount, "Prize pool shortfall");
g.claimReserveNative = 0;
g.prizePoolNative -= amount;
houseAccruedNative += amount;
emit ExpiredClaimReserveSweptToHouse(gameId, amount, block.timestamp);
emit HouseRevenueAccrued(gameId, amount, houseAccruedNative);
if (emitAdminEvent) {
emit AdminNativeBucketWithdrawn(
msg.sender,
address(this),
BUCKET_GAME_CLAIM_RESERVE,
amount,
reasonHash,
block.timestamp
);
}
}
function _transferNative(address payable recipient, uint256 amount) internal {
(bool ok, ) = recipient.call{value: amount}("");
require(ok, "Native transfer failed");
}
function _allocateTicketRevenue(uint256 totalPaidNative) internal {
uint256 prizeNative = (totalPaidNative * PRIZE_BPS) / BASIS_POINTS;
uint256 houseNative = (totalPaidNative * HOUSE_BPS) / BASIS_POINTS;
uint256 holderNative = totalPaidNative - prizeNative - houseNative;
games[currentGameId].prizePoolNative += prizeNative;
houseAccruedNative += houseNative;
holderRewardNativeReserve += holderNative;
totalHolderRewardNativeReserved += holderNative;
emit TicketRevenueAllocatedNative(currentGameId, totalPaidNative, prizeNative, houseNative, holderNative);
emit HouseRevenueAccrued(currentGameId, houseNative, houseAccruedNative);
emit HolderRewardNativeReserved(currentGameId, holderNative);
}
function _validateNumbers(uint8[6] calldata numbers) internal pure {
for (uint8 i = 0; i < NUMBERS_PER_TICKET; i++) {
require(numbers[i] >= MIN_NUMBER && numbers[i] <= MAX_NUMBER, "Range");
if (i > 0) require(numbers[i] > numbers[i - 1], "Unique+sorted");
}
}
function _setWinningNumbers(uint32 gameId, uint256 requestId, uint256 randomWord, uint8[6] memory win) internal {
Game storage g = games[gameId];
uint64 mask;
for (uint8 i = 0; i < NUMBERS_PER_TICKET; i++) {
mask |= uint64(1) << win[i];
}
g.winningNumbers = win;
g.winningMask = mask;
g.drawn = true;
delete vrfRequestToGameId[requestId];
if (pendingRandomnessRequestId == requestId) {
pendingRandomnessRequestId = 0;
randomnessRequestTimestamp = 0;
}
emit RandomnessFulfilled(gameId, requestId, randomWord);
emit NumbersDrawn(gameId, win);
}
function _sortNumbers(uint8[6] memory numbers) internal pure {
for (uint8 i = 0; i < NUMBERS_PER_TICKET - 1; i++) {
for (uint8 j = 0; j < NUMBERS_PER_TICKET - 1 - i; j++) {
if (numbers[j] > numbers[j + 1]) {
(numbers[j], numbers[j + 1]) = (numbers[j + 1], numbers[j]);
}
}
}
}
function _countMatches(uint8[6] memory arr, uint64 mask) internal pure returns (uint8 c) {
for (uint8 i = 0; i < NUMBERS_PER_TICKET; i++) {
if (((mask >> arr[i]) & 1) == 1) c++;
}
}
function _tierIndex(uint8 matches) internal pure returns (uint8) {
require(matches >= 3 && matches <= 6, "No prize");
return 6 - matches;
}
function _tierBps() internal pure returns (uint16[4] memory) {
return [MATCH6_TIER_BPS, MATCH5_TIER_BPS, MATCH4_TIER_BPS, MATCH3_TIER_BPS];
}
function _validatedEthUsdPrice() internal view returns (uint256 price, uint8 feedDecimals) {
(
uint80 roundId,
int256 answer,
,
uint256 updatedAt,
uint80 answeredInRound
) = ethUsdPriceFeed.latestRoundData();
require(answer > 0, "Invalid oracle price");
require(updatedAt > 0, "Invalid oracle update");
require(answeredInRound >= roundId, "Stale oracle round");
require(block.timestamp - updatedAt <= maxOracleStalenessSeconds, "Stale oracle price");
price = uint256(answer);
feedDecimals = ethUsdPriceFeed.decimals();
}
function _setTicketPriceUsdCents(uint256 newPriceUsdCents) internal {
require(
newPriceUsdCents >= MIN_TICKET_PRICE_USD_CENTS &&
newPriceUsdCents <= MAX_TICKET_PRICE_USD_CENTS,
"Ticket price out of bounds"
);
emit TicketPriceUsdCentsUpdated(ticketPriceUsdCents, newPriceUsdCents);
ticketPriceUsdCents = newPriceUsdCents;
}
function _setMaxOracleStalenessSeconds(uint256 newMaxOracleStalenessSeconds) internal {
require(
newMaxOracleStalenessSeconds >= MIN_ORACLE_STALENESS_SECONDS &&
newMaxOracleStalenessSeconds <= MAX_ORACLE_STALENESS_SECONDS,
"Oracle staleness out of bounds"
);
emit OracleStalenessUpdated(maxOracleStalenessSeconds, newMaxOracleStalenessSeconds);
maxOracleStalenessSeconds = newMaxOracleStalenessSeconds;
}
function _setGameDuration(uint256 newDuration) internal {
require(newDuration >= MIN_GAME_DURATION && newDuration <= MAX_GAME_DURATION, "Game duration out of bounds");
emit GameDurationUpdated(gameDuration, newDuration);
gameDuration = newDuration;
}
function _setClaimWindow(uint256 newClaimWindow) internal {
require(newClaimWindow >= MIN_CLAIM_DURATION && newClaimWindow <= MAX_CLAIM_DURATION, "Claim window out of bounds");
emit ClaimWindowUpdated(claimDuration, newClaimWindow);
claimDuration = newClaimWindow;
}
function _setVrfConfig(VrfConfig memory _vrfConfig) internal {
require(_vrfConfig.subscriptionId != 0, "Zero subId");
require(_vrfConfig.keyHash != bytes32(0), "Zero keyHash");
require(_vrfConfig.callbackGasLimit > 0, "Zero callback gas");
require(_vrfConfig.requestConfirmations > 0, "Zero confirmations");
vrfConfig = _vrfConfig;
emit VrfConfigUpdated(
_vrfConfig.subscriptionId,
_vrfConfig.keyHash,
_vrfConfig.callbackGasLimit,
_vrfConfig.requestConfirmations,
_vrfConfig.nativePayment
);
}
function _surplusNative(uint256 accounted) internal view returns (uint256) {
uint256 balance = address(this).balance;
return balance > accounted ? balance - accounted : 0;
}
function _ceilDiv(uint256 numerator, uint256 denominator) internal pure returns (uint256) {
return numerator == 0 ? 0 : ((numerator - 1) / denominator) + 1;
}
}
@chainlink/contracts/src/v0.8/shared/access/ConfirmedOwner.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ConfirmedOwnerWithProposal} from "./ConfirmedOwnerWithProposal.sol";
/// @title The ConfirmedOwner contract
/// @notice A contract with helpers for basic contract ownership.
contract ConfirmedOwner is ConfirmedOwnerWithProposal {
constructor(
address newOwner
) ConfirmedOwnerWithProposal(newOwner, address(0)) {}
}
@chainlink/contracts/src/v0.8/shared/access/ConfirmedOwnerWithProposal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IOwnable} from "../interfaces/IOwnable.sol";
/// @title The ConfirmedOwner contract
/// @notice A contract with helpers for basic contract ownership.
contract ConfirmedOwnerWithProposal is IOwnable {
address private s_owner;
address private s_pendingOwner;
event OwnershipTransferRequested(address indexed from, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
constructor(address newOwner, address pendingOwner) {
// solhint-disable-next-line gas-custom-errors
require(newOwner != address(0), "Cannot set owner to zero");
s_owner = newOwner;
if (pendingOwner != address(0)) {
_transferOwnership(pendingOwner);
}
}
/// @notice Allows an owner to begin transferring ownership to a new address.
function transferOwnership(
address to
) public override onlyOwner {
_transferOwnership(to);
}
/// @notice Allows an ownership transfer to be completed by the recipient.
function acceptOwnership() external override {
// solhint-disable-next-line gas-custom-errors
require(msg.sender == s_pendingOwner, "Must be proposed owner");
address oldOwner = s_owner;
s_owner = msg.sender;
s_pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/// @notice Get the current owner
function owner() public view override returns (address) {
return s_owner;
}
/// @notice validate, transfer ownership, and emit relevant events
function _transferOwnership(
address to
) private {
// solhint-disable-next-line gas-custom-errors
require(to != msg.sender, "Cannot transfer to self");
s_pendingOwner = to;
emit OwnershipTransferRequested(s_owner, to);
}
/// @notice validate access
function _validateOwnership() internal view {
// solhint-disable-next-line gas-custom-errors
require(msg.sender == s_owner, "Only callable by owner");
}
/// @notice Reverts if called by anyone other than the contract owner.
modifier onlyOwner() {
_validateOwnership();
_;
}
}
@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// solhint-disable-next-line interface-starts-with-i
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(
uint80 _roundId
) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
@chainlink/contracts/src/v0.8/shared/interfaces/IOwnable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IOwnable {
function owner() external returns (address);
function transferOwnership(
address recipient
) external;
function acceptOwnership() external;
}
@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol";
import {IVRFCoordinatorV2Plus} from "./interfaces/IVRFCoordinatorV2Plus.sol";
import {IVRFMigratableConsumerV2Plus} from "./interfaces/IVRFMigratableConsumerV2Plus.sol";
/**
*
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness. It ensures 2 things:
* @dev 1. The fulfillment came from the VRFCoordinatorV2Plus.
* @dev 2. The consumer contract implements fulfillRandomWords.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBaseV2Plus, and can
* @dev initialize VRFConsumerBaseV2Plus's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumerV2Plus is VRFConsumerBaseV2Plus {
* @dev constructor(<other arguments>, address _vrfCoordinator, address _subOwner)
* @dev VRFConsumerBaseV2Plus(_vrfCoordinator, _subOwner) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash). Create a subscription, fund it
* @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
* @dev subscription management functions).
* @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
* @dev callbackGasLimit, numWords, extraArgs),
* @dev see (IVRFCoordinatorV2Plus for a description of the arguments).
*
* @dev Once the VRFCoordinatorV2Plus has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomWords method.
*
* @dev The randomness argument to fulfillRandomWords is a set of random words
* @dev generated from your requestId and the blockHash of the request.
*
* @dev If your contract could have concurrent requests open, you can use the
* @dev requestId returned from requestRandomWords to track which response is associated
* @dev with which randomness request.
* @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ.
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBaseV2Plus.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request. It is for this reason that
* @dev that you can signal to an oracle you'd like them to wait longer before
* @dev responding to the request (however this is not enforced in the contract
* @dev and so remains effective only in the case of unmodified oracle software).
*/
abstract contract VRFConsumerBaseV2Plus is IVRFMigratableConsumerV2Plus, ConfirmedOwner {
error OnlyCoordinatorCanFulfill(address have, address want);
error OnlyOwnerOrCoordinator(address have, address owner, address coordinator);
error ZeroAddress();
// s_vrfCoordinator should be used by consumers to make requests to vrfCoordinator
// so that coordinator reference is updated after migration
IVRFCoordinatorV2Plus public s_vrfCoordinator;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
*/
constructor(
address _vrfCoordinator
) ConfirmedOwner(msg.sender) {
if (_vrfCoordinator == address(0)) {
revert ZeroAddress();
}
s_vrfCoordinator = IVRFCoordinatorV2Plus(_vrfCoordinator);
}
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBaseV2Plus expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomWords the VRF output expanded to the requested number of words
*/
// solhint-disable-next-line chainlink-solidity/prefix-internal-functions-with-underscore
function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) internal virtual;
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) external {
if (msg.sender != address(s_vrfCoordinator)) {
revert OnlyCoordinatorCanFulfill(msg.sender, address(s_vrfCoordinator));
}
fulfillRandomWords(requestId, randomWords);
}
/**
* @inheritdoc IVRFMigratableConsumerV2Plus
*/
function setCoordinator(
address _vrfCoordinator
) external override onlyOwnerOrCoordinator {
if (_vrfCoordinator == address(0)) {
revert ZeroAddress();
}
s_vrfCoordinator = IVRFCoordinatorV2Plus(_vrfCoordinator);
emit CoordinatorSet(_vrfCoordinator);
}
modifier onlyOwnerOrCoordinator() {
if (msg.sender != owner() && msg.sender != address(s_vrfCoordinator)) {
revert OnlyOwnerOrCoordinator(msg.sender, owner(), address(s_vrfCoordinator));
}
_;
}
}
@chainlink/contracts/src/v0.8/vrf/dev/interfaces/IVRFCoordinatorV2Plus.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {VRFV2PlusClient} from "../libraries/VRFV2PlusClient.sol";
import {IVRFSubscriptionV2Plus} from "./IVRFSubscriptionV2Plus.sol";
// Interface that enables consumers of VRFCoordinatorV2Plus to be future-proof for upgrades
// This interface is supported by subsequent versions of VRFCoordinatorV2Plus
interface IVRFCoordinatorV2Plus is IVRFSubscriptionV2Plus {
/**
* @notice Request a set of random words.
* @param req - a struct containing following fields for randomness request:
* keyHash - Corresponds to a particular oracle job which uses
* that key for generating the VRF proof. Different keyHash's have different gas price
* ceilings, so you can select a specific one to bound your maximum per request cost.
* subId - The ID of the VRF subscription. Must be funded
* with the minimum subscription balance required for the selected keyHash.
* requestConfirmations - How many blocks you'd like the
* oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
* for why you may want to request more. The acceptable range is
* [minimumRequestBlockConfirmations, 200].
* callbackGasLimit - How much gas you'd like to receive in your
* fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
* may be slightly less than this amount because of gas used calling the function
* (argument decoding etc.), so you may need to request slightly more than you expect
* to have inside fulfillRandomWords. The acceptable range is
* [0, maxGasLimit]
* numWords - The number of uint256 random values you'd like to receive
* in your fulfillRandomWords callback. Note these numbers are expanded in a
* secure way by the VRFCoordinator from a single random value supplied by the oracle.
* extraArgs - abi-encoded extra args
* @return requestId - A unique identifier of the request. Can be used to match
* a request to a response in fulfillRandomWords.
*/
function requestRandomWords(
VRFV2PlusClient.RandomWordsRequest calldata req
) external returns (uint256 requestId);
}
@chainlink/contracts/src/v0.8/vrf/dev/interfaces/IVRFMigratableConsumerV2Plus.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice The IVRFMigratableConsumerV2Plus interface defines the
/// @notice method required to be implemented by all V2Plus consumers.
/// @dev This interface is designed to be used in VRFConsumerBaseV2Plus.
interface IVRFMigratableConsumerV2Plus {
event CoordinatorSet(address vrfCoordinator);
/// @notice Sets the VRF Coordinator address
/// @notice This method should only be callable by the coordinator or contract owner
function setCoordinator(
address vrfCoordinator
) external;
}
@chainlink/contracts/src/v0.8/vrf/dev/interfaces/IVRFSubscriptionV2Plus.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice The IVRFSubscriptionV2Plus interface defines the subscription
/// @notice related methods implemented by the V2Plus coordinator.
interface IVRFSubscriptionV2Plus {
/**
* @notice Add a consumer to a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - New consumer which can use the subscription
*/
function addConsumer(uint256 subId, address consumer) external;
/**
* @notice Remove a consumer from a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - Consumer to remove from the subscription
*/
function removeConsumer(uint256 subId, address consumer) external;
/**
* @notice Cancel a subscription
* @param subId - ID of the subscription
* @param to - Where to send the remaining LINK to
*/
function cancelSubscription(uint256 subId, address to) external;
/**
* @notice Accept subscription owner transfer.
* @param subId - ID of the subscription
* @dev will revert if original owner of subId has
* not requested that msg.sender become the new owner.
*/
function acceptSubscriptionOwnerTransfer(
uint256 subId
) external;
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @param newOwner - proposed new owner of the subscription
*/
function requestSubscriptionOwnerTransfer(uint256 subId, address newOwner) external;
/**
* @notice Create a VRF subscription.
* @return subId - A unique subscription id.
* @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
* @dev Note to fund the subscription with LINK, use transferAndCall. For example
* @dev LINKTOKEN.transferAndCall(
* @dev address(COORDINATOR),
* @dev amount,
* @dev abi.encode(subId));
* @dev Note to fund the subscription with Native, use fundSubscriptionWithNative. Be sure
* @dev to send Native with the call, for example:
* @dev COORDINATOR.fundSubscriptionWithNative{value: amount}(subId);
*/
function createSubscription() external returns (uint256 subId);
/**
* @notice Get a VRF subscription.
* @param subId - ID of the subscription
* @return balance - LINK balance of the subscription in juels.
* @return nativeBalance - native balance of the subscription in wei.
* @return reqCount - Requests count of subscription.
* @return owner - owner of the subscription.
* @return consumers - list of consumer address which are able to use this subscription.
*/
function getSubscription(
uint256 subId
)
external
view
returns (uint96 balance, uint96 nativeBalance, uint64 reqCount, address owner, address[] memory consumers);
/*
* @notice Check to see if there exists a request commitment consumers
* for all consumers and keyhashes for a given sub.
* @param subId - ID of the subscription
* @return true if there exists at least one unfulfilled request for the subscription, false
* otherwise.
*/
function pendingRequestExists(
uint256 subId
) external view returns (bool);
/**
* @notice Paginate through all active VRF subscriptions.
* @param startIndex index of the subscription to start from
* @param maxCount maximum number of subscriptions to return, 0 to return all
* @dev the order of IDs in the list is **not guaranteed**, therefore, if making successive calls, one
* @dev should consider keeping the blockheight constant to ensure a holistic picture of the contract state
*/
function getActiveSubscriptionIds(uint256 startIndex, uint256 maxCount) external view returns (uint256[] memory);
/**
* @notice Fund a subscription with native.
* @param subId - ID of the subscription
* @notice This method expects msg.value to be greater than or equal to 0.
*/
function fundSubscriptionWithNative(
uint256 subId
) external payable;
}
@chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
// End consumer library.
library VRFV2PlusClient {
// extraArgs will evolve to support new features
bytes4 public constant EXTRA_ARGS_V1_TAG = bytes4(keccak256("VRF ExtraArgsV1"));
struct ExtraArgsV1 {
bool nativePayment;
}
struct RandomWordsRequest {
bytes32 keyHash;
uint256 subId;
uint16 requestConfirmations;
uint32 callbackGasLimit;
uint32 numWords;
bytes extraArgs;
}
function _argsToBytes(
ExtraArgsV1 memory extraArgs
) internal pure returns (bytes memory bts) {
return abi.encodeWithSelector(EXTRA_ARGS_V1_TAG, extraArgs);
}
}
@openzeppelin/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
@openzeppelin/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
@openzeppelin/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 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 {
/**
* @dev An operation with an ERC-20 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 {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
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.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
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.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, 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 to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @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].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// 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;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = 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();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* 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[ERC 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);
}
contracts/GeorgeSystemInterfaces.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IGeorgeFactoryLike {
function createPair(address tokenA, address tokenB) external returns (address pair);
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
interface IGeorgeRouter02 {
function WETH() external view returns (address);
function getAmountsOut(
uint256 amountIn,
address[] calldata path
) external view returns (uint256[] memory amounts);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external payable returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
}
interface IGeorgeRevenueTracker {
enum RevenueType {
REFLECTIONS,
LOTTERY_REWARDS,
P2E_REWARDS
}
function notifyRevenue(uint256 amount, RevenueType revenueType) external;
}
interface IGeorgePayToken is IERC20 {
function distributeReflections() external payable;
function distributeRewards() external payable;
function isEligibleForRewards(address holder) external view returns (bool);
function isEligibleForLotteryBonus(address holder) external view returns (bool);
function isEligibleForP2EBonus(address holder) external view returns (bool);
}
Compiler settingsShow
{
"debug": {
"revertStrings": "strip"
},
"viaIR": true,
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.