Verified contractExactMIT
GridMining
Address0x55b7f1a2e6a9e006ade356a9eff7a2131102bb89
- Balance
0.000056 ETH
- Transactions
832
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,972,578
- Creation transaction
- 0xb6107cf194…160b559255
11 files
- contracts/GridMining.solmain36.48 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/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/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/utils/ReentrancyGuard.sol3.38 KB
contracts/GridMining.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol";
import "@chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IGwei {
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function totalMinted() external view returns (uint256);
}
interface ITreasury {
function receiveVault() external payable;
}
contract GridMining is VRFConsumerBaseV2Plus, ReentrancyGuard {
// ============ Constants ============
uint256 public constant ROUND_DURATION = 300 seconds; // 5 minutes
uint256 public constant MIN_DEPLOY = 0.0000025 ether; // per-block dust guard
uint256 public constant GRID_SIZE = 25;
uint256 public constant ADMIN_FEE_BPS = 100; // 1%
uint256 public constant VAULT_FEE_BPS = 1000; // 10%
uint256 public constant REFINING_FEE_BPS = 1000; // 10%
uint256 public constant BPS_DENOMINATOR = 10000;
uint256 public constant ONE_GWEI = 1e18;
uint256 public constant GWEI_PER_ROUND = 5 * ONE_GWEI;
uint256 public constant MIN_GWEIPOT_ACCUMULATION = ONE_GWEI / 2; // 0.5 GWEI
uint256 public constant MAX_GWEIPOT_ACCUMULATION = 5 * ONE_GWEI; // 5.0 GWEI
uint256 public gweipotAccumulation = ONE_GWEI + ONE_GWEI / 2; // 1.5 GWEI
uint256 public constant GWEIPOT_CHANCE = 625;
uint256 public constant MAX_SUPPLY = 3_000_000 * ONE_GWEI;
// ============ VRF Config ============
uint256 public vrfSubscriptionId;
bytes32 public vrfKeyHash;
uint32 public vrfCallbackGasLimit;
uint16 public vrfRequestConfirmations;
uint32 public vrfNumWords = 2; // winning block, gweipot trigger
// ============ External Contracts ============
IGwei public gweiToken;
ITreasury public treasury;
address public feeCollector;
address public autoMiner;
// ============ Board State ============
uint64 public currentRoundId;
bool public gameStarted;
uint256 public maxMinersForWeighted = 500;
// ============ Tier System ============
struct Tier {
uint256 minTotal; // inclusive lower bound on msg.value; tier[0].minTotal MUST be 0
uint16 multiplierBps; // 10000=1x
}
Tier[] public tiers;
// ============ Round State ============
struct Round {
uint256 startTime;
uint256 endTime;
uint256[25] deployed; // ETH per block
uint256 totalDeployed;
uint256 totalWinnings; // After fees, for winners to claim
uint256 winnersDeployed; // Amount on winning block (raw ETH)
uint8 winningBlock;
uint256 gweiReward; // GWEI pool minted for this round split among winners
uint256 gweipotAmount; // Gweipot payout if triggered
uint256 vrfRequestId;
bool settled;
uint256 minerCount; // Number of unique deployers this round
uint256 winnersWeighted; // Cached weighted sum on winning block
bool weightedResolved; // Guard so resolver iterates at most once per round
}
struct FeeCalc {
uint256 adminFee;
uint256 vaultAmount;
uint256 totalWinnings;
}
mapping(uint64 => Round) internal rounds;
mapping(uint256 => uint64) public vrfRequestToRound;
// ============ Miner State ============
struct Miner {
uint256 deployedMask; // Bitmask of blocks deployed to
uint256 amountPerBlock; // ETH per block
uint16 tierMultiplierBps; // Frozen at deploy; packs with checkpointed in same slot
bool checkpointed;
}
// roundId => user => Miner
mapping(uint64 => mapping(address => Miner)) public miners;
// roundId => deployIndex => deployer address
mapping(uint64 => mapping(uint256 => address)) internal minerByIndex;
// ============ Global Rewards State ============
uint256 public gweipotPool;
// Refining fee redistribution
uint256 public totalUnclaimed;
uint256 public accRefiningPerUnclaimed;
mapping(address => uint256) public userRefiningDebt;
mapping(address => uint256) public userUnclaimedGWEI;
mapping(address => uint256) public userUnclaimedETH;
mapping(address => uint256) public userRefinedGWEI;
mapping(address => uint64) public userLastRound;
// ============ Events ============
event GameStarted(uint64 indexed roundId, uint256 startTime, uint256 endTime);
event Deployed(uint64 indexed roundId, address indexed user, uint256 amountPerBlock, uint256 blockMask, uint256 totalAmount);
event ResetRequested(uint64 indexed roundId, uint256 vrfRequestId);
event RoundSettled(
uint64 indexed roundId,
uint8 winningBlock,
uint256 totalWinnings,
uint256 gweiReward,
uint256 gweipotAmount,
uint256 winnersDeployed
);
event DeployedFor(
uint64 indexed roundId,
address indexed user,
address indexed executor,
uint256 amountPerBlock,
uint256 blockMask,
uint256 totalAmount
);
event AutoMinerUpdated(address indexed oldAutoMiner, address indexed newAutoMiner);
event Checkpointed(uint64 indexed roundId, address indexed user, uint256 ethReward, uint256 gweiReward);
event ClaimedETH(address indexed user, uint256 amount);
event ClaimedGWEI(address indexed user, uint256 minedGwei, uint256 refinedGwei, uint256 fee, uint256 net);
event EmergencyVRFRequested(uint64 indexed roundId, uint256 oldRequestId, uint256 newRequestId);
event GweipotAccumulationUpdated(uint256 oldValue, uint256 newValue);
event TiersUpdated(uint256 tierCount);
event MaxMinersForWeightedUpdated(uint256 newCap);
// ============ Errors ============
error GameNotStarted();
error GameAlreadyStarted();
error RoundNotActive();
error RoundNotEnded();
error RoundAlreadySettled();
error RoundNotSettled();
error AlreadyCheckpointed();
error InvalidBlockId();
error InsufficientDeployAmount();
error NoBlocksSelected();
error AlreadyDeployedThisRound();
error NothingToClaim();
error TransferFailed();
error InvalidVRFRequest();
error MaxSupplyReached();
error VRFNotConfigured();
error VRFAlreadyRequested();
error NotAutoMiner();
error MinimumThresholdTooLow();
error EmergencyTooEarly();
error InvalidGweipotAccumulation();
error InvalidTierConfig();
// ============ Constructor ============
constructor(
address _vrfCoordinator,
address _gweiToken,
address _treasury,
address _feeCollector
) VRFConsumerBaseV2Plus(_vrfCoordinator) {
if (_treasury == address(0)) revert ZeroAddress();
if (_feeCollector == address(0)) revert ZeroAddress();
if (_gweiToken == address(0)) revert ZeroAddress();
gweiToken = IGwei(_gweiToken);
treasury = ITreasury(_treasury);
feeCollector = _feeCollector;
// Initialize default tiers (owner may adjust via setTiers())
tiers.push(Tier({minTotal: 0, multiplierBps: 10000})); // baseline 1x
tiers.push(Tier({minTotal: 0.02 ether, multiplierBps: 15000})); // 1.5x
tiers.push(Tier({minTotal: 0.10 ether, multiplierBps: 20000})); // 2x
}
// ============ Admin Functions ============
function setVRFConfig(
uint256 _subscriptionId,
bytes32 _keyHash,
uint32 _callbackGasLimit,
uint16 _requestConfirmations
) external onlyOwner {
vrfSubscriptionId = _subscriptionId;
vrfKeyHash = _keyHash;
vrfCallbackGasLimit = _callbackGasLimit;
vrfRequestConfirmations = _requestConfirmations;
}
function setFeeCollector(address _feeCollector) external onlyOwner {
if (_feeCollector == address(0)) revert ZeroAddress();
feeCollector = _feeCollector;
}
function setTreasury(address _treasury) external onlyOwner {
if (_treasury == address(0)) revert ZeroAddress();
treasury = ITreasury(_treasury);
}
function setAutoMiner(address _autoMiner) external onlyOwner {
address old = autoMiner;
autoMiner = _autoMiner;
emit AutoMinerUpdated(old, _autoMiner);
}
function setGweipotAccumulation(uint256 _accumulation) external onlyOwner {
if (_accumulation < MIN_GWEIPOT_ACCUMULATION || _accumulation > MAX_GWEIPOT_ACCUMULATION) {
revert InvalidGweipotAccumulation();
}
uint256 oldValue = gweipotAccumulation;
gweipotAccumulation = _accumulation;
emit GweipotAccumulationUpdated(oldValue, _accumulation);
}
function setMaxMinersForWeighted(uint256 _max) external onlyOwner {
if (_max < 200) revert MinimumThresholdTooLow();
maxMinersForWeighted = _max;
emit MaxMinersForWeightedUpdated(_max);
}
/**
* @notice Replace the tier schedule. Tier 0 MUST have minTotal = 0 (baseline fallback).
* @param newTiers Array of tiers, sorted ascending by minTotal and monotonic on multiplierBps.
*/
function setTiers(Tier[] calldata newTiers) external onlyOwner {
uint256 len = newTiers.length;
if (len == 0) revert InvalidTierConfig();
if (newTiers[0].minTotal != 0) revert InvalidTierConfig();
uint256 prevMin;
uint16 prevBps;
for (uint256 i; i < len; ) {
Tier calldata t = newTiers[i];
if (t.multiplierBps < 10000 || t.multiplierBps > 50000) revert InvalidTierConfig();
if (i > 0) {
if (t.minTotal <= prevMin) revert InvalidTierConfig();
if (t.multiplierBps < prevBps) revert InvalidTierConfig();
}
prevMin = t.minTotal;
prevBps = t.multiplierBps;
unchecked { ++i; }
}
delete tiers;
for (uint256 i; i < len; ) {
tiers.push(newTiers[i]);
unchecked { ++i; }
}
emit TiersUpdated(len);
}
function startFirstRound() external onlyOwner {
if (vrfSubscriptionId == 0) revert VRFNotConfigured();
if (gameStarted) revert GameAlreadyStarted();
gameStarted = true;
currentRoundId = 1;
Round storage round = rounds[1];
round.startTime = block.timestamp;
round.endTime = block.timestamp + ROUND_DURATION;
emit GameStarted(1, round.startTime, round.endTime);
}
// ============ Core Game Functions ============
/**
* @notice Deploy ETH to selected blocks in the current round
* @param blockIds Array of block IDs (0-24) to deploy to
* @dev Deploys msg.value / blockIds.length to each selected block
*/
function deploy(uint8[] calldata blockIds) external payable nonReentrant {
if (!gameStarted) revert GameNotStarted();
// Auto-checkpoint previous round
_autoCheckpointPrevious(msg.sender);
Round storage round = rounds[currentRoundId];
// Check round is active
if (block.timestamp >= round.endTime) revert RoundNotActive();
uint256 numBlocks = blockIds.length;
if (numBlocks == 0) revert NoBlocksSelected();
uint256 amountPerBlock = msg.value / numBlocks;
if (amountPerBlock < MIN_DEPLOY) revert InsufficientDeployAmount();
Miner storage miner = miners[currentRoundId][msg.sender];
// One deploy per round
if (miner.deployedMask != 0) revert AlreadyDeployedThisRound();
// Determine tier based on total msg.value
uint16 tierBps = _getTierMultiplier(msg.value);
// Assign deploy index for weighted resolution
minerByIndex[currentRoundId][round.minerCount] = msg.sender;
round.minerCount++;
uint256 blockMask;
uint256 totalAmount;
for (uint256 i; i < numBlocks; ) {
uint8 blockId = blockIds[i];
if (blockId >= GRID_SIZE) revert InvalidBlockId();
uint256 bit = 1 << blockId;
if ((blockMask & bit) != 0) revert InvalidBlockId();
blockMask |= bit;
uint256 currentDeployed = round.deployed[blockId];
round.deployed[blockId] = currentDeployed + amountPerBlock;
unchecked {
totalAmount += amountPerBlock;
++i;
}
}
// Write miner state
miner.deployedMask = blockMask;
miner.amountPerBlock = amountPerBlock;
miner.tierMultiplierBps = tierBps;
round.totalDeployed += totalAmount;
// Track user's last played round
userLastRound[msg.sender] = currentRoundId;
emit Deployed(currentRoundId, msg.sender, amountPerBlock, blockMask, totalAmount);
}
/**
* @notice Deploy ETH to selected blocks on behalf of a user (AutoMiner only)
* @param user The address to credit deposits to
* @param blockIds Array of block IDs (0-24) to deploy to
*/
function deployFor(address user, uint8[] calldata blockIds) external payable nonReentrant {
if (msg.sender != autoMiner) revert NotAutoMiner();
if (user == address(0)) revert ZeroAddress();
if (!gameStarted) revert GameNotStarted();
// Auto-checkpoint previous round for the USER
_autoCheckpointPrevious(user);
Round storage round = rounds[currentRoundId];
// Check round is active
if (block.timestamp >= round.endTime) revert RoundNotActive();
uint256 numBlocks = blockIds.length;
if (numBlocks == 0) revert NoBlocksSelected();
uint256 amountPerBlock = msg.value / numBlocks;
if (amountPerBlock < MIN_DEPLOY) revert InsufficientDeployAmount();
// Use USER's miner state
Miner storage miner = miners[currentRoundId][user];
// One deploy per round
if (miner.deployedMask != 0) revert AlreadyDeployedThisRound();
// Determine tier based on total msg.value
uint16 tierBps = _getTierMultiplier(msg.value);
// Assign deploy index for weighted resolution
minerByIndex[currentRoundId][round.minerCount] = user;
round.minerCount++;
uint256 blockMask;
uint256 totalAmount;
for (uint256 i; i < numBlocks; ) {
uint8 blockId = blockIds[i];
if (blockId >= GRID_SIZE) revert InvalidBlockId();
uint256 bit = 1 << blockId;
if ((blockMask & bit) != 0) revert InvalidBlockId();
blockMask |= bit;
uint256 currentDeployed = round.deployed[blockId];
round.deployed[blockId] = currentDeployed + amountPerBlock;
unchecked {
totalAmount += amountPerBlock;
++i;
}
}
// Write miner state
miner.deployedMask = blockMask;
miner.amountPerBlock = amountPerBlock;
miner.tierMultiplierBps = tierBps;
round.totalDeployed += totalAmount;
// Track USER's last played round
userLastRound[user] = currentRoundId;
emit DeployedFor(currentRoundId, user, msg.sender, amountPerBlock, blockMask, totalAmount);
}
/**
* @notice End the current round and request VRF
* @dev Anyone can call this after round ends
*/
function reset() external nonReentrant {
if (!gameStarted) revert GameNotStarted();
Round storage round = rounds[currentRoundId];
if (block.timestamp < round.endTime) revert RoundNotEnded();
if (round.settled) revert RoundAlreadySettled();
if (round.vrfRequestId != 0) revert VRFAlreadyRequested();
// Handle empty round
if (round.totalDeployed == 0) {
round.settled = true;
_startNextRound();
return;
}
// Request VRF
uint256 requestId = s_vrfCoordinator.requestRandomWords(
VRFV2PlusClient.RandomWordsRequest({
keyHash: vrfKeyHash,
subId: vrfSubscriptionId,
requestConfirmations: vrfRequestConfirmations,
callbackGasLimit: vrfCallbackGasLimit,
numWords: vrfNumWords,
extraArgs: VRFV2PlusClient._argsToBytes(
VRFV2PlusClient.ExtraArgsV1({nativePayment: true})
)
})
);
round.vrfRequestId = requestId;
vrfRequestToRound[requestId] = currentRoundId;
emit ResetRequested(currentRoundId, requestId);
}
function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) internal override {
uint64 roundId = vrfRequestToRound[requestId];
if (roundId == 0) return;
Round storage round = rounds[roundId];
if (round.settled) return;
uint8 winningBlock = uint8(randomWords[0] % GRID_SIZE);
round.winningBlock = winningBlock;
round.winnersDeployed = round.deployed[winningBlock];
if (round.winnersDeployed == 0) {
_settleNoWinners(roundId, round, winningBlock);
return;
}
FeeCalc memory fees = _calculateSettlementFees(round.totalDeployed, round.winnersDeployed);
round.totalWinnings = fees.totalWinnings;
_processMinting(round, randomWords);
round.settled = true;
_safeTransferETH(feeCollector, fees.adminFee);
treasury.receiveVault{value: fees.vaultAmount}();
_startNextRound();
emit RoundSettled(
roundId,
winningBlock,
round.totalWinnings,
round.gweiReward,
round.gweipotAmount,
round.winnersDeployed
);
}
function _settleNoWinners(uint64 roundId, Round storage round, uint8 winningBlock) internal {
uint256 adminFee = (round.totalDeployed * ADMIN_FEE_BPS) / BPS_DENOMINATOR;
uint256 vaultAmount = round.totalDeployed - adminFee;
round.settled = true;
_safeTransferETH(feeCollector, adminFee);
treasury.receiveVault{value: vaultAmount}();
_startNextRound();
emit RoundSettled(roundId, winningBlock, 0, 0, 0, 0);
}
function _calculateSettlementFees(uint256 totalDeployed, uint256 winnersDeployed) internal pure returns (FeeCalc memory) {
uint256 losersPool = totalDeployed - winnersDeployed;
uint256 adminFee = (totalDeployed * ADMIN_FEE_BPS) / BPS_DENOMINATOR;
uint256 losersAdminShare = (losersPool * ADMIN_FEE_BPS) / BPS_DENOMINATOR;
uint256 losersAfterAdmin = losersPool - losersAdminShare;
uint256 vaultAmount = (losersAfterAdmin * VAULT_FEE_BPS) / BPS_DENOMINATOR;
uint256 totalWinnings = losersAfterAdmin - vaultAmount;
return FeeCalc(adminFee, vaultAmount, totalWinnings);
}
function _processMinting(Round storage round, uint256[] calldata randomWords) internal {
// Cap combined mint to remaining supply. Avoid revert near MAX_SUPPLY (V-001)
uint256 remaining = MAX_SUPPLY - gweiToken.totalMinted();
uint256 mintAmount = GWEI_PER_ROUND > remaining ? remaining : GWEI_PER_ROUND;
remaining -= mintAmount;
uint256 gweipotMint = gweipotAccumulation > remaining ? remaining : gweipotAccumulation;
round.gweiReward = mintAmount;
// randomWords[1] is gweipot trigger
if (randomWords[1] % GWEIPOT_CHANCE == 0 && gweipotPool > 0) {
round.gweipotAmount = gweipotPool;
gweipotPool = 0;
}
gweipotPool += gweipotMint;
uint256 totalMint = mintAmount + gweipotMint;
if (totalMint > 0) {
gweiToken.mint(address(this), totalMint);
}
}
function _checkpoint(uint64 roundId, address user) internal {
Round storage round = rounds[roundId];
Miner storage miner = miners[roundId][user];
// Skip if already checkpointed or round not settled
if (miner.checkpointed || !round.settled) return;
uint8 winningBlock = round.winningBlock;
// Bitmask check
uint256 userDeployed = (miner.deployedMask & (1 << winningBlock)) != 0
? miner.amountPerBlock
: 0;
// If user didn't deploy to winning block, mark as checkpointed and return
if (userDeployed == 0) {
miner.checkpointed = true;
emit Checkpointed(roundId, user, 0, 0);
return;
}
uint256 winnersDeployed = round.winnersDeployed;
// Calculate ETH rewards. Proportional share of actual retained ETH
uint256 ethReward;
unchecked {
uint256 claimablePool = _getClaimablePool(round.totalDeployed, winnersDeployed);
ethReward = (claimablePool * userDeployed) / winnersDeployed;
}
// GWEI rewards weighted
_resolveWinnersWeighted(roundId, round);
uint256 gweiReward;
if (round.minerCount > maxMinersForWeighted) {
// Safety-cap fallback: raw proportional split
gweiReward = (round.gweiReward * userDeployed) / winnersDeployed;
if (round.gweipotAmount != 0) {
gweiReward += (round.gweipotAmount * userDeployed) / winnersDeployed;
}
} else {
uint256 userWeighted = (miner.amountPerBlock * miner.tierMultiplierBps) / BPS_DENOMINATOR;
uint256 winnersWeighted = round.winnersWeighted;
gweiReward = (round.gweiReward * userWeighted) / winnersWeighted;
if (round.gweipotAmount != 0) {
gweiReward += (round.gweipotAmount * userWeighted) / winnersWeighted;
}
}
miner.checkpointed = true;
// Snapshot pending refined rewards before modifying unclaimed or debt
_updateRefiningRewards(user);
// Conditional unclaimed updates
if (ethReward != 0) {
userUnclaimedETH[user] += ethReward;
}
if (gweiReward != 0) {
userUnclaimedGWEI[user] += gweiReward;
totalUnclaimed += gweiReward;
}
// Update user's refining debt
userRefiningDebt[user] = accRefiningPerUnclaimed;
emit Checkpointed(roundId, user, ethReward, gweiReward);
}
/**
* @notice Checkpoint rewards for a specific round
* @param roundId The round to checkpoint
*/
function checkpoint(uint64 roundId) external nonReentrant {
_checkpoint(roundId, msg.sender);
}
function _autoCheckpointPrevious(address user) internal {
uint64 lastRound = userLastRound[user];
if (lastRound == 0) return;
if (lastRound >= currentRoundId) return;
_checkpoint(lastRound, user);
}
/**
* @notice Claim accumulated ETH rewards
*/
function claimETH() external nonReentrant {
// Auto-checkpoint previous round
_autoCheckpointPrevious(msg.sender);
uint256 amount = userUnclaimedETH[msg.sender];
if (amount == 0) revert NothingToClaim();
// Safety net: cap at contract balance to prevent revert from rounding dust
uint256 balance = address(this).balance;
if (amount > balance) {
amount = balance;
}
userUnclaimedETH[msg.sender] = 0;
_safeTransferETH(msg.sender, amount);
emit ClaimedETH(msg.sender, amount);
}
/**
* @notice Claim accumulated GWEI rewards with refining fee
*/
function claimGWEI() external nonReentrant {
// Auto-checkpoint previous round
_autoCheckpointPrevious(msg.sender);
// First, update user's refining bonus
_updateRefiningRewards(msg.sender);
uint256 minedGWEI = userUnclaimedGWEI[msg.sender];
uint256 refinedGWEI = userRefinedGWEI[msg.sender];
uint256 gross = minedGWEI + refinedGWEI;
if (gross == 0) revert NothingToClaim();
// Calculate refining fee (only on mined, not on refined bonus)
uint256 fee = 0;
if (minedGWEI > 0 && totalUnclaimed > 0) {
fee = (minedGWEI * REFINING_FEE_BPS) / BPS_DENOMINATOR;
// Distribute fee to remaining unclaimed holders
uint256 remainingUnclaimed = totalUnclaimed - minedGWEI;
if (remainingUnclaimed > 0) {
accRefiningPerUnclaimed += (fee * 1e18) / remainingUnclaimed;
} else {
// No other unclaimed holders. Burn the fee instead of losing it
gweiToken.burn(fee);
}
}
uint256 net = gross - fee;
// Safety net: cap at contract GWEI balance to prevent revert from rounding dust
uint256 contractGweiBalance = IERC20(address(gweiToken)).balanceOf(address(this));
if (net > contractGweiBalance) {
net = contractGweiBalance;
}
// Update state
totalUnclaimed -= minedGWEI;
userUnclaimedGWEI[msg.sender] = 0;
userRefinedGWEI[msg.sender] = 0;
userRefiningDebt[msg.sender] = accRefiningPerUnclaimed;
// Transfer GWEI
require(IERC20(address(gweiToken)).transfer(msg.sender, net), "Transfer failed");
emit ClaimedGWEI(msg.sender, minedGWEI, refinedGWEI, fee, net);
}
/**
* @notice Re-request VRF if the original request wasn't fulfilled within 1 hour
* @dev Anyone can call this after the timeout period
*/
function emergencyResetVRF() external nonReentrant {
if (!gameStarted) revert GameNotStarted();
Round storage round = rounds[currentRoundId];
// Must have a pending VRF request
if (round.vrfRequestId == 0) revert InvalidVRFRequest();
// Must not be already settled
if (round.settled) revert RoundAlreadySettled();
// Must be at least 1 hour since round ended
if (block.timestamp < round.endTime + 1 hours) revert EmergencyTooEarly();
// Clear old request mapping
uint256 oldRequestId = round.vrfRequestId;
delete vrfRequestToRound[oldRequestId];
// Request new VRF
uint256 newRequestId = s_vrfCoordinator.requestRandomWords(
VRFV2PlusClient.RandomWordsRequest({
keyHash: vrfKeyHash,
subId: vrfSubscriptionId,
requestConfirmations: vrfRequestConfirmations,
callbackGasLimit: vrfCallbackGasLimit,
numWords: vrfNumWords,
extraArgs: VRFV2PlusClient._argsToBytes(
VRFV2PlusClient.ExtraArgsV1({nativePayment: true})
)
})
);
// Update mappings
round.vrfRequestId = newRequestId;
vrfRequestToRound[newRequestId] = currentRoundId;
emit EmergencyVRFRequested(currentRoundId, oldRequestId, newRequestId);
}
// ============ Internal Functions ============
function _startNextRound() internal {
currentRoundId += 1;
Round storage nextRound = rounds[currentRoundId];
nextRound.startTime = block.timestamp;
nextRound.endTime = block.timestamp + ROUND_DURATION;
emit GameStarted(currentRoundId, nextRound.startTime, nextRound.endTime);
}
/**
* @notice Tier lookup by total msg.value. Walks from highest tier down; tier 0 (minTotal=0) always matches.
*/
function _getTierMultiplier(uint256 totalDeploy) internal view returns (uint16 bps) {
Tier[] storage t = tiers;
for (uint256 i = t.length; i > 0; ) {
unchecked { --i; }
if (totalDeploy >= t[i].minTotal) return t[i].multiplierBps;
}
// Defensive fallback
return 10000;
}
/**
* @notice Resolve sum of weighted deployments on winning block
* @dev First checkpointer pays the iteration cost; subsequent checkpoints read the cached value.
* Above maxMinersForWeighted, falls back to raw winnersDeployed so GWEI splits like raw proportional.
*/
function _resolveWinnersWeighted(uint64 roundId, Round storage round) internal {
if (round.weightedResolved) return;
round.weightedResolved = true;
// Safety cap: beyond this, skip tier weighting for the round
if (round.minerCount > maxMinersForWeighted) {
round.winnersWeighted = round.winnersDeployed;
return;
}
uint256 winningBit = 1 << round.winningBlock;
uint256 sum;
uint256 count = round.minerCount;
for (uint256 i; i < count; ) {
address minerAddr = minerByIndex[roundId][i];
Miner storage m = miners[roundId][minerAddr];
if ((m.deployedMask & winningBit) != 0) {
sum += (m.amountPerBlock * m.tierMultiplierBps) / BPS_DENOMINATOR;
}
unchecked { ++i; }
}
round.winnersWeighted = sum;
}
/**
* @notice View-only mirror of _resolveWinnersWeighted for getTotalPendingRewards preview.
*/
function _viewWinnersWeighted(uint64 roundId, Round storage round) internal view returns (uint256) {
if (round.weightedResolved) return round.winnersWeighted;
if (round.minerCount > maxMinersForWeighted) return round.winnersDeployed;
uint256 winningBit = 1 << round.winningBlock;
uint256 sum;
uint256 count = round.minerCount;
for (uint256 i; i < count; ) {
address minerAddr = minerByIndex[roundId][i];
Miner storage m = miners[roundId][minerAddr];
if ((m.deployedMask & winningBit) != 0) {
sum += (m.amountPerBlock * m.tierMultiplierBps) / BPS_DENOMINATOR;
}
unchecked { ++i; }
}
return sum;
}
function _getClaimablePool(uint256 totalDeployed, uint256 winnersDeployed) internal pure returns (uint256) {
uint256 adminFee = (totalDeployed * ADMIN_FEE_BPS) / BPS_DENOMINATOR;
uint256 losersPool = totalDeployed - winnersDeployed;
uint256 losersAdminShare = (losersPool * ADMIN_FEE_BPS) / BPS_DENOMINATOR;
uint256 vaultAmount = ((losersPool - losersAdminShare) * VAULT_FEE_BPS) / BPS_DENOMINATOR;
return totalDeployed - adminFee - vaultAmount;
}
function _updateRefiningRewards(address user) internal {
uint256 unclaimed = userUnclaimedGWEI[user];
if (unclaimed == 0) return;
uint256 accumulatedPerToken = accRefiningPerUnclaimed - userRefiningDebt[user];
uint256 pending = (unclaimed * accumulatedPerToken) / 1e18;
userRefinedGWEI[user] += pending;
userRefiningDebt[user] = accRefiningPerUnclaimed;
}
function _safeTransferETH(address to, uint256 amount) internal {
(bool success, ) = to.call{value: amount}("");
if (!success) revert TransferFailed();
}
// ============ View Functions ============
function getRound(uint64 roundId) external view returns (
uint256 startTime,
uint256 endTime,
uint256 totalDeployed,
uint256 totalWinnings,
uint256 winnersDeployed,
uint8 winningBlock,
uint256 gweiReward,
uint256 gweipotAmount,
uint256 minerCount,
bool settled
) {
Round storage round = rounds[roundId];
return (
round.startTime,
round.endTime,
round.totalDeployed,
round.totalWinnings,
round.winnersDeployed,
round.winningBlock,
round.gweiReward,
round.gweipotAmount,
round.minerCount,
round.settled
);
}
function getRoundDeployed(uint64 roundId) external view returns (uint256[25] memory) {
return rounds[roundId].deployed;
}
function getMinerInfo(uint64 roundId, address user) external view returns (
uint256 deployedMask,
uint256 amountPerBlock,
uint16 tierMultiplierBps,
bool checkpointed
) {
Miner storage miner = miners[roundId][user];
return (miner.deployedMask, miner.amountPerBlock, miner.tierMultiplierBps, miner.checkpointed);
}
function getTiers() external view returns (Tier[] memory) {
return tiers;
}
function getPendingETH(address user) external view returns (uint256) {
return userUnclaimedETH[user];
}
function getPendingGWEI(address user) external view returns (uint256 gross, uint256 fee, uint256 net) {
uint256 minedGWEI = userUnclaimedGWEI[user];
// Calculate pending refining bonus
uint256 accumulatedPerToken = accRefiningPerUnclaimed - userRefiningDebt[user];
uint256 pendingRefined = (minedGWEI * accumulatedPerToken) / 1e18;
uint256 refinedGWEI = userRefinedGWEI[user] + pendingRefined;
gross = minedGWEI + refinedGWEI;
// Fee only on mined
fee = (minedGWEI * REFINING_FEE_BPS) / BPS_DENOMINATOR;
net = gross - fee;
}
function getTotalPendingRewards(address user) external view returns (
uint256 pendingETH,
uint256 pendingUnrefinedGWEI,
uint256 pendingRefinedGWEI,
uint64 uncheckpointedRound
) {
// 1. Already checkpointed rewards
pendingETH = userUnclaimedETH[user];
pendingUnrefinedGWEI = userUnclaimedGWEI[user];
// 2. Refining bonus (stored + pending)
pendingRefinedGWEI = userRefinedGWEI[user]
+ (userUnclaimedGWEI[user] * (accRefiningPerUnclaimed - userRefiningDebt[user])) / 1e18;
// 3. Check for uncheckpointed round
uint64 lastRound = userLastRound[user];
if (lastRound == 0) return (pendingETH, pendingUnrefinedGWEI, pendingRefinedGWEI, 0);
Round storage round = rounds[lastRound];
Miner storage miner = miners[lastRound][user];
if (miner.checkpointed || !round.settled) {
return (pendingETH, pendingUnrefinedGWEI, pendingRefinedGWEI, 0);
}
// 4. Calculate uncheckpointed rewards
{
uint8 winningBlock = round.winningBlock;
uint256 userDeployed = (miner.deployedMask & (1 << winningBlock)) != 0
? miner.amountPerBlock
: 0;
if (userDeployed == 0) {
return (pendingETH, pendingUnrefinedGWEI, pendingRefinedGWEI, 0);
}
uncheckpointedRound = lastRound;
uint256 winnersDeployed = round.winnersDeployed;
// ETH: proportional share of actual retained ETH
pendingETH += (_getClaimablePool(round.totalDeployed, winnersDeployed) * userDeployed) / winnersDeployed;
// GWEI: weighted (view-only resolution mirror)
uint256 gweiReward;
if (round.minerCount > maxMinersForWeighted) {
// Fallback path: raw proportional
gweiReward = (round.gweiReward * userDeployed) / winnersDeployed;
if (round.gweipotAmount != 0) {
gweiReward += (round.gweipotAmount * userDeployed) / winnersDeployed;
}
} else {
uint256 userWeighted = (miner.amountPerBlock * miner.tierMultiplierBps) / BPS_DENOMINATOR;
uint256 winnersWeighted = _viewWinnersWeighted(lastRound, round);
gweiReward = (round.gweiReward * userWeighted) / winnersWeighted;
if (round.gweipotAmount != 0) {
gweiReward += (round.gweipotAmount * userWeighted) / winnersWeighted;
}
}
pendingUnrefinedGWEI += gweiReward;
}
}
function getCurrentRoundInfo() external view returns (
uint64 roundId,
uint256 startTime,
uint256 endTime,
uint256 totalDeployed,
uint256 timeRemaining,
bool isActive
) {
Round storage round = rounds[currentRoundId];
roundId = currentRoundId;
startTime = round.startTime;
endTime = round.endTime;
totalDeployed = round.totalDeployed;
timeRemaining = block.timestamp >= round.endTime ? 0 : round.endTime - block.timestamp;
isActive = gameStarted && block.timestamp < round.endTime && !round.settled;
}
// ============ Receive ============
receive() external payable {}
}
@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/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/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/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.