Verified contractPartialMIT
FWACloneVRFService
Address0x7d93bd9de5dc121992ea4a59e61b2519fa1ed65d
- Balance
0.187002 ETH
- Transactions
143
- Compiler
solc 0.8.26
- Same code
1 more contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,328,830
- Creation transaction
- 0x9b28d67778…cb717f25b1
13 files
- src/userowned/FWACloneVRFService.solmain38.24 KB
- lib/chainlink-evm/contracts/src/v0.8/shared/access/ConfirmedOwner.sol390 B
- lib/chainlink-evm/contracts/src/v0.8/shared/access/ConfirmedOwnerWithProposal.sol2.13 KB
- lib/chainlink-evm/contracts/src/v0.8/shared/interfaces/IOwnable.sol234 B
- lib/chainlink-evm/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol8.27 KB
- lib/chainlink-evm/contracts/src/v0.8/vrf/dev/interfaces/IVRFCoordinatorV2Plus.sol2.14 KB
- lib/chainlink-evm/contracts/src/v0.8/vrf/dev/interfaces/IVRFCoordinatorV2PlusInternal.sol1.9 KB
- lib/chainlink-evm/contracts/src/v0.8/vrf/dev/interfaces/IVRFMigratableConsumerV2Plus.sol562 B
- lib/chainlink-evm/contracts/src/v0.8/vrf/dev/interfaces/IVRFSubscriptionV2Plus.sol3.95 KB
- lib/chainlink-evm/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol650 B
- lib/solady/src/utils/ReentrancyGuard.sol2.33 KB
- lib/solady/src/utils/SafeTransferLib.sol32.8 KB
- src/userowned/interfaces/IFWACloneFactory.sol5.73 KB
src/userowned/FWACloneVRFService.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {ReentrancyGuard} from "solady/src/utils/ReentrancyGuard.sol";
import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";
import {VRFConsumerBaseV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol";
import {IVRFCoordinatorV2PlusInternal} from
"@chainlink/contracts/src/v0.8/vrf/dev/interfaces/IVRFCoordinatorV2PlusInternal.sol";
import {VRFV2PlusClient} from "@chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol";
import {IFWACloneFactory, IFWACloneVRFHost} from "./interfaces/IFWACloneFactory.sol";
interface IFWACloneRandomnessReceiver {
function rawFulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) external;
}
/// @title FWACloneVRFService
/// @notice The sole Chainlink consumer and native-subscription treasury for every factory clone.
/// @dev A clone pays for and prepares each request before calling the coordinator-compatible
/// `requestRandomWords` facade. The service returns the real Chainlink request ID, stores the
/// authenticated result before a failure-isolated delivery attempt, and never re-requests a word.
contract FWACloneVRFService is VRFConsumerBaseV2Plus, ReentrancyGuard {
uint256 public constant BPS = 10_000;
uint32 public constant NUM_WORDS = 1;
uint32 public constant MAX_CALLBACK_GAS_LIMIT = 2_500_000;
/// @dev Gas retained after the bounded clone call for terminal storage and event emission.
uint256 internal constant DELIVERY_RETURN_GAS_RESERVE = 80_000;
enum RequestStatus {
None,
CoordinatorOutstanding,
WordStored,
EmptyWordArrayStored,
Delivered,
CoordinatorCallbackLost
}
address public immutable factory;
uint256 public immutable subscriptionId;
bytes32 public approvedVrfKeyHash;
uint16 public immutable approvedRequestConfirmations;
uint32 public immutable approvedCallbackGasLimit;
uint32 public immutable approvedRouterCallbackGasLimit;
bytes32 public immutable approvedExtraArgsHash;
uint256 public serviceGasEstimate = 1_100_000;
uint256 public serviceMarginBps = 3_000;
uint256 public serviceFlatWei;
uint256 public minimumSubscriptionBuffer;
uint256 public maxFulfillmentCostWei;
uint256 public coverageFloor;
/// @notice Zero disables the corresponding explicit request limit; coverage remains mandatory.
uint256 public maxOutstandingPerPool = 10;
uint256 public maxOutstandingGlobal = 100;
/// @notice Addresses approved by factory governance to use the reimbursed processing route.
/// Every clone's direct processor remains permissionless and unsubsidized.
mapping(address operator => bool allowed) public operators;
uint256 public maxSponsoredCount = 10;
uint256 public maxReimbursementGas = 2_100_000;
uint256 public reimbursementGasOverhead = 55_000;
uint256 public maxReimbursementBaseFeeWei = 5 gwei;
uint256 public maxReimbursementPriorityFeeWei = 1 gwei;
uint256 public maxReimbursementWei = 0.02 ether;
bool public subscriptionActive;
bool public subscriptionTerminated;
bool public requestsPaused = true;
uint256 public totalPrepared;
uint256 public totalCoordinatorOutstanding;
mapping(address pool => bool registered) public registeredPool;
mapping(address pool => uint256 credits) public preparedCredits;
mapping(address pool => uint256 outstanding) public coordinatorOutstandingFor;
/// @notice A coordinator migration resets its consumer nonce. Never reusing a gas lane prevents
/// the new coordinator from recreating a historical real request ID.
mapping(bytes32 keyHash => bool used) public usedVrfKeyHash;
mapping(uint256 requestId => address pool) public requestPool;
mapping(uint256 requestId => RequestStatus status) public requestStatus;
mapping(uint256 requestId => uint256 word) public storedRandomWord;
event TreasuryFunded(address indexed sender, uint256 amount);
event SubscriptionActivated(uint256 indexed subscriptionId, address indexed coordinator);
event PoolRegistered(address indexed pool);
event RequestFeesReceived(address indexed pool, uint256 requestCount, uint256 amount);
event RequestsPrepared(
address indexed pool,
uint256 requestCount,
uint256 poolPrepared,
uint256 poolCoordinatorOutstanding,
uint256 globalPrepared,
uint256 globalCoordinatorOutstanding
);
event RandomnessRequested(uint256 indexed requestId, address indexed pool);
event RandomnessStored(uint256 indexed requestId, address indexed pool, uint256 word, bool hasWord);
event RandomnessDeliveryDeferred(uint256 indexed requestId, address indexed pool);
event RandomnessDeliveryFailed(uint256 indexed requestId, address indexed pool);
event RandomnessDelivered(uint256 indexed requestId, address indexed pool);
event FulfillmentIgnored(uint256 indexed requestId, RequestStatus status, uint256 wordCount);
event CoordinatorRequestReconciled(uint256 indexed requestId, address indexed pool);
event SubscriptionFunded(uint256 indexed subscriptionId, uint256 amount, uint256 requiredBalance);
event SubscriptionTerminated(address indexed recoveryRecipient, uint256 serviceEthRefund);
event TerminalEthRecovered(address indexed caller, address indexed recoveryRecipient, uint256 amount);
event RequestsPausedSet(bool paused);
event RequestLimitsSet(uint256 maxPerPool, uint256 maxGlobal);
event VrfKeyHashRotated(bytes32 indexed oldKeyHash, bytes32 indexed newKeyHash, uint256 coverageFloor);
event PoolRequestConfigSynced(address indexed pool, bytes32 indexed keyHash, uint32 callbackGasLimit);
event FeeConfigSet(uint256 gasEstimate, uint256 marginBps, uint256 flatWei);
event CoverageConfigSet(uint256 minimumBuffer, uint256 maxFulfillmentCost);
event OperatorSet(address indexed operator, bool allowed);
event ReimbursementConfigSet(
uint256 maxSponsoredCount,
uint256 maxReimbursementGas,
uint256 reimbursementGasOverhead,
uint256 maxReimbursementBaseFeeWei,
uint256 maxReimbursementPriorityFeeWei,
uint256 maxReimbursementWei
);
event AcquisitionsSponsored(
address indexed operator,
address indexed pool,
uint256 processed,
uint256 reimbursableGas,
uint256 reimbursableGasPrice,
uint256 reimbursement
);
event SurplusWithdrawn(address indexed recipient, uint256 amount);
error OnlyFactory();
error OnlyOperator();
error UnknownPool();
error AlreadyRegistered();
error InvalidConfig();
error InvalidRequestTuple();
error IncorrectRequestFee();
error PoolConfigMismatch();
error PoolNotReady();
error SubscriptionNotActive();
error SubscriptionAlreadyActive();
error VrfServiceTerminated();
error SubscriptionNotOwnedByFactory();
error SubscriptionNotPristine();
error SubscriptionConsumerMismatch();
error RequestsPaused();
error PerPoolRequestLimitExceeded();
error GlobalRequestLimitExceeded();
error MissingPreparedCredit();
error DuplicateRequestId();
error InsufficientVrfCoverage();
error OutstandingCallbacks();
error InsufficientSurplus();
error NoProcessorSurplus();
error RandomnessNotDeliverable();
error CoordinatorCommitmentCheckFailed();
error CoordinatorRequestStillPending();
error VrfKeyHashAlreadyUsed();
constructor(
address factory_,
address coordinator_,
uint256 subscriptionId_,
bytes32 keyHash_,
uint16 requestConfirmations_,
uint32 poolCallbackGasLimit_,
uint32 routerCallbackGasLimit_,
uint256 minimumBuffer_,
uint256 maxFulfillmentCost_
) VRFConsumerBaseV2Plus(coordinator_) {
if (
factory_ == address(0) || factory_.code.length == 0 || coordinator_ == address(0)
|| coordinator_.code.length == 0 || subscriptionId_ == 0 || keyHash_ == bytes32(0)
|| requestConfirmations_ < 3 || requestConfirmations_ > 200 || poolCallbackGasLimit_ == 0
|| routerCallbackGasLimit_ <= poolCallbackGasLimit_ || routerCallbackGasLimit_ > MAX_CALLBACK_GAS_LIMIT
|| minimumBuffer_ == 0 || maxFulfillmentCost_ == 0
) revert InvalidConfig();
factory = factory_;
subscriptionId = subscriptionId_;
approvedVrfKeyHash = keyHash_;
usedVrfKeyHash[keyHash_] = true;
approvedRequestConfirmations = requestConfirmations_;
approvedCallbackGasLimit = poolCallbackGasLimit_;
approvedRouterCallbackGasLimit = routerCallbackGasLimit_;
approvedExtraArgsHash =
keccak256(VRFV2PlusClient._argsToBytes(VRFV2PlusClient.ExtraArgsV1({nativePayment: true})));
minimumSubscriptionBuffer = minimumBuffer_;
maxFulfillmentCostWei = maxFulfillmentCost_;
coverageFloor = maxFulfillmentCost_;
// The factory contract must explicitly accept. Governance has no factory method that can call
// the inherited generic coordinator setter; official coordinator migration remains possible.
transferOwnership(factory_);
emit RequestsPausedSet(true);
emit RequestLimitsSet(maxOutstandingPerPool, maxOutstandingGlobal);
emit FeeConfigSet(serviceGasEstimate, serviceMarginBps, serviceFlatWei);
emit CoverageConfigSet(minimumBuffer_, maxFulfillmentCost_);
emit ReimbursementConfigSet(
maxSponsoredCount,
maxReimbursementGas,
reimbursementGasOverhead,
maxReimbursementBaseFeeWei,
maxReimbursementPriorityFeeWei,
maxReimbursementWei
);
}
modifier onlyFactory() {
if (msg.sender != factory) revert OnlyFactory();
_;
}
modifier onlyOperator() {
if (!operators[msg.sender]) revert OnlyOperator();
_;
}
receive() external payable {
if (subscriptionTerminated) revert VrfServiceTerminated();
emit TreasuryFunded(msg.sender, msg.value);
}
/*//////////////////////////////////////////////////////////////
VIEWS
//////////////////////////////////////////////////////////////*/
/// @notice The current real coordinator. It updates only through the official consumer-base path.
function coordinator() public view returns (address) {
return address(s_vrfCoordinator);
}
function requestConfirmations() external view returns (uint16) {
return approvedRequestConfirmations;
}
function routerCallbackGasLimit() external view returns (uint32) {
return approvedRouterCallbackGasLimit;
}
function maxOutstandingRequestsPerPool() external view returns (uint256) {
return maxOutstandingPerPool;
}
function maxOutstandingRequestsGlobal() external view returns (uint256) {
return maxOutstandingGlobal;
}
function requestFee() public view returns (uint256) {
return serviceGasEstimate * tx.gasprice * (BPS + serviceMarginBps) / BPS + serviceFlatWei;
}
function requiredSubscriptionBalance() public view returns (uint256) {
return minimumSubscriptionBuffer + (totalPrepared + totalCoordinatorOutstanding) * maxFulfillmentCostWei;
}
function subscriptionNativeBalance() public view returns (uint256 nativeBalance) {
// The coordinator deletes the subscription during terminal cancellation. Keep terminal views
// usable without querying a record that is guaranteed not to exist.
if (subscriptionTerminated) return 0;
(, uint96 balance,,,) = s_vrfCoordinator.getSubscription(subscriptionId);
nativeBalance = balance;
}
/// @notice Liquid ETH not needed to close the subscription's current coverage shortfall.
function availableSurplus() public view returns (uint256 available) {
if (subscriptionTerminated) return 0;
uint256 required = requiredSubscriptionBalance();
uint256 current = subscriptionNativeBalance();
uint256 reserved = required > current ? required - current : 0;
uint256 liquid = address(this).balance;
if (liquid > reserved) available = liquid - reserved;
}
/// @notice Coordinator-compatible, but intentionally scoped to the calling clone.
function pendingRequestExists(uint256 subId) external view returns (bool) {
if (!registeredPool[msg.sender]) revert UnknownPool();
if (subId != subscriptionId) revert InvalidRequestTuple();
return coordinatorOutstandingFor[msg.sender] != 0;
}
/*//////////////////////////////////////////////////////////////
ACTIVATION + REGISTRY
//////////////////////////////////////////////////////////////*/
function activateSubscription() external onlyFactory {
if (subscriptionTerminated) revert VrfServiceTerminated();
if (subscriptionActive) revert SubscriptionAlreadyActive();
_validateFactoryConfig();
if (owner() != factory) revert SubscriptionNotOwnedByFactory();
(, uint96 nativeBalance, uint64 requestCount, address subOwner, address[] memory consumers) =
s_vrfCoordinator.getSubscription(subscriptionId);
if (subOwner != factory) revert SubscriptionNotOwnedByFactory();
if (requestCount != 0 || s_vrfCoordinator.pendingRequestExists(subscriptionId)) {
revert SubscriptionNotPristine();
}
if (consumers.length != 1 || consumers[0] != address(this)) {
revert SubscriptionConsumerMismatch();
}
if (uint256(nativeBalance) < minimumSubscriptionBuffer) revert InsufficientVrfCoverage();
subscriptionActive = true;
emit SubscriptionActivated(subscriptionId, address(s_vrfCoordinator));
}
/// @notice Irreversibly retire this service and send its complete liquid ETH balance to the factory's
/// preconfigured recovery recipient. The factory cancels the coordinator subscription later in
/// the same transaction, so a failed coordinator refund rolls this transfer and terminal state
/// back atomically.
/// @dev This deliberately does not touch stored words or delivery state. It also does not query
/// `getSubscription`, which is invalid after coordinator cancellation.
function terminateSubscription(address payable recoveryRecipient)
external
onlyFactory
nonReentrant
returns (uint256 serviceEthRefund)
{
if (subscriptionTerminated) revert VrfServiceTerminated();
if (!subscriptionActive) revert SubscriptionNotActive();
if (!requestsPaused) revert RequestsPaused();
if (totalPrepared != 0 || totalCoordinatorOutstanding != 0) revert OutstandingCallbacks();
if (s_vrfCoordinator.pendingRequestExists(subscriptionId)) revert OutstandingCallbacks();
IFWACloneFactory config = IFWACloneFactory(factory);
if (
recoveryRecipient == address(0) || recoveryRecipient != config.vrfRecoveryRecipient()
|| !config.vrfSubscriptionTerminated() || !config.vrfSubscriptionActive() || config.globalPurchasesEnabled()
|| config.poolCreationEnabled() || !config.vrfRequestsPaused()
) revert InvalidConfig();
subscriptionTerminated = true;
subscriptionActive = false;
serviceEthRefund = address(this).balance;
if (serviceEthRefund != 0) SafeTransferLib.safeTransferETH(recoveryRecipient, serviceEthRefund);
emit SubscriptionTerminated(recoveryRecipient, serviceEthRefund);
}
/// @notice Permissionlessly forward ETH force-sent after shutdown to the same immutable-in-terminal
/// recovery recipient. Ordinary post-terminal transfers are rejected by `receive()`.
function recoverTerminalEth() external nonReentrant returns (uint256 amount) {
if (!subscriptionTerminated) revert SubscriptionNotActive();
address payable recoveryRecipient = payable(IFWACloneFactory(factory).vrfRecoveryRecipient());
if (recoveryRecipient == address(0) || recoveryRecipient == address(this)) revert InvalidConfig();
amount = address(this).balance;
if (amount != 0) SafeTransferLib.safeTransferETH(recoveryRecipient, amount);
emit TerminalEthRecovered(msg.sender, recoveryRecipient, amount);
}
function registerPool(address pool) external onlyFactory {
if (!subscriptionActive) revert SubscriptionNotActive();
if (pool == address(0) || pool.code.length == 0) revert InvalidConfig();
if (registeredPool[pool]) revert AlreadyRegistered();
if (!IFWACloneFactory(factory).isPool(pool)) revert UnknownPool();
_validatePoolConfig(pool);
if (IFWACloneVRFHost(pool).unfulfilledVrfCount() != 0) revert PoolConfigMismatch();
registeredPool[pool] = true;
emit PoolRegistered(pool);
}
/*//////////////////////////////////////////////////////////////
REQUEST FEE + COVERAGE
//////////////////////////////////////////////////////////////*/
/// @notice Reserve all callback coverage for a single request or complete batch before request #1.
function prepareRequests(uint256 requestCount) external payable nonReentrant {
address pool = msg.sender;
if (!subscriptionActive) revert SubscriptionNotActive();
if (requestsPaused) revert RequestsPaused();
if (!registeredPool[pool]) revert UnknownPool();
if (!IFWACloneFactory(factory).consumerReady(pool)) revert PoolNotReady();
if (requestCount == 0) revert InvalidConfig();
if (msg.value != requestFee() * requestCount) revert IncorrectRequestFee();
_validatePoolConfig(pool);
uint256 poolPrepared = preparedCredits[pool];
uint256 poolOutstanding = coordinatorOutstandingFor[pool];
uint256 newPoolLiability = poolPrepared + poolOutstanding + requestCount;
uint256 poolLimit = maxOutstandingPerPool;
if (poolLimit != 0 && newPoolLiability > poolLimit) revert PerPoolRequestLimitExceeded();
uint256 newGlobalLiability = totalPrepared + totalCoordinatorOutstanding + requestCount;
uint256 globalLimit = maxOutstandingGlobal;
if (globalLimit != 0 && newGlobalLiability > globalLimit) revert GlobalRequestLimitExceeded();
poolPrepared += requestCount;
preparedCredits[pool] = poolPrepared;
totalPrepared += requestCount;
emit RequestFeesReceived(pool, requestCount, msg.value);
emit RequestsPrepared(
pool, requestCount, poolPrepared, poolOutstanding, totalPrepared, totalCoordinatorOutstanding
);
_ensureSubscriptionCoverage();
}
/// @notice Coordinator-compatible request facade called only by a registered clone.
/// @return requestId The unmodified request ID returned by the real coordinator.
function requestRandomWords(VRFV2PlusClient.RandomWordsRequest calldata req)
external
nonReentrant
returns (uint256 requestId)
{
address pool = msg.sender;
if (!subscriptionActive) revert SubscriptionNotActive();
if (requestsPaused) revert RequestsPaused();
if (!registeredPool[pool]) revert UnknownPool();
if (!IFWACloneFactory(factory).consumerReady(pool)) revert PoolNotReady();
if (preparedCredits[pool] == 0) revert MissingPreparedCredit();
_validateRequestTuple(req);
_validatePoolConfig(pool);
// Convert one prepared liability into one coordinator liability before the external call.
// A coordinator revert, duplicate ID, or any later pool revert rolls this entire transaction back.
unchecked {
preparedCredits[pool] -= 1;
totalPrepared -= 1;
}
coordinatorOutstandingFor[pool] += 1;
totalCoordinatorOutstanding += 1;
requestId = s_vrfCoordinator.requestRandomWords(
VRFV2PlusClient.RandomWordsRequest({
keyHash: approvedVrfKeyHash,
subId: subscriptionId,
requestConfirmations: approvedRequestConfirmations,
callbackGasLimit: approvedRouterCallbackGasLimit,
numWords: NUM_WORDS,
extraArgs: VRFV2PlusClient._argsToBytes(VRFV2PlusClient.ExtraArgsV1({nativePayment: true}))
})
);
if (requestId == 0 || requestStatus[requestId] != RequestStatus.None) {
revert DuplicateRequestId();
}
requestPool[requestId] = pool;
requestStatus[requestId] = RequestStatus.CoordinatorOutstanding;
emit RandomnessRequested(requestId, pool);
}
function topUpSubscription() external nonReentrant returns (uint256 amount) {
if (!subscriptionActive) revert SubscriptionNotActive();
amount = _ensureSubscriptionCoverage();
}
function _ensureSubscriptionCoverage() internal returns (uint256 amount) {
if (subscriptionTerminated) revert VrfServiceTerminated();
uint256 required = requiredSubscriptionBalance();
uint256 current = subscriptionNativeBalance();
if (current >= required) return 0;
amount = required - current;
if (amount > address(this).balance) revert InsufficientVrfCoverage();
s_vrfCoordinator.fundSubscriptionWithNative{value: amount}(subscriptionId);
emit SubscriptionFunded(subscriptionId, amount, required);
}
/*//////////////////////////////////////////////////////////////
CALLBACK + REDelivery
//////////////////////////////////////////////////////////////*/
/// @dev The inherited external entrypoint authenticates `s_vrfCoordinator` before reaching here.
/// Unknown, duplicate, terminal, and malformed callbacks deliberately do not revert.
function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) internal override {
RequestStatus status = requestStatus[requestId];
address pool = requestPool[requestId];
if (status != RequestStatus.CoordinatorOutstanding || pool == address(0)) {
emit FulfillmentIgnored(requestId, status, randomWords.length);
return;
}
_releaseCoordinatorLiability(pool);
bool hasWord = randomWords.length != 0;
if (hasWord) {
storedRandomWord[requestId] = randomWords[0];
requestStatus[requestId] = RequestStatus.WordStored;
} else {
requestStatus[requestId] = RequestStatus.EmptyWordArrayStored;
}
emit RandomnessStored(requestId, pool, hasWord ? randomWords[0] : 0, hasWord);
_attemptDelivery(requestId, pool);
}
/// @notice Retry only the authenticated word already stored for its immutable original pool.
function deliverRandomness(uint256 requestId) external nonReentrant returns (bool delivered) {
RequestStatus status = requestStatus[requestId];
if (status != RequestStatus.WordStored && status != RequestStatus.EmptyWordArrayStored) {
revert RandomnessNotDeliverable();
}
delivered = _attemptDelivery(requestId, requestPool[requestId]);
}
function _attemptDelivery(uint256 requestId, address pool) internal returns (bool delivered) {
RequestStatus status = requestStatus[requestId];
bool hasWord = status == RequestStatus.WordStored;
if (!hasWord && status != RequestStatus.EmptyWordArrayStored) return false;
if (pool.code.length == 0) {
emit RandomnessDeliveryFailed(requestId, pool);
return false;
}
uint256[] memory words = new uint256[](hasWord ? 1 : 0);
if (hasWord) words[0] = storedRandomWord[requestId];
bytes memory callData = abi.encodeCall(IFWACloneRandomnessReceiver.rawFulfillRandomWords, (requestId, words));
uint256 stipend = approvedCallbackGasLimit;
uint256 eip150Overhead = (stipend + 62) / 63;
if (gasleft() < stipend + eip150Overhead + DELIVERY_RETURN_GAS_RESERVE) {
emit RandomnessDeliveryDeferred(requestId, pool);
return false;
}
assembly ("memory-safe") {
delivered := call(stipend, pool, 0, add(callData, 0x20), mload(callData), 0, 0)
}
if (delivered) {
requestStatus[requestId] = RequestStatus.Delivered;
delete storedRandomWord[requestId];
emit RandomnessDelivered(requestId, pool);
} else {
emit RandomnessDeliveryFailed(requestId, pool);
}
}
/// @notice Release a request whose real coordinator commitment is already consumed but whose
/// authenticated callback never stored a word here. No replacement randomness is created.
function reconcileCoordinatorRequest(uint256 requestId) external nonReentrant {
if (requestStatus[requestId] != RequestStatus.CoordinatorOutstanding) {
revert RandomnessNotDeliverable();
}
(bool checked, bytes32 commitment) = _requestCommitment(requestId);
if (!checked) revert CoordinatorCommitmentCheckFailed();
if (commitment != bytes32(0)) revert CoordinatorRequestStillPending();
address pool = requestPool[requestId];
requestStatus[requestId] = RequestStatus.CoordinatorCallbackLost;
_releaseCoordinatorLiability(pool);
emit CoordinatorRequestReconciled(requestId, pool);
}
/// @dev Fixed-size staticcall prevents an unexpected coordinator return payload from being copied.
function _requestCommitment(uint256 requestId) internal view returns (bool checked, bytes32 commitment) {
address currentCoordinator = address(s_vrfCoordinator);
bytes4 selector = IVRFCoordinatorV2PlusInternal.s_requestCommitments.selector;
assembly ("memory-safe") {
let ptr := mload(0x40)
// Solidity exposes fixed-size bytes to assembly left-aligned, so `selector` already
// occupies the first four ABI bytes (shifting it would erase it).
mstore(ptr, selector)
mstore(add(ptr, 0x04), requestId)
checked := staticcall(gas(), currentCoordinator, ptr, 0x24, ptr, 0x20)
if and(checked, eq(returndatasize(), 0x20)) { commitment := mload(ptr) }
if iszero(eq(returndatasize(), 0x20)) { checked := 0 }
}
}
function _releaseCoordinatorLiability(address pool) internal {
uint256 poolOutstanding = coordinatorOutstandingFor[pool];
uint256 globalOutstanding = totalCoordinatorOutstanding;
if (poolOutstanding != 0 && globalOutstanding != 0) {
coordinatorOutstandingFor[pool] = poolOutstanding - 1;
totalCoordinatorOutstanding = globalOutstanding - 1;
}
}
/*//////////////////////////////////////////////////////////////
SPONSORED PROCESSING
//////////////////////////////////////////////////////////////*/
/// @notice Process one registered clone's canonical prefix and reimburse an approved operator
/// from subscription-safe service surplus.
/// @dev This is only a sponsored wrapper around the clone's existing permissionless processor.
/// The operator chooses neither request IDs nor ordering. A failed reimbursement rolls back
/// this sponsored call, while the clone's direct processor remains available to everyone.
function processAcquisitions(address pool, uint256 maxCount)
external
nonReentrant
onlyOperator
returns (uint256 processed, uint256 reimbursement)
{
if (!registeredPool[pool]) revert UnknownPool();
if (maxCount == 0 || maxCount > maxSponsoredCount) revert InvalidConfig();
uint256 gasStart = gasleft();
// Chainlink can bill only subscription-held ETH. Restore the complete coordinator reserve
// before classifying or paying any liquid treasury balance as processor surplus.
_ensureSubscriptionCoverage();
uint256 available = availableSurplus();
if (available == 0) revert NoProcessorSurplus();
processed = IFWACloneVRFHost(pool).processAcquisitions(maxCount);
if (processed == 0) {
emit AcquisitionsSponsored(msg.sender, pool, 0, 0, 0, 0);
return (0, 0);
}
uint256 gasUnits = gasStart - gasleft() + reimbursementGasOverhead;
if (gasUnits > maxReimbursementGas) gasUnits = maxReimbursementGas;
uint256 baseFee = block.basefee;
if (baseFee > maxReimbursementBaseFeeWei) baseFee = maxReimbursementBaseFeeWei;
uint256 gasPriceCap = baseFee + maxReimbursementPriorityFeeWei;
uint256 reimbursableGasPrice = tx.gasprice;
if (reimbursableGasPrice > gasPriceCap) reimbursableGasPrice = gasPriceCap;
reimbursement = gasUnits * reimbursableGasPrice;
if (reimbursement > maxReimbursementWei) reimbursement = maxReimbursementWei;
// Re-establish and re-read coverage at the exact payment point. Processing does not mutate
// router liabilities today, but keeping this invariant local makes future changes fail closed.
_ensureSubscriptionCoverage();
available = availableSurplus();
if (reimbursement > available) reimbursement = available;
if (reimbursement != 0) SafeTransferLib.safeTransferETH(msg.sender, reimbursement);
emit AcquisitionsSponsored(msg.sender, pool, processed, gasUnits, reimbursableGasPrice, reimbursement);
}
/*//////////////////////////////////////////////////////////////
FACTORY CONFIG
//////////////////////////////////////////////////////////////*/
function setRequestsPaused(bool paused) external onlyFactory {
if (!paused) {
if (subscriptionTerminated) revert VrfServiceTerminated();
if (!subscriptionActive) revert SubscriptionNotActive();
_validateFactoryConfig();
}
requestsPaused = paused;
emit RequestsPausedSet(paused);
}
/// @notice A zero value removes that explicit limit. Existing requests are never affected.
function setRequestLimits(uint256 maxPerPool, uint256 maxGlobal) external onlyFactory {
maxOutstandingPerPool = maxPerPool;
maxOutstandingGlobal = maxGlobal;
emit RequestLimitsSet(maxPerPool, maxGlobal);
}
/// @notice Rotate to a never-before-used gas lane after an official coordinator migration.
/// @dev Chainlink's migration target resets this consumer's request nonce to zero. Because a real
/// request ID hashes the key hash together with this service, subscription, and nonce, key-hash
/// uniqueness is what prevents a post-migration request from colliding with historical pool state.
function setVrfKeyHash(bytes32 newKeyHash) external onlyFactory nonReentrant {
if (!subscriptionActive) revert SubscriptionNotActive();
if (!requestsPaused) revert RequestsPaused();
if (newKeyHash == bytes32(0) || newKeyHash == approvedVrfKeyHash) revert InvalidConfig();
if (usedVrfKeyHash[newKeyHash]) revert VrfKeyHashAlreadyUsed();
if (totalPrepared != 0 || totalCoordinatorOutstanding != 0) revert OutstandingCallbacks();
if (s_vrfCoordinator.pendingRequestExists(subscriptionId)) revert OutstandingCallbacks();
IFWACloneFactory config = IFWACloneFactory(factory);
if (config.chainlinkCoordinator() != address(s_vrfCoordinator) || config.vrfKeyHash() != newKeyHash) {
revert InvalidConfig();
}
bytes32 oldKeyHash = approvedVrfKeyHash;
approvedVrfKeyHash = newKeyHash;
usedVrfKeyHash[newKeyHash] = true;
// The current ceiling becomes the non-decreasing floor approved for this new gas lane.
coverageFloor = maxFulfillmentCostWei;
emit VrfKeyHashRotated(oldKeyHash, newKeyHash, coverageFloor);
}
/// @notice Permissionlessly bring one cleared pool onto the current post-migration request tuple.
/// @dev The clone itself additionally requires factory request/global purchase pauses and zero local
/// unsettled/callback work. An already-synced pool is an idempotent no-op.
function syncPoolRequestConfig(address pool) external nonReentrant {
if (!requestsPaused) revert RequestsPaused();
if (!registeredPool[pool]) revert UnknownPool();
if (preparedCredits[pool] != 0 || coordinatorOutstandingFor[pool] != 0) {
revert OutstandingCallbacks();
}
IFWACloneVRFHost host = IFWACloneVRFHost(pool);
(address logicalCoordinator, uint256 configuredSubId) = host.vrfCoordinatorAndSubId();
(bytes32 keyHash, uint32 gasLimit) = host.vrfRequestConfig();
if (
logicalCoordinator != address(this) || configuredSubId != subscriptionId
|| host.vrfService() != address(this) || gasLimit != approvedCallbackGasLimit
) revert PoolConfigMismatch();
if (keyHash == approvedVrfKeyHash) return;
host.configureVrfRequest(approvedVrfKeyHash, approvedCallbackGasLimit);
_validatePoolConfig(pool);
emit PoolRequestConfigSynced(pool, approvedVrfKeyHash, approvedCallbackGasLimit);
}
function setFeeConfig(uint256 gasEstimate, uint256 marginBps, uint256 flatWei) external onlyFactory {
if (gasEstimate == 0) revert InvalidConfig();
serviceGasEstimate = gasEstimate;
serviceMarginBps = marginBps;
serviceFlatWei = flatWei;
emit FeeConfigSet(gasEstimate, marginBps, flatWei);
}
function setCoverageConfig(uint256 minimumBuffer, uint256 maxFulfillmentCost) external onlyFactory nonReentrant {
if (minimumBuffer == 0 || maxFulfillmentCost < coverageFloor) revert InvalidConfig();
uint256 liabilities = totalPrepared + totalCoordinatorOutstanding;
if (
liabilities != 0
&& (minimumBuffer < minimumSubscriptionBuffer || maxFulfillmentCost < maxFulfillmentCostWei)
) revert OutstandingCallbacks();
minimumSubscriptionBuffer = minimumBuffer;
maxFulfillmentCostWei = maxFulfillmentCost;
if (subscriptionActive) _ensureSubscriptionCoverage();
emit CoverageConfigSet(minimumBuffer, maxFulfillmentCost);
}
function setOperator(address operator, bool allowed) external onlyFactory {
if (operator == address(0)) revert InvalidConfig();
operators[operator] = allowed;
emit OperatorSet(operator, allowed);
}
function setReimbursementConfig(
uint256 sponsoredCount,
uint256 reimbursementGas,
uint256 gasOverhead,
uint256 maxBaseFeeWei,
uint256 maxPriorityFeeWei,
uint256 reimbursementWei
) external onlyFactory {
if (sponsoredCount == 0 || reimbursementGas == 0 || maxBaseFeeWei == 0 || reimbursementWei == 0) {
revert InvalidConfig();
}
maxSponsoredCount = sponsoredCount;
maxReimbursementGas = reimbursementGas;
reimbursementGasOverhead = gasOverhead;
maxReimbursementBaseFeeWei = maxBaseFeeWei;
maxReimbursementPriorityFeeWei = maxPriorityFeeWei;
maxReimbursementWei = reimbursementWei;
emit ReimbursementConfigSet(
sponsoredCount, reimbursementGas, gasOverhead, maxBaseFeeWei, maxPriorityFeeWei, reimbursementWei
);
}
/// @notice Factory-controlled timing and live recipient selection.
function withdrawSurplus(address recipient, uint256 amount) external onlyFactory nonReentrant {
if (subscriptionTerminated) revert VrfServiceTerminated();
if (recipient == address(0) || recipient != IFWACloneFactory(factory).protocolFeeRecipient()) {
revert InvalidConfig();
}
if (amount > availableSurplus()) revert InsufficientSurplus();
SafeTransferLib.safeTransferETH(recipient, amount);
emit SurplusWithdrawn(recipient, amount);
}
/*//////////////////////////////////////////////////////////////
VALIDATION
//////////////////////////////////////////////////////////////*/
function _validateRequestTuple(VRFV2PlusClient.RandomWordsRequest calldata req) internal view {
if (
req.keyHash != approvedVrfKeyHash || req.subId != subscriptionId
|| req.requestConfirmations != approvedRequestConfirmations
|| req.callbackGasLimit != approvedCallbackGasLimit || req.numWords != NUM_WORDS
|| keccak256(req.extraArgs) != approvedExtraArgsHash
) revert InvalidRequestTuple();
}
function _validatePoolConfig(address pool) internal view {
IFWACloneVRFHost host = IFWACloneVRFHost(pool);
(address logicalCoordinator, uint256 configuredSubId) = host.vrfCoordinatorAndSubId();
(bytes32 keyHash, uint32 gasLimit) = host.vrfRequestConfig();
if (
logicalCoordinator != address(this) || configuredSubId != subscriptionId
|| host.vrfService() != address(this) || keyHash != approvedVrfKeyHash
|| gasLimit != approvedCallbackGasLimit
) revert PoolConfigMismatch();
}
function _validateFactoryConfig() internal view {
IFWACloneFactory config = IFWACloneFactory(factory);
if (
config.chainlinkCoordinator() != address(s_vrfCoordinator) || config.vrfCoordinator() != address(this)
|| config.vrfSubscriptionId() != subscriptionId || config.vrfKeyHash() != approvedVrfKeyHash
|| config.callbackGasLimit() != approvedCallbackGasLimit
|| config.routerCallbackGasLimit() != approvedRouterCallbackGasLimit
|| config.requestConfirmations() != approvedRequestConfirmations
) revert InvalidConfig();
}
}
lib/chainlink-evm/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)) {}
}
lib/chainlink-evm/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();
_;
}
}
lib/chainlink-evm/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;
}
lib/chainlink-evm/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));
}
_;
}
}
lib/chainlink-evm/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);
}
lib/chainlink-evm/contracts/src/v0.8/vrf/dev/interfaces/IVRFCoordinatorV2PlusInternal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IVRFCoordinatorV2Plus} from "./IVRFCoordinatorV2Plus.sol";
// IVRFCoordinatorV2PlusInternal is the interface used by chainlink core and should
// not be used by consumer conracts
// Future versions of VRF V2plus must conform to this interface
// VRF coordinator doesn't directly inherit from this interface because solidity
// imposes interface methods be external, whereas methods implementated VRF coordinator
// are public. This is OK because IVRFCoordinatorV2PlusInternal doesn't have any solidity
// use case. It is only used to generate gethwrappers
interface IVRFCoordinatorV2PlusInternal is IVRFCoordinatorV2Plus {
event RandomWordsRequested(
bytes32 indexed keyHash,
uint256 requestId,
uint256 preSeed,
uint256 indexed subId,
uint16 minimumRequestConfirmations,
uint32 callbackGasLimit,
uint32 numWords,
bytes extraArgs,
address indexed sender
);
event RandomWordsFulfilled(
uint256 indexed requestId, uint256 outputSeed, uint256 indexed subId, uint96 payment, bool success, bool onlyPremium
);
struct RequestCommitment {
uint64 blockNum;
uint256 subId;
uint32 callbackGasLimit;
uint32 numWords;
address sender;
bytes extraArgs;
}
struct Proof {
uint256[2] pk;
uint256[2] gamma;
uint256 c;
uint256 s;
uint256 seed;
address uWitness;
uint256[2] cGammaWitness;
uint256[2] sHashWitness;
uint256 zInv;
}
// solhint-disable-next-line func-name-mixedcase
function s_requestCommitments(
uint256 requestID
) external view returns (bytes32);
function fulfillRandomWords(
Proof calldata proof,
RequestCommitment memory rc,
bool onlyPremium
) external returns (uint96);
// solhint-disable-next-line func-name-mixedcase
function LINK_NATIVE_FEED() external view returns (address);
}
lib/chainlink-evm/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;
}
lib/chainlink-evm/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;
}
lib/chainlink-evm/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);
}
}
lib/solady/src/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unauthorized reentrant call.
error Reentrancy();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
/// 9 bytes is large enough to avoid collisions with lower slots,
/// but not too large to result in excessive bytecode bloat.
uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* REENTRANCY GUARD */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Guards a function from reentrancy.
modifier nonReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
sstore(_REENTRANCY_GUARD_SLOT, address())
}
_;
/// @solidity memory-safe-assembly
assembly {
sstore(_REENTRANCY_GUARD_SLOT, codesize())
}
}
/// @dev Guards a view function from read-only reentrancy.
modifier nonReadReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
_;
}
}
lib/solady/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
/// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
/// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) {
revert(codesize(), codesize())
} // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend) internal returns (bool success) {
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
/// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
/// and upon failure, deploys a minimal vault to accrue the ETH.
function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
/// @solidity memory-safe-assembly
assembly {
to := shr(96, shl(96, to)) // Clean upper 96 bits.
for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
let selfBalanceBefore := selfbalance()
if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if extcodesize(mover) {
let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
mstore(0x00, to)
pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
// If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
// Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
if lt(selfBalanceBefore, selfbalance()) { invalid() }
}
let m := mload(0x40)
// If the mover is missing or bricked, deploy a minimal vault
// that withdraws all ETH to `to` when being called only by `to`.
// forgefmt: disable-next-item
mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, keccak256(m, 0x40))
mstore(0x01, shl(96, address())) // Deployer.
mstore(0x15, 0) // Salt.
vault := keccak256(0x00, 0x55)
pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
// The vault returns a single word on success. Failure reverts with empty data.
if iszero(returndatasize()) {
if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
}
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount := mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Performs a `token.balanceOf(account)` check.
/// `implemented` denotes whether the `token` implements `balanceOf`.
/// `amount` is zero if the `token` does not implement `balanceOf`.
function checkBalanceOf(address token, address account)
internal
view
returns (bool implemented, uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
implemented := and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
amount := mul(mload(0x20), implemented)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))
) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0x84, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
src/userowned/interfaces/IFWACloneFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @notice Read-only factory surface consumed by user-owned FWA pool clones.
/// @dev `vrfCoordinator()` is deliberately the logical coordinator seen by every clone: the singleton
/// router/service. `chainlinkCoordinator()` is the mutable real Chainlink coordinator and is never
/// called directly by a clone.
interface IFWACloneFactory {
function vrfCoordinator() external view returns (address);
function chainlinkCoordinator() external view returns (address);
function vrfSubscriptionId() external view returns (uint256);
function vrfKeyHash() external view returns (bytes32);
function callbackGasLimit() external view returns (uint32);
function routerCallbackGasLimit() external view returns (uint32);
function requestConfirmations() external view returns (uint16);
function selectionTimeoutBlocks() external view returns (uint32);
function maxActivationsPerAcquisition() external view returns (uint16);
function maxAcquisitionsPerTx() external view returns (uint16);
function selectionSlippageBps() external view returns (uint16);
function maxStagedListings() external view returns (uint256);
function edgeBps() external view returns (uint16);
function inventoryChangeCooldown() external view returns (uint32);
function buybackPurchaserBps() external view returns (uint16);
function buybackOwnerBps() external view returns (uint16);
function buybackProtocolBps() external view returns (uint16);
function buybackPurchaserWindow() external view returns (uint32);
function buybackFinalizationWindow() external view returns (uint32);
function globalPurchasesEnabled() external view returns (bool);
function globalWithdrawOnly() external view returns (bool);
function poolCreationEnabled() external view returns (bool);
function vrfSubscriptionActive() external view returns (bool);
function vrfSubscriptionTerminated() external view returns (bool);
function vrfRecoveryRecipient() external view returns (address);
function vrfRequestsPaused() external view returns (bool);
function consumerReady(address pool) external view returns (bool);
function isPool(address pool) external view returns (bool);
function protocolFeeRecipient() external view returns (address);
function maxOutstandingRequestsPerPool() external view returns (uint256);
function maxOutstandingRequestsGlobal() external view returns (uint256);
}
/// @notice Factory-only control and inspection surface implemented by the singleton VRF router/service.
/// @dev The factory intentionally has no generic executor and no wrapper around the consumer base's
/// `setCoordinator`. Only the old authenticated Chainlink coordinator may change that value during
/// an official subscription migration.
interface IFWACloneVRFServiceAdmin {
function factory() external view returns (address);
function coordinator() external view returns (address);
function subscriptionId() external view returns (uint256);
function approvedVrfKeyHash() external view returns (bytes32);
function approvedCallbackGasLimit() external view returns (uint32);
function routerCallbackGasLimit() external view returns (uint32);
function requestConfirmations() external view returns (uint16);
function owner() external view returns (address);
function acceptOwnership() external;
function subscriptionActive() external view returns (bool);
function subscriptionTerminated() external view returns (bool);
function requestsPaused() external view returns (bool);
function registeredPool(address pool) external view returns (bool);
function totalPrepared() external view returns (uint256);
function totalCoordinatorOutstanding() external view returns (uint256);
function minimumSubscriptionBuffer() external view returns (uint256);
function maxFulfillmentCostWei() external view returns (uint256);
function usedVrfKeyHash(bytes32 keyHash) external view returns (bool);
function registerPool(address pool) external;
function activateSubscription() external;
function terminateSubscription(address payable recoveryRecipient) external returns (uint256 serviceEthRefund);
function setVrfKeyHash(bytes32 keyHash) external;
function syncPoolRequestConfig(address pool) external;
function setRequestLimits(uint256 perPoolLimit, uint256 globalLimit) external;
function setRequestsPaused(bool paused) external;
function setFeeConfig(uint256 gasEstimate, uint256 marginBps, uint256 flatWei) external;
function setCoverageConfig(uint256 minimumBuffer, uint256 maxFulfillmentCost) external;
function setOperator(address operator, bool allowed) external;
function setReimbursementConfig(
uint256 sponsoredCount,
uint256 reimbursementGas,
uint256 gasOverhead,
uint256 maxBaseFeeWei,
uint256 maxPriorityFeeWei,
uint256 reimbursementWei
) external;
function withdrawSurplus(address recipient, uint256 amount) external;
}
/// @notice Pool configuration surface used by the singleton router/service when registering clones.
interface IFWACloneVRFHost {
function processAcquisitions(uint256 maxCount) external returns (uint256 processed);
function unfulfilledVrfCount() external view returns (uint256);
function vrfCoordinatorAndSubId() external view returns (address coordinator, uint256 subId);
function vrfRequestConfig() external view returns (bytes32 keyHash, uint32 gasLimit);
function vrfService() external view returns (address);
function configureVrfRequest(bytes32 keyHash, uint32 gasLimit) external;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"solady/=lib/solady/",
"forge-std/=lib/forge-std/src/",
"@chainlink/contracts/=lib/chainlink-evm/contracts/",
"@uniswap/v4-core/=lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"project/=/",
"solady-0.1.26/=lib/solady-0.1.26/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
"chainlink-evm/=lib/chainlink-evm/",
"ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"permit2/=lib/v4-periphery/lib/permit2/",
"solmate/=lib/v4-core/lib/solmate/",
"v4-core/=lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.