From 9c080dec35cf675bb5b4385df0cb615f827e52c4 Mon Sep 17 00:00:00 2001 From: Iva Brajer Date: Wed, 28 Oct 2026 20:41:56 +0100 Subject: [PATCH 1/5] Remove VRF v2 contracts Deletes the VRF v2 Solidity contracts (VRFCoordinatorV2, VRFConsumerBaseV2, VRFV2Wrapper, consumers, test helpers, mocks and the AuthorizedReceiver, KeepersVRFConsumer, VRFOwner and VRFSubscriptionBalanceMonitor contracts that depend on the v2 coordinator interface) and removes their compile script entries. Also removes the corresponding go:generate directives and wrapper dependency-version entries (identical to the change in the VRF v2 wrappers removal PR, so the two can merge in either order). Co-Authored-By: Claude Code --- contracts/scripts/native_solc_compile_all_vrf | 34 +- contracts/src/v0.8/vrf/AuthorizedReceiver.sol | 90 -- .../src/v0.8/vrf/BatchVRFCoordinatorV2.sol | 79 -- contracts/src/v0.8/vrf/KeepersVRFConsumer.sol | 130 --- contracts/src/v0.8/vrf/VRFConsumerBaseV2.sol | 145 --- contracts/src/v0.8/vrf/VRFCoordinatorV2.sol | 876 ------------------ contracts/src/v0.8/vrf/VRFOwner.sol | 376 -------- .../vrf/VRFSubscriptionBalanceMonitor.sol | 291 ------ contracts/src/v0.8/vrf/VRFV2Wrapper.sol | 464 ---------- .../src/v0.8/vrf/VRFV2WrapperConsumerBase.sol | 96 -- .../vrf/interfaces/IAuthorizedReceiver.sol | 14 - .../interfaces/VRFCoordinatorV2Interface.sol | 129 --- .../vrf/interfaces/VRFV2WrapperInterface.sol | 38 - .../v0.8/vrf/mocks/VRFCoordinatorV2Mock.sol | 355 ------- .../v0.8/vrf/test/VRFCoordinatorV2Mock.t.sol | 359 ------- .../v0.8/vrf/testhelpers/VRFConsumerV2.sol | 73 -- .../VRFConsumerV2UpgradeableExample.sol | 75 -- .../vrf/testhelpers/VRFCoordinatorTestV2.sol | 866 ----------------- .../VRFCoordinatorV2TestHelper.sol | 85 -- .../VRFExternalSubOwnerExample.sol | 55 -- .../VRFLoadTestExternalSubOwner.sol | 44 - .../testhelpers/VRFMaliciousConsumerV2.sol | 63 -- .../testhelpers/VRFSingleConsumerExample.sol | 114 --- .../VRFSubscriptionBalanceMonitorExposed.sol | 20 - .../testhelpers/VRFV2LoadTestWithMetrics.sol | 167 ---- .../testhelpers/VRFV2OwnerTestConsumer.sol | 142 --- .../v0.8/vrf/testhelpers/VRFV2ProxyAdmin.sol | 8 - .../vrf/testhelpers/VRFV2RevertingExample.sol | 74 -- .../VRFV2TransparentUpgradeableProxy.sol | 13 - .../VRFV2WrapperConsumerExample.sol | 63 -- .../VRFV2WrapperLoadTestConsumer.sol | 142 --- .../VRFV2WrapperOutOfGasConsumerExample.sol | 28 - .../VRFV2WrapperRevertingConsumerExample.sol | 28 - .../VRFV2WrapperUnderFundingConsumer.sol | 32 - .../v0.8/vrf/testhelpers/VRFv2Consumer.sol | 71 -- ...rapper-dependency-versions-do-not-edit.txt | 21 - gethwrappers/go_generate_vrf.go | 26 - 37 files changed, 2 insertions(+), 5684 deletions(-) delete mode 100644 contracts/src/v0.8/vrf/AuthorizedReceiver.sol delete mode 100644 contracts/src/v0.8/vrf/BatchVRFCoordinatorV2.sol delete mode 100644 contracts/src/v0.8/vrf/KeepersVRFConsumer.sol delete mode 100644 contracts/src/v0.8/vrf/VRFConsumerBaseV2.sol delete mode 100644 contracts/src/v0.8/vrf/VRFCoordinatorV2.sol delete mode 100644 contracts/src/v0.8/vrf/VRFOwner.sol delete mode 100644 contracts/src/v0.8/vrf/VRFSubscriptionBalanceMonitor.sol delete mode 100644 contracts/src/v0.8/vrf/VRFV2Wrapper.sol delete mode 100644 contracts/src/v0.8/vrf/VRFV2WrapperConsumerBase.sol delete mode 100644 contracts/src/v0.8/vrf/interfaces/IAuthorizedReceiver.sol delete mode 100644 contracts/src/v0.8/vrf/interfaces/VRFCoordinatorV2Interface.sol delete mode 100644 contracts/src/v0.8/vrf/interfaces/VRFV2WrapperInterface.sol delete mode 100644 contracts/src/v0.8/vrf/mocks/VRFCoordinatorV2Mock.sol delete mode 100644 contracts/src/v0.8/vrf/test/VRFCoordinatorV2Mock.t.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFConsumerV2.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFConsumerV2UpgradeableExample.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFCoordinatorTestV2.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFCoordinatorV2TestHelper.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFExternalSubOwnerExample.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFLoadTestExternalSubOwner.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFMaliciousConsumerV2.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFSingleConsumerExample.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFSubscriptionBalanceMonitorExposed.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFV2LoadTestWithMetrics.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFV2OwnerTestConsumer.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFV2ProxyAdmin.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFV2RevertingExample.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFV2TransparentUpgradeableProxy.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperConsumerExample.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperLoadTestConsumer.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperOutOfGasConsumerExample.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperRevertingConsumerExample.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperUnderFundingConsumer.sol delete mode 100644 contracts/src/v0.8/vrf/testhelpers/VRFv2Consumer.sol diff --git a/contracts/scripts/native_solc_compile_all_vrf b/contracts/scripts/native_solc_compile_all_vrf index de01cd8570..86efe75ddd 100755 --- a/contracts/scripts/native_solc_compile_all_vrf +++ b/contracts/scripts/native_solc_compile_all_vrf @@ -37,49 +37,19 @@ compileContract vrf-compile VRFConsumerBase compileContract vrf-compile testhelpers/VRFConsumer compileContract vrf-compile testhelpers/VRFRequestIDBaseTestHelper compileContract vrf-compile mocks/VRFCoordinatorMock -# -## VRF V2 -compileContract vrf-compile VRFConsumerBaseV2 + +# VRF Helpers compileContract vrf-compile testhelpers/ChainSpecificUtilHelper -compileContract vrf-compile testhelpers/VRFConsumerV2 -compileContract vrf-compile testhelpers/VRFMaliciousConsumerV2 compileContract vrf-compile testhelpers/VRFTestHelper -compileContract vrf-compile testhelpers/VRFV2RevertingExample -compileContract vrf-compile testhelpers/VRFV2ProxyAdmin -compileContract vrf-compile testhelpers/VRFV2TransparentUpgradeableProxy -compileContract vrf-compile testhelpers/VRFConsumerV2UpgradeableExample -compileContract vrf-compile BatchVRFCoordinatorV2 -compileContract vrf-compile testhelpers/VRFCoordinatorV2TestHelper -compileContract vrf-compile VRFCoordinatorV2 10000 -compileContract vrf-compile mocks/VRFCoordinatorV2Mock -compileContract vrf-compile VRFOwner -compileContract vrf-compile VRFSubscriptionBalanceMonitor -compileContract vrf-compile KeepersVRFConsumer - -# VRF V2 Wrapper -compileContract vrf-compile VRFV2Wrapper -compileContract vrf-compile interfaces/VRFV2WrapperInterface -compileContract vrf-compile VRFV2WrapperConsumerBase -compileContract vrf-compile testhelpers/VRFV2WrapperConsumerExample -compileContract vrf-compile testhelpers/VRFV2WrapperLoadTestConsumer -compileContract vrf-compile testhelpers/VRFv2Consumer # VRF Consumers and Mocks -compileContract vrf-compile testhelpers/VRFExternalSubOwnerExample -compileContract vrf-compile testhelpers/VRFSingleConsumerExample compileContract vrf-compile testhelpers/VRFOwnerlessConsumerExample compileContract vrf-compile testhelpers/VRFLoadTestOwnerlessConsumer -compileContract vrf-compile testhelpers/VRFLoadTestExternalSubOwner -compileContract vrf-compile testhelpers/VRFV2LoadTestWithMetrics -compileContract vrf-compile testhelpers/VRFV2OwnerTestConsumer -compileContract vrf-compile testhelpers/VRFCoordinatorTestV2 10000 compileContract vrf-compile testhelpers/VRFMockETHLINKAggregator compileContract vrf-compile testhelpers/Counter # Helper contracts compileContract vrf-compile interfaces/IAuthorizedReceiver -compileContract vrf-compile interfaces/VRFCoordinatorV2Interface -compileContract vrf-compile interfaces/VRFV2WrapperInterface # VRF V2 Plus compileContract vrfv2plus-compile interfaces/IVRFCoordinatorV2PlusInternal diff --git a/contracts/src/v0.8/vrf/AuthorizedReceiver.sol b/contracts/src/v0.8/vrf/AuthorizedReceiver.sol deleted file mode 100644 index af011b6763..0000000000 --- a/contracts/src/v0.8/vrf/AuthorizedReceiver.sol +++ /dev/null @@ -1,90 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.6; - -import {IAuthorizedReceiver} from "./interfaces/IAuthorizedReceiver.sol"; -import {EnumerableSet} from "@openzeppelin/contracts@4.9.6/utils/structs/EnumerableSet.sol"; - -abstract contract AuthorizedReceiver is IAuthorizedReceiver { - using EnumerableSet for EnumerableSet.AddressSet; - - event AuthorizedSendersChanged(address[] senders, address changedBy); - - error EmptySendersList(); - error UnauthorizedSender(); - error NotAllowedToSetSenders(); - - EnumerableSet.AddressSet private s_authorizedSenders; - address[] private s_authorizedSendersList; - - /** - * @notice Sets the fulfillment permission for a given node. Use `true` to allow, `false` to disallow. - * @param senders The addresses of the authorized Chainlink node - */ - function setAuthorizedSenders( - address[] calldata senders - ) external override validateAuthorizedSenderSetter { - if (senders.length == 0) { - revert EmptySendersList(); - } - for (uint256 i = 0; i < s_authorizedSendersList.length; i++) { - s_authorizedSenders.remove(s_authorizedSendersList[i]); - } - for (uint256 i = 0; i < senders.length; i++) { - s_authorizedSenders.add(senders[i]); - } - s_authorizedSendersList = senders; - emit AuthorizedSendersChanged(senders, msg.sender); - } - - /** - * @notice Retrieve a list of authorized senders - * @return array of addresses - */ - function getAuthorizedSenders() public view override returns (address[] memory) { - return s_authorizedSendersList; - } - - /** - * @notice Use this to check if a node is authorized for fulfilling requests - * @param sender The address of the Chainlink node - * @return The authorization status of the node - */ - function isAuthorizedSender( - address sender - ) public view override returns (bool) { - return s_authorizedSenders.contains(sender); - } - - /** - * @notice customizable guard of who can update the authorized sender list - * @return bool whether sender can update authorized sender list - */ - function _canSetAuthorizedSenders() internal virtual returns (bool); - - /** - * @notice validates the sender is an authorized sender - */ - function _validateIsAuthorizedSender() internal view { - if (!isAuthorizedSender(msg.sender)) { - revert UnauthorizedSender(); - } - } - - /** - * @notice prevents non-authorized addresses from calling this method - */ - modifier validateAuthorizedSender() { - _validateIsAuthorizedSender(); - _; - } - - /** - * @notice prevents non-authorized addresses from calling this method - */ - modifier validateAuthorizedSenderSetter() { - if (!_canSetAuthorizedSenders()) { - revert NotAllowedToSetSenders(); - } - _; - } -} diff --git a/contracts/src/v0.8/vrf/BatchVRFCoordinatorV2.sol b/contracts/src/v0.8/vrf/BatchVRFCoordinatorV2.sol deleted file mode 100644 index c47fc62459..0000000000 --- a/contracts/src/v0.8/vrf/BatchVRFCoordinatorV2.sol +++ /dev/null @@ -1,79 +0,0 @@ -// SPDX-License-Identifier: MIT -// solhint-disable-next-line one-contract-per-file -pragma solidity ^0.8.6; - -import {VRFTypes} from "./VRFTypes.sol"; - -/** - * @title BatchVRFCoordinatorV2 - * @notice The BatchVRFCoordinatorV2 contract acts as a proxy to write many random responses to the - * provided VRFCoordinatorV2 contract efficiently in a single transaction. - */ -contract BatchVRFCoordinatorV2 { - // solhint-disable-next-line chainlink-solidity/prefix-immutable-variables-with-i - VRFCoordinatorV2 public immutable COORDINATOR; - - event ErrorReturned(uint256 indexed requestId, string reason); - event RawErrorReturned(uint256 indexed requestId, bytes lowLevelData); - - constructor( - address coordinatorAddr - ) { - COORDINATOR = VRFCoordinatorV2(coordinatorAddr); - } - - /** - * @notice fulfills multiple randomness requests with the provided proofs and commitments. - * @param proofs the randomness proofs generated by the VRF provider. - * @param rcs the request commitments corresponding to the randomness proofs. - */ - function fulfillRandomWords( - VRFTypes.Proof[] calldata proofs, - VRFTypes.RequestCommitment[] memory rcs - ) external { - // solhint-disable-next-line gas-custom-errors - require(proofs.length == rcs.length, "input array arg lengths mismatch"); - for (uint256 i = 0; i < proofs.length; i++) { - try COORDINATOR.fulfillRandomWords(proofs[i], rcs[i]) returns ( - uint96 /* payment */ - ) { - continue; - } catch Error(string memory reason) { - uint256 requestId = _getRequestIdFromProof(proofs[i]); - emit ErrorReturned(requestId, reason); - } catch (bytes memory lowLevelData) { - uint256 requestId = _getRequestIdFromProof(proofs[i]); - emit RawErrorReturned(requestId, lowLevelData); - } - } - } - - /** - * @notice Returns the proving key hash associated with this public key. - * @param publicKey the key to return the hash of. - */ - function _hashOfKey( - uint256[2] memory publicKey - ) internal pure returns (bytes32) { - return keccak256(abi.encode(publicKey)); - } - - /** - * @notice Returns the request ID of the request associated with the given proof. - * @param proof the VRF proof provided by the VRF oracle. - */ - function _getRequestIdFromProof( - VRFTypes.Proof memory proof - ) internal pure returns (uint256) { - bytes32 keyHash = _hashOfKey(proof.pk); - return uint256(keccak256(abi.encode(keyHash, proof.seed))); - } -} - -// solhint-disable-next-line interface-starts-with-i -interface VRFCoordinatorV2 { - function fulfillRandomWords( - VRFTypes.Proof calldata proof, - VRFTypes.RequestCommitment memory rc - ) external returns (uint96); -} diff --git a/contracts/src/v0.8/vrf/KeepersVRFConsumer.sol b/contracts/src/v0.8/vrf/KeepersVRFConsumer.sol deleted file mode 100644 index 16bd800f55..0000000000 --- a/contracts/src/v0.8/vrf/KeepersVRFConsumer.sol +++ /dev/null @@ -1,130 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.6; - -import {IAutomationCompatible} from "../automation-cre/interfaces/IAutomationCompatible.sol"; - -import {VRFConsumerBaseV2} from "./VRFConsumerBaseV2.sol"; -import {VRFCoordinatorV2Interface} from "./interfaces/VRFCoordinatorV2Interface.sol"; - -/** - * @title KeepersVRFConsumer - * @notice KeepersVRFConsumer is a Chainlink Keepers compatible contract that also acts as a - * VRF V2 requester and consumer. In particular, a random words request is made when `performUpkeep` - * is called in a cadence provided by the upkeep interval. - */ -// solhint-disable chainlink-solidity/prefix-immutable-variables-with-i -contract KeepersVRFConsumer is IAutomationCompatible, VRFConsumerBaseV2 { - // Upkeep interval in seconds. This contract's performUpkeep method will - // be called by the Keepers network roughly every UPKEEP_INTERVAL seconds. - uint256 public immutable UPKEEP_INTERVAL; - - // VRF V2 information, provided upon contract construction. - VRFCoordinatorV2Interface public immutable COORDINATOR; - uint64 public immutable SUBSCRIPTION_ID; - uint16 public immutable REQUEST_CONFIRMATIONS; - bytes32 public immutable KEY_HASH; - - // Contract state, updated in performUpkeep and fulfillRandomWords. - uint256 public s_lastTimeStamp; - uint256 public s_vrfRequestCounter; - uint256 public s_vrfResponseCounter; - - struct RequestRecord { - uint256 requestId; - bool fulfilled; - uint32 callbackGasLimit; - uint256 randomness; - } - - mapping(uint256 => RequestRecord) public s_requests; /* request ID */ /* request record */ - - constructor( - address vrfCoordinator, - uint64 subscriptionId, - bytes32 keyHash, - uint16 requestConfirmations, - uint256 upkeepInterval - ) VRFConsumerBaseV2(vrfCoordinator) { - COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); - SUBSCRIPTION_ID = subscriptionId; - REQUEST_CONFIRMATIONS = requestConfirmations; - KEY_HASH = keyHash; - UPKEEP_INTERVAL = upkeepInterval; - - s_lastTimeStamp = block.timestamp; - s_vrfRequestCounter = 0; - s_vrfResponseCounter = 0; - } - - /** - * @notice Returns true if and only if at least UPKEEP_INTERVAL seconds have elapsed - * since the last upkeep or since construction of the contract. - * @return upkeepNeeded true if and only if at least UPKEEP_INTERVAL seconds have elapsed since the last upkeep or - * since construction - * of the contract. - */ - // solhint-disable-next-line chainlink-solidity/explicit-returns - function checkUpkeep( - bytes calldata /* checkData */ - ) - external - view - override - returns ( - bool upkeepNeeded, - bytes memory /* performData */ - ) - { - upkeepNeeded = (block.timestamp - s_lastTimeStamp) > UPKEEP_INTERVAL; - } - - /** - * @notice Requests random words from the VRF coordinator if UPKEEP_INTERVAL seconds have elapsed - * since the last upkeep or since construction of the contract. - */ - function performUpkeep( - bytes calldata /* performData */ - ) external override { - if ((block.timestamp - s_lastTimeStamp) > UPKEEP_INTERVAL) { - s_lastTimeStamp = block.timestamp; - - _requestRandomWords(); - } - } - - /** - * @notice VRF callback implementation - * @param requestId the VRF V2 request ID, provided at request time. - * @param randomWords the randomness provided by Chainlink VRF. - */ - // solhint-disable-next-line chainlink-solidity/prefix-internal-functions-with-underscore - function fulfillRandomWords( - uint256 requestId, - uint256[] memory randomWords - ) internal override { - // Check that the request exists. If not, revert. - RequestRecord memory record = s_requests[requestId]; - // solhint-disable-next-line gas-custom-errors - require(record.requestId == requestId, "request ID not found in map"); - - // Update the randomness in the record, and increment the response counter. - s_requests[requestId].randomness = randomWords[0]; - s_vrfResponseCounter++; - } - - /** - * @notice Requests random words from Chainlink VRF. - */ - function _requestRandomWords() internal { - uint256 requestId = COORDINATOR.requestRandomWords( - KEY_HASH, - SUBSCRIPTION_ID, - REQUEST_CONFIRMATIONS, - 150_000, // callback gas limit - 1 // num words - ); - s_requests[requestId] = - RequestRecord({requestId: requestId, fulfilled: false, callbackGasLimit: 150_000, randomness: 0}); - s_vrfRequestCounter++; - } -} diff --git a/contracts/src/v0.8/vrf/VRFConsumerBaseV2.sol b/contracts/src/v0.8/vrf/VRFConsumerBaseV2.sol deleted file mode 100644 index 233c77a60e..0000000000 --- a/contracts/src/v0.8/vrf/VRFConsumerBaseV2.sol +++ /dev/null @@ -1,145 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.4; - -/** - * - * @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 VRFCoordinator - * @dev 2. The consumer contract implements fulfillRandomWords. - * ***************************************************************************** - * @dev USAGE - * - * @dev Calling contracts must inherit from VRFConsumerBase, and can - * @dev initialize VRFConsumerBase's attributes in their constructor as - * @dev shown: - * - * @dev contract VRFConsumer { - * @dev constructor(, address _vrfCoordinator, address _link) - * @dev VRFConsumerBase(_vrfCoordinator) public { - * @dev - * @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 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), - * @dev see (VRFCoordinatorInterface for a description of the arguments). - * - * @dev Once the VRFCoordinator 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 VRFConsumerBase.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 VRFConsumerBaseV2 { - error OnlyCoordinatorCanFulfill(address have, address want); - - // solhint-disable-next-line chainlink-solidity/prefix-immutable-variables-with-i - address private immutable vrfCoordinator; - - /** - * @param _vrfCoordinator address of VRFCoordinator contract - */ - constructor( - address _vrfCoordinator - ) { - vrfCoordinator = _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 VRFConsumerBaseV2 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[] memory 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[] memory randomWords - ) external { - if (msg.sender != vrfCoordinator) { - revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator); - } - fulfillRandomWords(requestId, randomWords); - } -} diff --git a/contracts/src/v0.8/vrf/VRFCoordinatorV2.sol b/contracts/src/v0.8/vrf/VRFCoordinatorV2.sol deleted file mode 100644 index 48a5c2a95a..0000000000 --- a/contracts/src/v0.8/vrf/VRFCoordinatorV2.sol +++ /dev/null @@ -1,876 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.4; - -import {ConfirmedOwner} from "../shared/access/ConfirmedOwner.sol"; -import {AggregatorV3Interface} from "../shared/interfaces/AggregatorV3Interface.sol"; -import {IERC677Receiver} from "../shared/interfaces/IERC677Receiver.sol"; -import {ITypeAndVersion} from "../shared/interfaces/ITypeAndVersion.sol"; -import {LinkTokenInterface} from "../shared/interfaces/LinkTokenInterface.sol"; - -import {ChainSpecificUtil} from "./ChainSpecificUtil_v0_8_6.sol"; -import {VRF} from "./VRF.sol"; -import {VRFConsumerBaseV2} from "./VRFConsumerBaseV2.sol"; -import {BlockhashStoreInterface} from "./interfaces/BlockhashStoreInterface.sol"; -import {VRFCoordinatorV2Interface} from "./interfaces/VRFCoordinatorV2Interface.sol"; - -contract VRFCoordinatorV2 is VRF, ConfirmedOwner, ITypeAndVersion, VRFCoordinatorV2Interface, IERC677Receiver { - // solhint-disable-next-line chainlink-solidity/prefix-immutable-variables-with-i - LinkTokenInterface public immutable LINK; - // solhint-disable-next-line chainlink-solidity/prefix-immutable-variables-with-i - AggregatorV3Interface public immutable LINK_ETH_FEED; - // solhint-disable-next-line chainlink-solidity/prefix-immutable-variables-with-i - BlockhashStoreInterface public immutable BLOCKHASH_STORE; - - // We need to maintain a list of consuming addresses. - // This bound ensures we are able to loop over them as needed. - // Should a user require more consumers, they can use multiple subscriptions. - uint16 public constant MAX_CONSUMERS = 100; - - error TooManyConsumers(); - error InsufficientBalance(); - error InvalidConsumer(uint64 subId, address consumer); - error InvalidSubscription(); - error OnlyCallableFromLink(); - error InvalidCalldata(); - error MustBeSubOwner(address owner); - error PendingRequestExists(); - error MustBeRequestedOwner(address proposedOwner); - error BalanceInvariantViolated(uint256 internalBalance, uint256 externalBalance); // Should never happen - - event FundsRecovered(address to, uint256 amount); - // We use the subscription struct (1 word) - // at fulfillment time. - - struct Subscription { - // There are only 1e9*1e18 = 1e27 juels in existence, so the balance can fit in uint96 (2^96 ~ 7e28) - uint96 balance; // Common link balance used for all consumer requests. - uint64 reqCount; // For fee tiers - } - // We use the config for the mgmt APIs - - struct SubscriptionConfig { - address owner; // Owner can fund/withdraw/cancel the sub. - address requestedOwner; // For safely transferring sub ownership. - // Maintains the list of keys in s_consumers. - // We do this for 2 reasons: - // 1. To be able to clean up all keys from s_consumers when canceling a subscription. - // 2. To be able to return the list of all consumers in getSubscription. - // Note that we need the s_consumers map to be able to directly check if a - // consumer is valid without reading all the consumers from storage. - address[] consumers; - } - // Note a nonce of 0 indicates an the consumer is not assigned to that subscription. - - mapping(address => mapping(uint64 => uint64)) private /* consumer */ /* subId */ /* nonce */ s_consumers; - mapping(uint64 => SubscriptionConfig) private /* subId */ /* subscriptionConfig */ s_subscriptionConfigs; - mapping(uint64 => Subscription) private /* subId */ /* subscription */ s_subscriptions; - // We make the sub count public so that its possible to - // get all the current subscriptions via getSubscription. - uint64 private s_currentSubId; - // s_totalBalance tracks the total link sent to/from - // this contract through onTokenTransfer, cancelSubscription and oracleWithdraw. - // A discrepancy with this contract's link balance indicates someone - // sent tokens using transfer and so we may need to use recoverFunds. - uint96 private s_totalBalance; - - event SubscriptionCreated(uint64 indexed subId, address owner); - event SubscriptionFunded(uint64 indexed subId, uint256 oldBalance, uint256 newBalance); - event SubscriptionConsumerAdded(uint64 indexed subId, address consumer); - event SubscriptionConsumerRemoved(uint64 indexed subId, address consumer); - event SubscriptionCanceled(uint64 indexed subId, address to, uint256 amount); - event SubscriptionOwnerTransferRequested(uint64 indexed subId, address from, address to); - event SubscriptionOwnerTransferred(uint64 indexed subId, address from, address to); - - // Set this maximum to 200 to give us a 56 block window to fulfill - // the request before requiring the block hash feeder. - uint16 public constant MAX_REQUEST_CONFIRMATIONS = 200; - uint32 public constant MAX_NUM_WORDS = 500; - // 5k is plenty for an EXTCODESIZE call (2600) + warm CALL (100) - // and some arithmetic operations. - uint256 private constant GAS_FOR_CALL_EXACT_CHECK = 5000; - - error InvalidRequestConfirmations(uint16 have, uint16 min, uint16 max); - error GasLimitTooBig(uint32 have, uint32 want); - error NumWordsTooBig(uint32 have, uint32 want); - error ProvingKeyAlreadyRegistered(bytes32 keyHash); - error NoSuchProvingKey(bytes32 keyHash); - error InvalidLinkWeiPrice(int256 linkWei); - error InsufficientGasForConsumer(uint256 have, uint256 want); - error NoCorrespondingRequest(); - error IncorrectCommitment(); - error BlockhashNotInStore(uint256 blockNum); - error PaymentTooLarge(); - error Reentrant(); - - struct RequestCommitment { - uint64 blockNum; - uint64 subId; - uint32 callbackGasLimit; - uint32 numWords; - address sender; - } - - mapping(bytes32 => address) private /* keyHash */ /* oracle */ s_provingKeys; - bytes32[] private s_provingKeyHashes; - mapping(address => uint96) private /* oracle */ /* LINK balance */ s_withdrawableTokens; - mapping(uint256 => bytes32) private /* requestID */ /* commitment */ s_requestCommitments; - - event ProvingKeyRegistered(bytes32 keyHash, address indexed oracle); - event ProvingKeyDeregistered(bytes32 keyHash, address indexed oracle); - event RandomWordsRequested( - bytes32 indexed keyHash, - uint256 requestId, - uint256 preSeed, - uint64 indexed subId, - uint16 minimumRequestConfirmations, - uint32 callbackGasLimit, - uint32 numWords, - address indexed sender - ); - event RandomWordsFulfilled(uint256 indexed requestId, uint256 outputSeed, uint96 payment, bool success); - - struct Config { - uint16 minimumRequestConfirmations; - uint32 maxGasLimit; - // Reentrancy protection. - bool reentrancyLock; - // stalenessSeconds is how long before we consider the feed price to be stale - // and fallback to fallbackWeiPerUnitLink. - uint32 stalenessSeconds; - // Gas to cover oracle payment after we calculate the payment. - // We make it configurable in case those operations are repriced. - uint32 gasAfterPaymentCalculation; - } - - int256 private s_fallbackWeiPerUnitLink; - Config private s_config; - FeeConfig private s_feeConfig; - - struct FeeConfig { - // Flat fee charged per fulfillment in millionths of link - // So fee range is [0, 2^32/10^6]. - uint32 fulfillmentFlatFeeLinkPPMTier1; - uint32 fulfillmentFlatFeeLinkPPMTier2; - uint32 fulfillmentFlatFeeLinkPPMTier3; - uint32 fulfillmentFlatFeeLinkPPMTier4; - uint32 fulfillmentFlatFeeLinkPPMTier5; - uint24 reqsForTier2; - uint24 reqsForTier3; - uint24 reqsForTier4; - uint24 reqsForTier5; - } - - event ConfigSet( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation, - int256 fallbackWeiPerUnitLink, - FeeConfig feeConfig - ); - - constructor( - address link, - address blockhashStore, - address linkEthFeed - ) ConfirmedOwner(msg.sender) { - LINK = LinkTokenInterface(link); - LINK_ETH_FEED = AggregatorV3Interface(linkEthFeed); - BLOCKHASH_STORE = BlockhashStoreInterface(blockhashStore); - } - - /** - * @notice Registers a proving key to an oracle. - * @param oracle address of the oracle - * @param publicProvingKey key that oracle can use to submit vrf fulfillments - */ - function registerProvingKey( - address oracle, - uint256[2] calldata publicProvingKey - ) external onlyOwner { - bytes32 kh = hashOfKey(publicProvingKey); - if (s_provingKeys[kh] != address(0)) { - revert ProvingKeyAlreadyRegistered(kh); - } - s_provingKeys[kh] = oracle; - s_provingKeyHashes.push(kh); - emit ProvingKeyRegistered(kh, oracle); - } - - /** - * @notice Deregisters a proving key to an oracle. - * @param publicProvingKey key that oracle can use to submit vrf fulfillments - */ - function deregisterProvingKey( - uint256[2] calldata publicProvingKey - ) external onlyOwner { - bytes32 kh = hashOfKey(publicProvingKey); - address oracle = s_provingKeys[kh]; - if (oracle == address(0)) { - revert NoSuchProvingKey(kh); - } - delete s_provingKeys[kh]; - for (uint256 i = 0; i < s_provingKeyHashes.length; i++) { - if (s_provingKeyHashes[i] == kh) { - bytes32 last = s_provingKeyHashes[s_provingKeyHashes.length - 1]; - // Copy last element and overwrite kh to be deleted with it - s_provingKeyHashes[i] = last; - s_provingKeyHashes.pop(); - } - } - emit ProvingKeyDeregistered(kh, oracle); - } - - /** - * @notice Returns the proving key hash key associated with this public key - * @param publicKey the key to return the hash of - */ - function hashOfKey( - uint256[2] memory publicKey - ) public pure returns (bytes32) { - return keccak256(abi.encode(publicKey)); - } - - /** - * @notice Sets the configuration of the vrfv2 coordinator - * @param minimumRequestConfirmations global min for request confirmations - * @param maxGasLimit global max for request gas limit - * @param stalenessSeconds if the eth/link feed is more stale then this, use the fallback price - * @param gasAfterPaymentCalculation gas used in doing accounting after completing the gas measurement - * @param fallbackWeiPerUnitLink fallback eth/link price in the case of a stale feed - * @param feeConfig fee tier configuration - */ - function setConfig( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation, - int256 fallbackWeiPerUnitLink, - FeeConfig memory feeConfig - ) external onlyOwner { - if (minimumRequestConfirmations > MAX_REQUEST_CONFIRMATIONS) { - revert InvalidRequestConfirmations( - minimumRequestConfirmations, minimumRequestConfirmations, MAX_REQUEST_CONFIRMATIONS - ); - } - if (fallbackWeiPerUnitLink <= 0) { - revert InvalidLinkWeiPrice(fallbackWeiPerUnitLink); - } - s_config = Config({ - minimumRequestConfirmations: minimumRequestConfirmations, - maxGasLimit: maxGasLimit, - stalenessSeconds: stalenessSeconds, - gasAfterPaymentCalculation: gasAfterPaymentCalculation, - reentrancyLock: false - }); - s_feeConfig = feeConfig; - s_fallbackWeiPerUnitLink = fallbackWeiPerUnitLink; - emit ConfigSet( - minimumRequestConfirmations, - maxGasLimit, - stalenessSeconds, - gasAfterPaymentCalculation, - fallbackWeiPerUnitLink, - s_feeConfig - ); - } - - function getConfig() - external - view - returns ( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation - ) - { - return ( - s_config.minimumRequestConfirmations, - s_config.maxGasLimit, - s_config.stalenessSeconds, - s_config.gasAfterPaymentCalculation - ); - } - - function getFeeConfig() - external - view - returns ( - uint32 fulfillmentFlatFeeLinkPPMTier1, - uint32 fulfillmentFlatFeeLinkPPMTier2, - uint32 fulfillmentFlatFeeLinkPPMTier3, - uint32 fulfillmentFlatFeeLinkPPMTier4, - uint32 fulfillmentFlatFeeLinkPPMTier5, - uint24 reqsForTier2, - uint24 reqsForTier3, - uint24 reqsForTier4, - uint24 reqsForTier5 - ) - { - return ( - s_feeConfig.fulfillmentFlatFeeLinkPPMTier1, - s_feeConfig.fulfillmentFlatFeeLinkPPMTier2, - s_feeConfig.fulfillmentFlatFeeLinkPPMTier3, - s_feeConfig.fulfillmentFlatFeeLinkPPMTier4, - s_feeConfig.fulfillmentFlatFeeLinkPPMTier5, - s_feeConfig.reqsForTier2, - s_feeConfig.reqsForTier3, - s_feeConfig.reqsForTier4, - s_feeConfig.reqsForTier5 - ); - } - - function getTotalBalance() external view returns (uint256) { - return s_totalBalance; - } - - function getFallbackWeiPerUnitLink() external view returns (int256) { - return s_fallbackWeiPerUnitLink; - } - - /** - * @notice Owner cancel subscription, sends remaining link directly to the subscription owner. - * @param subId subscription id - * @dev notably can be called even if there are pending requests, outstanding ones may fail onchain - */ - function ownerCancelSubscription( - uint64 subId - ) external onlyOwner { - if (s_subscriptionConfigs[subId].owner == address(0)) { - revert InvalidSubscription(); - } - _cancelSubscriptionHelper(subId, s_subscriptionConfigs[subId].owner); - } - - /** - * @notice Recover link sent with transfer instead of transferAndCall. - * @param to address to send link to - */ - function recoverFunds( - address to - ) external onlyOwner { - uint256 externalBalance = LINK.balanceOf(address(this)); - uint256 internalBalance = uint256(s_totalBalance); - if (internalBalance > externalBalance) { - revert BalanceInvariantViolated(internalBalance, externalBalance); - } - if (internalBalance < externalBalance) { - uint256 amount = externalBalance - internalBalance; - LINK.transfer(to, amount); - emit FundsRecovered(to, amount); - } - // If the balances are equal, nothing to be done. - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function getRequestConfig() external view override returns (uint16, uint32, bytes32[] memory) { - return (s_config.minimumRequestConfirmations, s_config.maxGasLimit, s_provingKeyHashes); - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function requestRandomWords( - bytes32 keyHash, - uint64 subId, - uint16 requestConfirmations, - uint32 callbackGasLimit, - uint32 numWords - ) external override nonReentrant returns (uint256) { - // Input validation using the subscription storage. - if (s_subscriptionConfigs[subId].owner == address(0)) { - revert InvalidSubscription(); - } - // Its important to ensure that the consumer is in fact who they say they - // are, otherwise they could use someone else's subscription balance. - // A nonce of 0 indicates consumer is not allocated to the sub. - uint64 currentNonce = s_consumers[msg.sender][subId]; - if (currentNonce == 0) { - revert InvalidConsumer(subId, msg.sender); - } - // Input validation using the config storage word. - if (requestConfirmations < s_config.minimumRequestConfirmations || requestConfirmations > MAX_REQUEST_CONFIRMATIONS) - { - revert InvalidRequestConfirmations( - requestConfirmations, s_config.minimumRequestConfirmations, MAX_REQUEST_CONFIRMATIONS - ); - } - // No lower bound on the requested gas limit. A user could request 0 - // and they would simply be billed for the proof verification and wouldn't be - // able to do anything with the random value. - if (callbackGasLimit > s_config.maxGasLimit) { - revert GasLimitTooBig(callbackGasLimit, s_config.maxGasLimit); - } - if (numWords > MAX_NUM_WORDS) { - revert NumWordsTooBig(numWords, MAX_NUM_WORDS); - } - // Note we do not check whether the keyHash is valid to save gas. - // The consequence for users is that they can send requests - // for invalid keyHashes which will simply not be fulfilled. - uint64 nonce = currentNonce + 1; - (uint256 requestId, uint256 preSeed) = _computeRequestId(keyHash, msg.sender, subId, nonce); - - s_requestCommitments[requestId] = keccak256( - abi.encode(requestId, ChainSpecificUtil._getBlockNumber(), subId, callbackGasLimit, numWords, msg.sender) - ); - emit RandomWordsRequested( - keyHash, requestId, preSeed, subId, requestConfirmations, callbackGasLimit, numWords, msg.sender - ); - s_consumers[msg.sender][subId] = nonce; - - return requestId; - } - - /** - * @notice Get request commitment - * @param requestId id of request - * @dev used to determine if a request is fulfilled or not - */ - function getCommitment( - uint256 requestId - ) external view returns (bytes32) { - return s_requestCommitments[requestId]; - } - - function _computeRequestId( - bytes32 keyHash, - address sender, - uint64 subId, - uint64 nonce - ) private pure returns (uint256, uint256) { - uint256 preSeed = uint256(keccak256(abi.encode(keyHash, sender, subId, nonce))); - return (uint256(keccak256(abi.encode(keyHash, preSeed))), preSeed); - } - - /** - * @dev calls target address with exactly gasAmount gas and data as calldata - * or reverts if at least gasAmount gas is not available. - */ - function _callWithExactGas( - uint256 gasAmount, - address target, - bytes memory data - ) private returns (bool success) { - assembly { - let g := gas() - // Compute g -= GAS_FOR_CALL_EXACT_CHECK and check for underflow - // The gas actually passed to the callee is min(gasAmount, 63//64*gas available). - // We want to ensure that we revert if gasAmount > 63//64*gas available - // as we do not want to provide them with less, however that check itself costs - // gas. GAS_FOR_CALL_EXACT_CHECK ensures we have at least enough gas to be able - // to revert if gasAmount > 63//64*gas available. - if lt(g, GAS_FOR_CALL_EXACT_CHECK) { revert(0, 0) } - g := sub(g, GAS_FOR_CALL_EXACT_CHECK) - // if g - g//64 <= gasAmount, revert - // (we subtract g//64 because of EIP-150) - if iszero(gt(sub(g, div(g, 64)), gasAmount)) { revert(0, 0) } - // solidity calls check that a contract actually exists at the destination, so we do the same - if iszero(extcodesize(target)) { revert(0, 0) } - // call and return whether we succeeded. ignore return data - // call(gas,addr,value,argsOffset,argsLength,retOffset,retLength) - success := call(gasAmount, target, 0, add(data, 0x20), mload(data), 0, 0) - } - return success; - } - - function _getRandomnessFromProof( - Proof calldata proof, - RequestCommitment memory rc - ) private view returns (bytes32 keyHash, uint256 requestId, uint256 randomness) { - keyHash = hashOfKey(proof.pk); - // Only registered proving keys are permitted. - address oracle = s_provingKeys[keyHash]; - if (oracle == address(0)) { - revert NoSuchProvingKey(keyHash); - } - requestId = uint256(keccak256(abi.encode(keyHash, proof.seed))); - bytes32 commitment = s_requestCommitments[requestId]; - if (commitment == 0) { - revert NoCorrespondingRequest(); - } - if ( - commitment != keccak256(abi.encode(requestId, rc.blockNum, rc.subId, rc.callbackGasLimit, rc.numWords, rc.sender)) - ) { - revert IncorrectCommitment(); - } - - bytes32 blockHash = ChainSpecificUtil._getBlockhash(rc.blockNum); - if (blockHash == bytes32(0)) { - blockHash = BLOCKHASH_STORE.getBlockhash(rc.blockNum); - if (blockHash == bytes32(0)) { - revert BlockhashNotInStore(rc.blockNum); - } - } - - // The seed actually used by the VRF machinery, mixing in the blockhash - uint256 actualSeed = uint256(keccak256(abi.encodePacked(proof.seed, blockHash))); - randomness = VRF._randomValueFromVRFProof(proof, actualSeed); // Reverts on failure - return (keyHash, requestId, randomness); - } - - /* - * @notice Compute fee based on the request count - * @param reqCount number of requests - * @return feePPM fee in LINK PPM - */ - function getFeeTier( - uint64 reqCount - ) public view returns (uint32) { - FeeConfig memory fc = s_feeConfig; - if (0 <= reqCount && reqCount <= fc.reqsForTier2) { - return fc.fulfillmentFlatFeeLinkPPMTier1; - } - if (fc.reqsForTier2 < reqCount && reqCount <= fc.reqsForTier3) { - return fc.fulfillmentFlatFeeLinkPPMTier2; - } - if (fc.reqsForTier3 < reqCount && reqCount <= fc.reqsForTier4) { - return fc.fulfillmentFlatFeeLinkPPMTier3; - } - if (fc.reqsForTier4 < reqCount && reqCount <= fc.reqsForTier5) { - return fc.fulfillmentFlatFeeLinkPPMTier4; - } - return fc.fulfillmentFlatFeeLinkPPMTier5; - } - - /* - * @notice Fulfill a randomness request - * @param proof contains the proof and randomness - * @param rc request commitment pre-image, committed to at request time - * @return payment amount billed to the subscription - * @dev simulated offchain to determine if sufficient balance is present to fulfill the request - */ - function fulfillRandomWords( - Proof calldata proof, - RequestCommitment memory rc - ) external nonReentrant returns (uint96) { - uint256 startGas = gasleft(); - (bytes32 keyHash, uint256 requestId, uint256 randomness) = _getRandomnessFromProof(proof, rc); - - uint256[] memory randomWords = new uint256[](rc.numWords); - for (uint256 i = 0; i < rc.numWords; i++) { - randomWords[i] = uint256(keccak256(abi.encode(randomness, i))); - } - - delete s_requestCommitments[requestId]; - VRFConsumerBaseV2 v; - bytes memory resp = abi.encodeWithSelector(v.rawFulfillRandomWords.selector, requestId, randomWords); - // Call with explicitly the amount of callback gas requested - // Important to not let them exhaust the gas budget and avoid oracle payment. - // Do not allow any non-view/non-pure coordinator functions to be called - // during the consumers callback code via reentrancyLock. - // Note that _callWithExactGas will revert if we do not have sufficient gas - // to give the callee their requested amount. - s_config.reentrancyLock = true; - bool success = _callWithExactGas(rc.callbackGasLimit, rc.sender, resp); - s_config.reentrancyLock = false; - - // Increment the req count for fee tier selection. - uint64 reqCount = s_subscriptions[rc.subId].reqCount; - s_subscriptions[rc.subId].reqCount += 1; - - // We want to charge users exactly for how much gas they use in their callback. - // The gasAfterPaymentCalculation is meant to cover these additional operations where we - // decrement the subscription balance and increment the oracles withdrawable balance. - // We also add the flat link fee to the payment amount. - // Its specified in millionths of link, if s_config.fulfillmentFlatFeeLinkPPM = 1 - // 1 link / 1e6 = 1e18 juels / 1e6 = 1e12 juels. - uint96 payment = - _calculatePaymentAmount(startGas, s_config.gasAfterPaymentCalculation, getFeeTier(reqCount), tx.gasprice); - if (s_subscriptions[rc.subId].balance < payment) { - revert InsufficientBalance(); - } - s_subscriptions[rc.subId].balance -= payment; - s_withdrawableTokens[s_provingKeys[keyHash]] += payment; - // Include payment in the event for tracking costs. - emit RandomWordsFulfilled(requestId, randomness, payment, success); - return payment; - } - - // Get the amount of gas used for fulfillment - function _calculatePaymentAmount( - uint256 startGas, - uint256 gasAfterPaymentCalculation, - uint32 fulfillmentFlatFeeLinkPPM, - uint256 weiPerUnitGas - ) internal view returns (uint96) { - int256 weiPerUnitLink; - weiPerUnitLink = _getFeedData(); - if (weiPerUnitLink <= 0) { - revert InvalidLinkWeiPrice(weiPerUnitLink); - } - // Will return non-zero on chains that have this enabled - uint256 l1CostWei = ChainSpecificUtil._getCurrentTxL1GasFees(msg.data); - // (1e18 juels/link) ((wei/gas * gas) + l1wei) / (wei/link) = juels - uint256 paymentNoFee = (1e18 * (weiPerUnitGas * (gasAfterPaymentCalculation + startGas - gasleft()) + l1CostWei)) - / uint256(weiPerUnitLink); - uint256 fee = 1e12 * uint256(fulfillmentFlatFeeLinkPPM); - if (paymentNoFee > (1e27 - fee)) { - revert PaymentTooLarge(); // Payment + fee cannot be more than all of the link in existence. - } - return uint96(paymentNoFee + fee); - } - - function _getFeedData() private view returns (int256) { - uint32 stalenessSeconds = s_config.stalenessSeconds; - bool staleFallback = stalenessSeconds > 0; - uint256 timestamp; - int256 weiPerUnitLink; - (, weiPerUnitLink,, timestamp,) = LINK_ETH_FEED.latestRoundData(); - // solhint-disable-next-line not-rely-on-time - if (staleFallback && stalenessSeconds < block.timestamp - timestamp) { - weiPerUnitLink = s_fallbackWeiPerUnitLink; - } - return weiPerUnitLink; - } - - /* - * @notice Oracle withdraw LINK earned through fulfilling requests - * @param recipient where to send the funds - * @param amount amount to withdraw - */ - function oracleWithdraw( - address recipient, - uint96 amount - ) external nonReentrant { - if (s_withdrawableTokens[msg.sender] < amount) { - revert InsufficientBalance(); - } - s_withdrawableTokens[msg.sender] -= amount; - s_totalBalance -= amount; - if (!LINK.transfer(recipient, amount)) { - revert InsufficientBalance(); - } - } - - function onTokenTransfer( - address, - /* sender */ - uint256 amount, - bytes calldata data - ) external override nonReentrant { - if (msg.sender != address(LINK)) { - revert OnlyCallableFromLink(); - } - if (data.length != 32) { - revert InvalidCalldata(); - } - uint64 subId = abi.decode(data, (uint64)); - if (s_subscriptionConfigs[subId].owner == address(0)) { - revert InvalidSubscription(); - } - // We do not check that the msg.sender is the subscription owner, - // anyone can fund a subscription. - uint256 oldBalance = s_subscriptions[subId].balance; - s_subscriptions[subId].balance += uint96(amount); - s_totalBalance += uint96(amount); - emit SubscriptionFunded(subId, oldBalance, oldBalance + amount); - } - - function getCurrentSubId() external view returns (uint64) { - return s_currentSubId; - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function getSubscription( - uint64 subId - ) external view override returns (uint96 balance, uint64 reqCount, address owner, address[] memory consumers) { - if (s_subscriptionConfigs[subId].owner == address(0)) { - revert InvalidSubscription(); - } - return ( - s_subscriptions[subId].balance, - s_subscriptions[subId].reqCount, - s_subscriptionConfigs[subId].owner, - s_subscriptionConfigs[subId].consumers - ); - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function createSubscription() external override nonReentrant returns (uint64) { - s_currentSubId++; - uint64 currentSubId = s_currentSubId; - address[] memory consumers = new address[](0); - s_subscriptions[currentSubId] = Subscription({balance: 0, reqCount: 0}); - s_subscriptionConfigs[currentSubId] = - SubscriptionConfig({owner: msg.sender, requestedOwner: address(0), consumers: consumers}); - - emit SubscriptionCreated(currentSubId, msg.sender); - return currentSubId; - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function requestSubscriptionOwnerTransfer( - uint64 subId, - address newOwner - ) external override onlySubOwner(subId) nonReentrant { - // Proposing to address(0) would never be claimable so don't need to check. - if (s_subscriptionConfigs[subId].requestedOwner != newOwner) { - s_subscriptionConfigs[subId].requestedOwner = newOwner; - emit SubscriptionOwnerTransferRequested(subId, msg.sender, newOwner); - } - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function acceptSubscriptionOwnerTransfer( - uint64 subId - ) external override nonReentrant { - if (s_subscriptionConfigs[subId].owner == address(0)) { - revert InvalidSubscription(); - } - if (s_subscriptionConfigs[subId].requestedOwner != msg.sender) { - revert MustBeRequestedOwner(s_subscriptionConfigs[subId].requestedOwner); - } - address oldOwner = s_subscriptionConfigs[subId].owner; - s_subscriptionConfigs[subId].owner = msg.sender; - s_subscriptionConfigs[subId].requestedOwner = address(0); - emit SubscriptionOwnerTransferred(subId, oldOwner, msg.sender); - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function removeConsumer( - uint64 subId, - address consumer - ) external override onlySubOwner(subId) nonReentrant { - if (pendingRequestExists(subId)) { - revert PendingRequestExists(); - } - if (s_consumers[consumer][subId] == 0) { - revert InvalidConsumer(subId, consumer); - } - // Note bounded by MAX_CONSUMERS - address[] memory consumers = s_subscriptionConfigs[subId].consumers; - uint256 lastConsumerIndex = consumers.length - 1; - for (uint256 i = 0; i < consumers.length; i++) { - if (consumers[i] == consumer) { - address last = consumers[lastConsumerIndex]; - // Storage write to preserve last element - s_subscriptionConfigs[subId].consumers[i] = last; - // Storage remove last element - s_subscriptionConfigs[subId].consumers.pop(); - break; - } - } - delete s_consumers[consumer][subId]; - emit SubscriptionConsumerRemoved(subId, consumer); - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function addConsumer( - uint64 subId, - address consumer - ) external override onlySubOwner(subId) nonReentrant { - // Already maxed, cannot add any more consumers. - if (s_subscriptionConfigs[subId].consumers.length == MAX_CONSUMERS) { - revert TooManyConsumers(); - } - if (s_consumers[consumer][subId] != 0) { - // Idempotence - do nothing if already added. - // Ensures uniqueness in s_subscriptions[subId].consumers. - return; - } - // Initialize the nonce to 1, indicating the consumer is allocated. - s_consumers[consumer][subId] = 1; - s_subscriptionConfigs[subId].consumers.push(consumer); - - emit SubscriptionConsumerAdded(subId, consumer); - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function cancelSubscription( - uint64 subId, - address to - ) external override onlySubOwner(subId) nonReentrant { - if (pendingRequestExists(subId)) { - revert PendingRequestExists(); - } - _cancelSubscriptionHelper(subId, to); - } - - function _cancelSubscriptionHelper( - uint64 subId, - address to - ) private nonReentrant { - SubscriptionConfig memory subConfig = s_subscriptionConfigs[subId]; - Subscription memory sub = s_subscriptions[subId]; - uint96 balance = sub.balance; - // Note bounded by MAX_CONSUMERS; - // If no consumers, does nothing. - for (uint256 i = 0; i < subConfig.consumers.length; i++) { - delete s_consumers[subConfig.consumers[i]][subId]; - } - delete s_subscriptionConfigs[subId]; - delete s_subscriptions[subId]; - s_totalBalance -= balance; - if (!LINK.transfer(to, uint256(balance))) { - revert InsufficientBalance(); - } - emit SubscriptionCanceled(subId, to, balance); - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - * @dev Looping is bounded to MAX_CONSUMERS*(number of keyhashes). - * @dev Used to disable subscription canceling while outstanding request are present. - */ - function pendingRequestExists( - uint64 subId - ) public view override returns (bool) { - SubscriptionConfig memory subConfig = s_subscriptionConfigs[subId]; - for (uint256 i = 0; i < subConfig.consumers.length; i++) { - for (uint256 j = 0; j < s_provingKeyHashes.length; j++) { - (uint256 reqId,) = _computeRequestId( - s_provingKeyHashes[j], subConfig.consumers[i], subId, s_consumers[subConfig.consumers[i]][subId] - ); - if (s_requestCommitments[reqId] != 0) { - return true; - } - } - } - return false; - } - - modifier onlySubOwner( - uint64 subId - ) { - address owner = s_subscriptionConfigs[subId].owner; - if (owner == address(0)) { - revert InvalidSubscription(); - } - if (msg.sender != owner) { - revert MustBeSubOwner(owner); - } - _; - } - - modifier nonReentrant() { - if (s_config.reentrancyLock) { - revert Reentrant(); - } - _; - } - - /** - * @notice The type and version of this contract - * @return Type and version string - */ - function typeAndVersion() external pure virtual override returns (string memory) { - return "VRFCoordinatorV2 1.0.0"; - } -} diff --git a/contracts/src/v0.8/vrf/VRFOwner.sol b/contracts/src/v0.8/vrf/VRFOwner.sol deleted file mode 100644 index 4b3adcd913..0000000000 --- a/contracts/src/v0.8/vrf/VRFOwner.sol +++ /dev/null @@ -1,376 +0,0 @@ -// SPDX-License-Identifier: MIT -// solhint-disable-next-line one-contract-per-file -pragma solidity ^0.8.6; - -import {ConfirmedOwner} from "../shared/access/ConfirmedOwner.sol"; -import {AuthorizedReceiver} from "./AuthorizedReceiver.sol"; -import {VRFTypes} from "./VRFTypes.sol"; - -// Taken from VRFCoordinatorV2.sol -// Must be abi-compatible with what's there -struct FeeConfig { - // Flat fee charged per fulfillment in millionths of link - // So fee range is [0, 2^32/10^6]. - uint32 fulfillmentFlatFeeLinkPPMTier1; - uint32 fulfillmentFlatFeeLinkPPMTier2; - uint32 fulfillmentFlatFeeLinkPPMTier3; - uint32 fulfillmentFlatFeeLinkPPMTier4; - uint32 fulfillmentFlatFeeLinkPPMTier5; - uint24 reqsForTier2; - uint24 reqsForTier3; - uint24 reqsForTier4; - uint24 reqsForTier5; -} - -// Taken from VRFCoordinatorV2.sol -// Must be abi-compatible with what's there -struct Config { - uint16 minimumRequestConfirmations; - uint32 maxGasLimit; - // stalenessSeconds is how long before we consider the feed price to be stale - // and fallback to fallbackWeiPerUnitLink. - uint32 stalenessSeconds; - // Gas to cover oracle payment after we calculate the payment. - // We make it configurable in case those operations are repriced. - uint32 gasAfterPaymentCalculation; - int256 fallbackWeiPerUnitLink; - FeeConfig feeConfig; -} - -/// @dev IVRFCoordinatorV2 is the set of functions on the VRF coordinator V2 -/// @dev that are used in the VRF Owner contract below. -interface IVRFCoordinatorV2 { - function acceptOwnership() external; - - function transferOwnership( - address to - ) external; - - function registerProvingKey( - address oracle, - uint256[2] calldata publicProvingKey - ) external; - - function deregisterProvingKey( - uint256[2] calldata publicProvingKey - ) external; - - function setConfig( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation, - int256 fallbackWeiPerUnitLink, - FeeConfig memory feeConfig - ) external; - - function getConfig() - external - view - returns ( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation - ); - - function getFeeConfig() - external - view - returns ( - uint32 fulfillmentFlatFeeLinkPPMTier1, - uint32 fulfillmentFlatFeeLinkPPMTier2, - uint32 fulfillmentFlatFeeLinkPPMTier3, - uint32 fulfillmentFlatFeeLinkPPMTier4, - uint32 fulfillmentFlatFeeLinkPPMTier5, - uint24 reqsForTier2, - uint24 reqsForTier3, - uint24 reqsForTier4, - uint24 reqsForTier5 - ); - - function getFallbackWeiPerUnitLink() external view returns (int256); - - function ownerCancelSubscription( - uint64 subId - ) external; - - function recoverFunds( - address to - ) external; - - function hashOfKey( - uint256[2] memory publicKey - ) external pure returns (bytes32); - - function fulfillRandomWords( - VRFTypes.Proof calldata proof, - VRFTypes.RequestCommitment memory rc - ) external returns (uint96); -} - -/** - * @notice VRFOwner is a contract that acts as the owner of the VRF - * @notice coordinator, with some useful utilities in the event extraordinary - * @notice things happen on-chain (i.e ETH/LINK price wildly fluctuates, and - * @notice a VRF fulfillment reverts on-chain). - */ -contract VRFOwner is ConfirmedOwner, AuthorizedReceiver { - int256 private constant MAX_INT256 = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; - - IVRFCoordinatorV2 internal s_vrfCoordinator; - - event RandomWordsForced(uint256 indexed requestId, uint64 indexed subId, address indexed sender); - - constructor( - address _vrfCoordinator - ) ConfirmedOwner(msg.sender) { - // solhint-disable-next-line gas-custom-errors - require(_vrfCoordinator != address(0), "vrf coordinator address must be non-zero"); - s_vrfCoordinator = IVRFCoordinatorV2(_vrfCoordinator); - } - - /** - * @notice Accepts ownership of the VRF coordinator if transferred to us. - */ - function acceptVRFOwnership() external onlyOwner { - s_vrfCoordinator.acceptOwnership(); - } - - /** - * @notice Transfers ownership of the VRF coordinator to the specified address. - * @param to the address to transfer ownership of the VRF Coordinator to. - */ - function transferVRFOwnership( - address to - ) external onlyOwner { - s_vrfCoordinator.transferOwnership(to); - } - - /** - * @notice Returns the address of the VRF coordinator reference in this contract. - * @return The address of the VRF coordinator reference in this contract. - */ - function getVRFCoordinator() public view returns (address) { - return address(s_vrfCoordinator); - } - - /** - * @notice Registers a proving key to an oracle. - * @param oracle address of the oracle - * @param publicProvingKey key that oracle can use to submit vrf fulfillments - */ - function registerProvingKey( - address oracle, - uint256[2] calldata publicProvingKey - ) external onlyOwner { - s_vrfCoordinator.registerProvingKey(oracle, publicProvingKey); - } - - /** - * @notice Deregisters a proving key to an oracle. - * @param publicProvingKey key that oracle can use to submit vrf fulfillments - */ - function deregisterProvingKey( - uint256[2] calldata publicProvingKey - ) external onlyOwner { - s_vrfCoordinator.deregisterProvingKey(publicProvingKey); - } - - /** - * @notice Sets the configuration of the vrfv2 coordinator - * @param minimumRequestConfirmations global min for request confirmations - * @param maxGasLimit global max for request gas limit - * @param stalenessSeconds if the eth/link feed is more stale then this, use the fallback price - * @param gasAfterPaymentCalculation gas used in doing accounting after completing the gas measurement - * @param fallbackWeiPerUnitLink fallback eth/link price in the case of a stale feed - * @param feeConfig fee tier configuration - */ - function setConfig( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation, - int256 fallbackWeiPerUnitLink, - FeeConfig memory feeConfig - ) public onlyOwner { - s_vrfCoordinator.setConfig( - minimumRequestConfirmations, - maxGasLimit, - stalenessSeconds, - gasAfterPaymentCalculation, - fallbackWeiPerUnitLink, - feeConfig - ); - } - - /** - * @notice Sets the configuration of the vrfv2 coordinator - only to be used from within fulfillRandomWords. - * @dev The reason plain setConfig cannot be used is that it is marked as onlyOwner. Since fulfillRandomWords - * @dev is gated by authorized senders, and the authorized senders are not necessarily owners, the call will - * @dev always fail if the caller of fulfillRandomWords is not the owner, which is not what we want. - * @param minimumRequestConfirmations global min for request confirmations - * @param maxGasLimit global max for request gas limit - * @param stalenessSeconds if the eth/link feed is more stale then this, use the fallback price - * @param gasAfterPaymentCalculation gas used in doing accounting after completing the gas measurement - * @param fallbackWeiPerUnitLink fallback eth/link price in the case of a stale feed - * @param feeConfig fee tier configuration - */ - function _setConfig( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation, - int256 fallbackWeiPerUnitLink, - FeeConfig memory feeConfig - ) private { - s_vrfCoordinator.setConfig( - minimumRequestConfirmations, - maxGasLimit, - stalenessSeconds, - gasAfterPaymentCalculation, - fallbackWeiPerUnitLink, - feeConfig - ); - } - - /** - * @notice Owner cancel subscription, sends remaining link directly to the subscription owner. - * @param subId subscription id - * @dev notably can be called even if there are pending requests, outstanding ones may fail onchain - */ - function ownerCancelSubscription( - uint64 subId - ) external onlyOwner { - s_vrfCoordinator.ownerCancelSubscription(subId); - } - - /** - * @notice Recover link sent with transfer instead of transferAndCall. - * @param to address to send link to - */ - function recoverFunds( - address to - ) external onlyOwner { - s_vrfCoordinator.recoverFunds(to); - } - - /** - * @notice Get all relevant configs from the VRF coordinator. - * @dev This is done in a separate function to avoid the "stack too deep" issue - * @dev when too many local variables are in the same scope. - * @return Config struct containing all relevant configs from the VRF coordinator. - */ - function _getConfigs() private view returns (Config memory) { - ( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation - ) = s_vrfCoordinator.getConfig(); - ( - uint32 fulfillmentFlatFeeLinkPPMTier1, - uint32 fulfillmentFlatFeeLinkPPMTier2, - uint32 fulfillmentFlatFeeLinkPPMTier3, - uint32 fulfillmentFlatFeeLinkPPMTier4, - uint32 fulfillmentFlatFeeLinkPPMTier5, - uint24 reqsForTier2, - uint24 reqsForTier3, - uint24 reqsForTier4, - uint24 reqsForTier5 - ) = s_vrfCoordinator.getFeeConfig(); - int256 fallbackWeiPerUnitLink = s_vrfCoordinator.getFallbackWeiPerUnitLink(); - return Config({ - minimumRequestConfirmations: minimumRequestConfirmations, - maxGasLimit: maxGasLimit, - stalenessSeconds: stalenessSeconds, - gasAfterPaymentCalculation: gasAfterPaymentCalculation, - fallbackWeiPerUnitLink: fallbackWeiPerUnitLink, - feeConfig: FeeConfig({ - fulfillmentFlatFeeLinkPPMTier1: fulfillmentFlatFeeLinkPPMTier1, - fulfillmentFlatFeeLinkPPMTier2: fulfillmentFlatFeeLinkPPMTier2, - fulfillmentFlatFeeLinkPPMTier3: fulfillmentFlatFeeLinkPPMTier3, - fulfillmentFlatFeeLinkPPMTier4: fulfillmentFlatFeeLinkPPMTier4, - fulfillmentFlatFeeLinkPPMTier5: fulfillmentFlatFeeLinkPPMTier5, - reqsForTier2: reqsForTier2, - reqsForTier3: reqsForTier3, - reqsForTier4: reqsForTier4, - reqsForTier5: reqsForTier5 - }) - }); - } - - /** - * @notice Fulfill a randomness request - * @param proof contains the proof and randomness - * @param rc request commitment pre-image, committed to at request time - */ - function fulfillRandomWords( - VRFTypes.Proof calldata proof, - VRFTypes.RequestCommitment memory rc - ) external validateAuthorizedSender { - uint256 requestId = _requestIdFromProof(proof.pk, proof.seed); - - // Get current configs to restore them to original values after - // calling _setConfig. - Config memory cfg = _getConfigs(); - - // call _setConfig with the appropriate params in order to fulfill - // an accidentally-underfunded request. - _setConfig( - cfg.minimumRequestConfirmations, - cfg.maxGasLimit, - 1, // stalenessSeconds - 0, // gasAfterPaymentCalculation - MAX_INT256, // fallbackWeiPerUnitLink - FeeConfig({ - fulfillmentFlatFeeLinkPPMTier1: 0, - fulfillmentFlatFeeLinkPPMTier2: 0, - fulfillmentFlatFeeLinkPPMTier3: 0, - fulfillmentFlatFeeLinkPPMTier4: 0, - fulfillmentFlatFeeLinkPPMTier5: 0, - reqsForTier2: 0, - reqsForTier3: 0, - reqsForTier4: 0, - reqsForTier5: 0 - }) - ); - - s_vrfCoordinator.fulfillRandomWords(proof, rc); - - // reset configuration back to old values. - _setConfig( - cfg.minimumRequestConfirmations, - cfg.maxGasLimit, - cfg.stalenessSeconds, - cfg.gasAfterPaymentCalculation, - cfg.fallbackWeiPerUnitLink, - cfg.feeConfig - ); - - emit RandomWordsForced(requestId, rc.subId, rc.sender); - } - - /** - * @notice Concrete implementation of AuthorizedReceiver - * @return bool of whether sender is authorized - */ - function _canSetAuthorizedSenders() internal view override returns (bool) { - return owner() == msg.sender; - } - - /** - * @notice Returns the request for corresponding to the given public key and proof seed. - * @param publicKey the VRF public key associated with the proof - * @param proofSeed the proof seed - * @dev Refer to VRFCoordinatorV2.getRandomnessFromProof for original implementation. - */ - function _requestIdFromProof( - uint256[2] memory publicKey, - uint256 proofSeed - ) private view returns (uint256) { - bytes32 keyHash = s_vrfCoordinator.hashOfKey(publicKey); - uint256 requestId = uint256(keccak256(abi.encode(keyHash, proofSeed))); - return requestId; - } -} diff --git a/contracts/src/v0.8/vrf/VRFSubscriptionBalanceMonitor.sol b/contracts/src/v0.8/vrf/VRFSubscriptionBalanceMonitor.sol deleted file mode 100644 index c03179a733..0000000000 --- a/contracts/src/v0.8/vrf/VRFSubscriptionBalanceMonitor.sol +++ /dev/null @@ -1,291 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.6; - -import {IAutomationCompatible} from "../automation-cre/interfaces/IAutomationCompatible.sol"; - -import {ConfirmedOwner} from "../shared/access/ConfirmedOwner.sol"; -import {LinkTokenInterface} from "../shared/interfaces/LinkTokenInterface.sol"; -import {VRFCoordinatorV2Interface} from "./interfaces/VRFCoordinatorV2Interface.sol"; -import {Pausable} from "@openzeppelin/contracts@4.9.6/security/Pausable.sol"; - -/** - * @title The VRFSubscriptionBalanceMonitor contract. - * @notice A keeper-compatible contract that monitors and funds VRF subscriptions. - */ -contract VRFSubscriptionBalanceMonitor is ConfirmedOwner, Pausable, IAutomationCompatible { - VRFCoordinatorV2Interface public COORDINATOR; - LinkTokenInterface public LINKTOKEN; - - uint256 private constant MIN_GAS_FOR_TRANSFER = 55_000; - - event FundsAdded(uint256 amountAdded, uint256 newBalance, address sender); - event FundsWithdrawn(uint256 amountWithdrawn, address payee); - event TopUpSucceeded(uint64 indexed subscriptionId); - event TopUpFailed(uint64 indexed subscriptionId); - event KeeperRegistryAddressUpdated(address oldAddress, address newAddress); - event VRFCoordinatorV2AddressUpdated(address oldAddress, address newAddress); - event LinkTokenAddressUpdated(address oldAddress, address newAddress); - event MinWaitPeriodUpdated(uint256 oldMinWaitPeriod, uint256 newMinWaitPeriod); - event OutOfGas(uint256 lastId); - - error InvalidWatchList(); - error OnlyKeeperRegistry(); - error DuplicateSubcriptionId(uint64 duplicate); - - struct Target { - bool isActive; - uint96 minBalanceJuels; - uint96 topUpAmountJuels; - uint56 lastTopUpTimestamp; - } - - address public s_keeperRegistryAddress; // the address of the keeper registry - uint256 public s_minWaitPeriodSeconds; // minimum time to wait between top-ups - uint64[] public s_watchList; // the watchlist on which subscriptions are stored - mapping(uint64 => Target) internal s_targets; - - /** - * @param linkTokenAddress the Link token address - * @param coordinatorAddress the address of the vrf coordinator contract - * @param keeperRegistryAddress the address of the keeper registry contract - * @param minWaitPeriodSeconds the minimum wait period for addresses between funding - */ - constructor( - address linkTokenAddress, - address coordinatorAddress, - address keeperRegistryAddress, - uint256 minWaitPeriodSeconds - ) ConfirmedOwner(msg.sender) { - setLinkTokenAddress(linkTokenAddress); - setVRFCoordinatorV2Address(coordinatorAddress); - setKeeperRegistryAddress(keeperRegistryAddress); - setMinWaitPeriodSeconds(minWaitPeriodSeconds); - } - - /** - * @notice Sets the list of subscriptions to watch and their funding parameters. - * @param subscriptionIds the list of subscription ids to watch - * @param minBalancesJuels the minimum balances for each subscription - * @param topUpAmountsJuels the amount to top up each subscription - */ - function setWatchList( - uint64[] calldata subscriptionIds, - uint96[] calldata minBalancesJuels, - uint96[] calldata topUpAmountsJuels - ) external onlyOwner { - if (subscriptionIds.length != minBalancesJuels.length || subscriptionIds.length != topUpAmountsJuels.length) { - revert InvalidWatchList(); - } - uint64[] memory oldWatchList = s_watchList; - for (uint256 idx = 0; idx < oldWatchList.length; idx++) { - s_targets[oldWatchList[idx]].isActive = false; - } - for (uint256 idx = 0; idx < subscriptionIds.length; idx++) { - if (s_targets[subscriptionIds[idx]].isActive) { - revert DuplicateSubcriptionId(subscriptionIds[idx]); - } - if (subscriptionIds[idx] == 0) { - revert InvalidWatchList(); - } - if (topUpAmountsJuels[idx] <= minBalancesJuels[idx]) { - revert InvalidWatchList(); - } - s_targets[subscriptionIds[idx]] = Target({ - isActive: true, - minBalanceJuels: minBalancesJuels[idx], - topUpAmountJuels: topUpAmountsJuels[idx], - lastTopUpTimestamp: 0 - }); - } - s_watchList = subscriptionIds; - } - - /** - * @notice Gets a list of subscriptions that are underfunded. - * @return list of subscriptions that are underfunded - */ - function getUnderfundedSubscriptions() public view returns (uint64[] memory) { - uint64[] memory watchList = s_watchList; - uint64[] memory needsFunding = new uint64[](watchList.length); - uint256 count = 0; - uint256 minWaitPeriod = s_minWaitPeriodSeconds; - uint256 contractBalance = LINKTOKEN.balanceOf(address(this)); - Target memory target; - for (uint256 idx = 0; idx < watchList.length; idx++) { - target = s_targets[watchList[idx]]; - (uint96 subscriptionBalance,,,) = COORDINATOR.getSubscription(watchList[idx]); - if ( - target.lastTopUpTimestamp + minWaitPeriod <= block.timestamp && contractBalance >= target.topUpAmountJuels - && subscriptionBalance < target.minBalanceJuels - ) { - needsFunding[count] = watchList[idx]; - count++; - contractBalance -= target.topUpAmountJuels; - } - } - if (count < watchList.length) { - assembly { - mstore(needsFunding, count) - } - } - return needsFunding; - } - - /** - * @notice Send funds to the subscriptions provided. - * @param needsFunding the list of subscriptions to fund - */ - function topUp( - uint64[] memory needsFunding - ) public whenNotPaused { - uint256 minWaitPeriodSeconds = s_minWaitPeriodSeconds; - uint256 contractBalance = LINKTOKEN.balanceOf(address(this)); - Target memory target; - for (uint256 idx = 0; idx < needsFunding.length; idx++) { - target = s_targets[needsFunding[idx]]; - (uint96 subscriptionBalance,,,) = COORDINATOR.getSubscription(needsFunding[idx]); - if ( - target.isActive && target.lastTopUpTimestamp + minWaitPeriodSeconds <= block.timestamp - && subscriptionBalance < target.minBalanceJuels && contractBalance >= target.topUpAmountJuels - ) { - bool success = - LINKTOKEN.transferAndCall(address(COORDINATOR), target.topUpAmountJuels, abi.encode(needsFunding[idx])); - if (success) { - s_targets[needsFunding[idx]].lastTopUpTimestamp = uint56(block.timestamp); - contractBalance -= target.topUpAmountJuels; - emit TopUpSucceeded(needsFunding[idx]); - } else { - emit TopUpFailed(needsFunding[idx]); - } - } - if (gasleft() < MIN_GAS_FOR_TRANSFER) { - emit OutOfGas(idx); - return; - } - } - } - - /** - * @notice Gets list of subscription ids that are underfunded and returns a keeper-compatible payload. - * @return upkeepNeeded signals if upkeep is needed, performData is an abi encoded list of subscription ids that need - * funds - */ - function checkUpkeep( - bytes calldata - ) external view override whenNotPaused returns (bool upkeepNeeded, bytes memory performData) { - uint64[] memory needsFunding = getUnderfundedSubscriptions(); - upkeepNeeded = needsFunding.length > 0; - performData = abi.encode(needsFunding); - return (upkeepNeeded, performData); - } - - /** - * @notice Called by the keeper to send funds to underfunded addresses. - * @param performData the abi encoded list of addresses to fund - */ - function performUpkeep( - bytes calldata performData - ) external override onlyKeeperRegistry whenNotPaused { - uint64[] memory needsFunding = abi.decode(performData, (uint64[])); - topUp(needsFunding); - } - - /** - * @notice Withdraws the contract balance in LINK. - * @param amount the amount of LINK (in juels) to withdraw - * @param payee the address to pay - */ - function withdraw( - uint256 amount, - address payable payee - ) external onlyOwner { - // solhint-disable-next-line gas-custom-errors, reason-string - require(payee != address(0)); - emit FundsWithdrawn(amount, payee); - LINKTOKEN.transfer(payee, amount); - } - - /** - * @notice Sets the LINK token address. - */ - function setLinkTokenAddress( - address linkTokenAddress - ) public onlyOwner { - // solhint-disable-next-line gas-custom-errors, reason-string - require(linkTokenAddress != address(0)); - emit LinkTokenAddressUpdated(address(LINKTOKEN), linkTokenAddress); - LINKTOKEN = LinkTokenInterface(linkTokenAddress); - } - - /** - * @notice Sets the VRF coordinator address. - */ - function setVRFCoordinatorV2Address( - address coordinatorAddress - ) public onlyOwner { - // solhint-disable-next-line gas-custom-errors, reason-string - require(coordinatorAddress != address(0)); - emit VRFCoordinatorV2AddressUpdated(address(COORDINATOR), coordinatorAddress); - COORDINATOR = VRFCoordinatorV2Interface(coordinatorAddress); - } - - /** - * @notice Sets the keeper registry address. - */ - function setKeeperRegistryAddress( - address keeperRegistryAddress - ) public onlyOwner { - // solhint-disable-next-line gas-custom-errors, reason-string - require(keeperRegistryAddress != address(0)); - emit KeeperRegistryAddressUpdated(s_keeperRegistryAddress, keeperRegistryAddress); - s_keeperRegistryAddress = keeperRegistryAddress; - } - - /** - * @notice Sets the minimum wait period (in seconds) for subscription ids between funding. - */ - function setMinWaitPeriodSeconds( - uint256 period - ) public onlyOwner { - emit MinWaitPeriodUpdated(s_minWaitPeriodSeconds, period); - s_minWaitPeriodSeconds = period; - } - - /** - * @notice Gets configuration information for a subscription on the watchlist. - */ - function getSubscriptionInfo( - uint64 subscriptionId - ) external view returns (bool isActive, uint96 minBalanceJuels, uint96 topUpAmountJuels, uint56 lastTopUpTimestamp) { - Target memory target = s_targets[subscriptionId]; - return (target.isActive, target.minBalanceJuels, target.topUpAmountJuels, target.lastTopUpTimestamp); - } - - /** - * @notice Gets the list of subscription ids being watched. - */ - function getWatchList() external view returns (uint64[] memory) { - return s_watchList; - } - - /** - * @notice Pause the contract, which prevents executing performUpkeep. - */ - function pause() external onlyOwner { - _pause(); - } - - /** - * @notice Unpause the contract. - */ - function unpause() external onlyOwner { - _unpause(); - } - - modifier onlyKeeperRegistry() { - if (msg.sender != s_keeperRegistryAddress) { - revert OnlyKeeperRegistry(); - } - _; - } -} diff --git a/contracts/src/v0.8/vrf/VRFV2Wrapper.sol b/contracts/src/v0.8/vrf/VRFV2Wrapper.sol deleted file mode 100644 index 148f605efe..0000000000 --- a/contracts/src/v0.8/vrf/VRFV2Wrapper.sol +++ /dev/null @@ -1,464 +0,0 @@ -// SPDX-License-Identifier: MIT -// solhint-disable-next-line one-contract-per-file -pragma solidity ^0.8.6; - -import {ConfirmedOwner} from "../shared/access/ConfirmedOwner.sol"; - -import {AggregatorV3Interface} from "../shared/interfaces/AggregatorV3Interface.sol"; -import {ITypeAndVersion} from "../shared/interfaces/ITypeAndVersion.sol"; -import {LinkTokenInterface} from "../shared/interfaces/LinkTokenInterface.sol"; - -import {ChainSpecificUtil} from "./ChainSpecificUtil_v0_8_6.sol"; -import {VRFConsumerBaseV2} from "./VRFConsumerBaseV2.sol"; -import {VRFV2WrapperConsumerBase} from "./VRFV2WrapperConsumerBase.sol"; -import {VRFCoordinatorV2Interface} from "./interfaces/VRFCoordinatorV2Interface.sol"; -import {VRFV2WrapperInterface} from "./interfaces/VRFV2WrapperInterface.sol"; - -/** - * @notice A wrapper for VRFCoordinatorV2 that provides an interface better suited to one-off - * @notice requests for randomness. - */ -contract VRFV2Wrapper is ConfirmedOwner, ITypeAndVersion, VRFConsumerBaseV2, VRFV2WrapperInterface { - event WrapperFulfillmentFailed(uint256 indexed requestId, address indexed consumer); - - // solhint-disable-next-line chainlink-solidity/prefix-immutable-variables-with-i - LinkTokenInterface public immutable LINK; - // solhint-disable-next-line chainlink-solidity/prefix-immutable-variables-with-i - AggregatorV3Interface public immutable LINK_ETH_FEED; - // solhint-disable-next-line chainlink-solidity/prefix-immutable-variables-with-i - ExtendedVRFCoordinatorV2Interface public immutable COORDINATOR; - // solhint-disable-next-line chainlink-solidity/prefix-immutable-variables-with-i - uint64 public immutable SUBSCRIPTION_ID; - /// @dev this is the size of a VRF v2 fulfillment's calldata abi-encoded in bytes. - /// @dev proofSize = 13 words = 13 * 256 = 3328 bits - /// @dev commitmentSize = 5 words = 5 * 256 = 1280 bits - /// @dev dataSize = proofSize + commitmentSize = 4608 bits - /// @dev selector = 32 bits - /// @dev total data size = 4608 bits + 32 bits = 4640 bits = 580 bytes - uint32 public s_fulfillmentTxSizeBytes = 580; - - // 5k is plenty for an EXTCODESIZE call (2600) + warm CALL (100) - // and some arithmetic operations. - uint256 private constant GAS_FOR_CALL_EXACT_CHECK = 5000; - - // lastRequestId is the request ID of the most recent VRF V2 request made by this wrapper. This - // should only be relied on within the same transaction the request was made. - uint256 public override lastRequestId; - - // Configuration fetched from VRFCoordinatorV2 - - // s_configured tracks whether this contract has been configured. If not configured, randomness - // requests cannot be made. - bool public s_configured; - - // s_disabled disables the contract when true. When disabled, new VRF requests cannot be made - // but existing ones can still be fulfilled. - bool public s_disabled; - - // s_fallbackWeiPerUnitLink is the backup LINK exchange rate used when the LINK/NATIVE feed is - // stale. - int256 private s_fallbackWeiPerUnitLink; - - // s_stalenessSeconds is the number of seconds before we consider the feed price to be stale and - // fallback to fallbackWeiPerUnitLink. - uint32 private s_stalenessSeconds; - - // s_fulfillmentFlatFeeLinkPPM is the flat fee in millionths of LINK that VRFCoordinatorV2 - // charges. - uint32 private s_fulfillmentFlatFeeLinkPPM; - - // Other configuration - - // s_wrapperGasOverhead reflects the gas overhead of the wrapper's fulfillRandomWords - // function. The cost for this gas is passed to the user. - uint32 private s_wrapperGasOverhead; - - // s_coordinatorGasOverhead reflects the gas overhead of the coordinator's fulfillRandomWords - // function. The cost for this gas is billed to the subscription, and must therefor be included - // in the pricing for wrapped requests. This includes the gas costs of proof verification and - // payment calculation in the coordinator. - uint32 private s_coordinatorGasOverhead; - - // s_wrapperPremiumPercentage is the premium ratio in percentage. For example, a value of 0 - // indicates no premium. A value of 15 indicates a 15 percent premium. - uint8 private s_wrapperPremiumPercentage; - - // s_keyHash is the key hash to use when requesting randomness. Fees are paid based on current gas - // fees, so this should be set to the highest gas lane on the network. - bytes32 internal s_keyHash; - - // s_maxNumWords is the max number of words that can be requested in a single wrapped VRF request. - uint8 internal s_maxNumWords; - - struct Callback { - address callbackAddress; - uint32 callbackGasLimit; - uint256 requestGasPrice; - int256 requestWeiPerUnitLink; - uint256 juelsPaid; - } - - mapping(uint256 => Callback) public /* requestID */ /* callback */ s_callbacks; - - constructor( - address _link, - address _linkEthFeed, - address _coordinator - ) ConfirmedOwner(msg.sender) VRFConsumerBaseV2(_coordinator) { - LINK = LinkTokenInterface(_link); - LINK_ETH_FEED = AggregatorV3Interface(_linkEthFeed); - COORDINATOR = ExtendedVRFCoordinatorV2Interface(_coordinator); - - // Create this wrapper's subscription and add itself as a consumer. - uint64 subId = ExtendedVRFCoordinatorV2Interface(_coordinator).createSubscription(); - SUBSCRIPTION_ID = subId; - ExtendedVRFCoordinatorV2Interface(_coordinator).addConsumer(subId, address(this)); - } - - /** - * @notice setFulfillmentTxSize sets the size of the fulfillment transaction in bytes. - * @param size is the size of the fulfillment transaction in bytes. - */ - function setFulfillmentTxSize( - uint32 size - ) external onlyOwner { - s_fulfillmentTxSizeBytes = size; - } - - /** - * @notice setConfig configures VRFV2Wrapper. - * - * @dev Sets wrapper-specific configuration based on the given parameters, and fetches any needed - * @dev VRFCoordinatorV2 configuration from the coordinator. - * - * @param _wrapperGasOverhead reflects the gas overhead of the wrapper's fulfillRandomWords - * function. - * - * @param _coordinatorGasOverhead reflects the gas overhead of the coordinator's - * fulfillRandomWords function. - * - * @param _wrapperPremiumPercentage is the premium ratio in percentage for wrapper requests. - * - * @param _keyHash to use for requesting randomness. - */ - function setConfig( - uint32 _wrapperGasOverhead, - uint32 _coordinatorGasOverhead, - uint8 _wrapperPremiumPercentage, - bytes32 _keyHash, - uint8 _maxNumWords - ) external onlyOwner { - s_wrapperGasOverhead = _wrapperGasOverhead; - s_coordinatorGasOverhead = _coordinatorGasOverhead; - s_wrapperPremiumPercentage = _wrapperPremiumPercentage; - s_keyHash = _keyHash; - s_maxNumWords = _maxNumWords; - s_configured = true; - - // Get other configuration from coordinator - (,, s_stalenessSeconds,) = COORDINATOR.getConfig(); - s_fallbackWeiPerUnitLink = COORDINATOR.getFallbackWeiPerUnitLink(); - (s_fulfillmentFlatFeeLinkPPM,,,,,,,,) = COORDINATOR.getFeeConfig(); - } - - /** - * @notice getConfig returns the current VRFV2Wrapper configuration. - * - * @return fallbackWeiPerUnitLink is the backup LINK exchange rate used when the LINK/NATIVE feed - * is stale. - * - * @return stalenessSeconds is the number of seconds before we consider the feed price to be stale - * and fallback to fallbackWeiPerUnitLink. - * - * @return fulfillmentFlatFeeLinkPPM is the flat fee in millionths of LINK that VRFCoordinatorV2 - * charges. - * - * @return wrapperGasOverhead reflects the gas overhead of the wrapper's fulfillRandomWords - * function. The cost for this gas is passed to the user. - * - * @return coordinatorGasOverhead reflects the gas overhead of the coordinator's - * fulfillRandomWords function. - * - * @return wrapperPremiumPercentage is the premium ratio in percentage. For example, a value of 0 - * indicates no premium. A value of 15 indicates a 15 percent premium. - * - * @return keyHash is the key hash to use when requesting randomness. Fees are paid based on - * current gas fees, so this should be set to the highest gas lane on the network. - * - * @return maxNumWords is the max number of words that can be requested in a single wrapped VRF - * request. - */ - function getConfig() - external - view - returns ( - int256 fallbackWeiPerUnitLink, - uint32 stalenessSeconds, - uint32 fulfillmentFlatFeeLinkPPM, - uint32 wrapperGasOverhead, - uint32 coordinatorGasOverhead, - uint8 wrapperPremiumPercentage, - bytes32 keyHash, - uint8 maxNumWords - ) - { - return ( - s_fallbackWeiPerUnitLink, - s_stalenessSeconds, - s_fulfillmentFlatFeeLinkPPM, - s_wrapperGasOverhead, - s_coordinatorGasOverhead, - s_wrapperPremiumPercentage, - s_keyHash, - s_maxNumWords - ); - } - - /** - * @notice Calculates the price of a VRF request with the given callbackGasLimit at the current - * @notice block. - * - * @dev This function relies on the transaction gas price which is not automatically set during - * @dev simulation. To estimate the price at a specific gas price, use the estimatePrice function. - * - * @param _callbackGasLimit is the gas limit used to estimate the price. - */ - function calculateRequestPrice( - uint32 _callbackGasLimit - ) external view override onlyConfiguredNotDisabled returns (uint256) { - int256 weiPerUnitLink = _getFeedData(); - return _calculateRequestPrice(_callbackGasLimit, tx.gasprice, weiPerUnitLink); - } - - /** - * @notice Estimates the price of a VRF request with a specific gas limit and gas price. - * - * @dev This is a convenience function that can be called in simulation to better understand - * @dev pricing. - * - * @param _callbackGasLimit is the gas limit used to estimate the price. - * @param _requestGasPriceWei is the gas price in wei used for the estimation. - */ - function estimateRequestPrice( - uint32 _callbackGasLimit, - uint256 _requestGasPriceWei - ) external view override onlyConfiguredNotDisabled returns (uint256) { - int256 weiPerUnitLink = _getFeedData(); - return _calculateRequestPrice(_callbackGasLimit, _requestGasPriceWei, weiPerUnitLink); - } - - function _calculateRequestPrice( - uint256 _gas, - uint256 _requestGasPrice, - int256 _weiPerUnitLink - ) internal view returns (uint256) { - // costWei is the base fee denominated in wei (native) - // costWei takes into account the L1 posting costs of the VRF fulfillment - // transaction, if we are on an L2. - uint256 costWei = - (_requestGasPrice * (_gas + s_wrapperGasOverhead + s_coordinatorGasOverhead) - + ChainSpecificUtil._getL1CalldataGasCost(s_fulfillmentTxSizeBytes)); - // (1e18 juels/link) * ((wei/gas * (gas)) + l1wei) / (wei/link) == 1e18 juels * wei/link / (wei/link) == 1e18 juels - // * wei/link * link/wei == juels - // baseFee is the base fee denominated in juels (link) - uint256 baseFee = (1e18 * costWei) / uint256(_weiPerUnitLink); - // feeWithPremium is the fee after the percentage premium is applied - uint256 feeWithPremium = (baseFee * (s_wrapperPremiumPercentage + 100)) / 100; - // feeWithFlatFee is the fee after the flat fee is applied on top of the premium - uint256 feeWithFlatFee = feeWithPremium + (1e12 * uint256(s_fulfillmentFlatFeeLinkPPM)); - - return feeWithFlatFee; - } - - /** - * @notice onTokenTransfer is called by LinkToken upon payment for a VRF request. - * - * @dev Reverts if payment is too low. - * - * @param _sender is the sender of the payment, and the address that will receive a VRF callback - * upon fulfillment. - * - * @param _amount is the amount of LINK paid in Juels. - * - * @param _data is the abi-encoded VRF request parameters: uint32 callbackGasLimit, - * uint16 requestConfirmations, and uint32 numWords. - */ - function onTokenTransfer( - address _sender, - uint256 _amount, - bytes calldata _data - ) external onlyConfiguredNotDisabled { - // solhint-disable-next-line gas-custom-errors - require(msg.sender == address(LINK), "only callable from LINK"); - - (uint32 callbackGasLimit, uint16 requestConfirmations, uint32 numWords) = - abi.decode(_data, (uint32, uint16, uint32)); - uint32 eip150Overhead = _getEIP150Overhead(callbackGasLimit); - int256 weiPerUnitLink = _getFeedData(); - uint256 price = _calculateRequestPrice(callbackGasLimit, tx.gasprice, weiPerUnitLink); - // solhint-disable-next-line gas-custom-errors - require(_amount >= price, "fee too low"); - // solhint-disable-next-line gas-custom-errors - require(numWords <= s_maxNumWords, "numWords too high"); - - uint256 requestId = COORDINATOR.requestRandomWords( - s_keyHash, - SUBSCRIPTION_ID, - requestConfirmations, - callbackGasLimit + eip150Overhead + s_wrapperGasOverhead, - numWords - ); - s_callbacks[requestId] = Callback({ - callbackAddress: _sender, - callbackGasLimit: callbackGasLimit, - requestGasPrice: tx.gasprice, - requestWeiPerUnitLink: weiPerUnitLink, - juelsPaid: _amount - }); - lastRequestId = requestId; - } - - /** - * @notice withdraw is used by the VRFV2Wrapper's owner to withdraw LINK revenue. - * - * @param _recipient is the address that should receive the LINK funds. - * - * @param _amount is the amount of LINK in Juels that should be withdrawn. - */ - function withdraw( - address _recipient, - uint256 _amount - ) external onlyOwner { - LINK.transfer(_recipient, _amount); - } - - /** - * @notice enable this contract so that new requests can be accepted. - */ - function enable() external onlyOwner { - s_disabled = false; - } - - /** - * @notice disable this contract so that new requests will be rejected. When disabled, new requests - * @notice will revert but existing requests can still be fulfilled. - */ - function disable() external onlyOwner { - s_disabled = true; - } - - // solhint-disable-next-line chainlink-solidity/prefix-internal-functions-with-underscore - function fulfillRandomWords( - uint256 _requestId, - uint256[] memory _randomWords - ) internal override { - Callback memory callback = s_callbacks[_requestId]; - delete s_callbacks[_requestId]; - // solhint-disable-next-line gas-custom-errors - require(callback.callbackAddress != address(0), "request not found"); // This should never happen - - VRFV2WrapperConsumerBase c; - bytes memory resp = abi.encodeWithSelector(c.rawFulfillRandomWords.selector, _requestId, _randomWords); - - bool success = _callWithExactGas(callback.callbackGasLimit, callback.callbackAddress, resp); - if (!success) { - emit WrapperFulfillmentFailed(_requestId, callback.callbackAddress); - } - } - - function _getFeedData() private view returns (int256) { - bool staleFallback = s_stalenessSeconds > 0; - uint256 timestamp; - int256 weiPerUnitLink; - (, weiPerUnitLink,, timestamp,) = LINK_ETH_FEED.latestRoundData(); - // solhint-disable-next-line not-rely-on-time - if (staleFallback && s_stalenessSeconds < block.timestamp - timestamp) { - weiPerUnitLink = s_fallbackWeiPerUnitLink; - } - // solhint-disable-next-line gas-custom-errors - require(weiPerUnitLink >= 0, "Invalid LINK wei price"); - return weiPerUnitLink; - } - - /** - * @dev Calculates extra amount of gas required for running an assembly call() post-EIP150. - */ - function _getEIP150Overhead( - uint32 gas - ) private pure returns (uint32) { - return gas / 63 + 1; - } - - /** - * @dev calls target address with exactly gasAmount gas and data as calldata - * or reverts if at least gasAmount gas is not available. - */ - function _callWithExactGas( - uint256 gasAmount, - address target, - bytes memory data - ) private returns (bool success) { - assembly { - let g := gas() - // Compute g -= GAS_FOR_CALL_EXACT_CHECK and check for underflow - // The gas actually passed to the callee is min(gasAmount, 63//64*gas available). - // We want to ensure that we revert if gasAmount > 63//64*gas available - // as we do not want to provide them with less, however that check itself costs - // gas. GAS_FOR_CALL_EXACT_CHECK ensures we have at least enough gas to be able - // to revert if gasAmount > 63//64*gas available. - if lt(g, GAS_FOR_CALL_EXACT_CHECK) { revert(0, 0) } - g := sub(g, GAS_FOR_CALL_EXACT_CHECK) - // if g - g//64 <= gasAmount, revert - // (we subtract g//64 because of EIP-150) - if iszero(gt(sub(g, div(g, 64)), gasAmount)) { revert(0, 0) } - // solidity calls check that a contract actually exists at the destination, so we do the same - if iszero(extcodesize(target)) { revert(0, 0) } - // call and return whether we succeeded. ignore return data - // call(gas,addr,value,argsOffset,argsLength,retOffset,retLength) - success := call(gasAmount, target, 0, add(data, 0x20), mload(data), 0, 0) - } - return success; - } - - function typeAndVersion() external pure virtual override returns (string memory) { - return "VRFV2Wrapper 1.0.0"; - } - - modifier onlyConfiguredNotDisabled() { - // solhint-disable-next-line gas-custom-errors - require(s_configured, "wrapper is not configured"); - // solhint-disable-next-line gas-custom-errors - require(!s_disabled, "wrapper is disabled"); - _; - } -} - - // solhint-disable-next-line interface-starts-with-i - interface ExtendedVRFCoordinatorV2Interface is VRFCoordinatorV2Interface { - function getConfig() - external - view - returns ( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation - ); - - function getFallbackWeiPerUnitLink() external view returns (int256); - - function getFeeConfig() - external - view - returns ( - uint32 fulfillmentFlatFeeLinkPPMTier1, - uint32 fulfillmentFlatFeeLinkPPMTier2, - uint32 fulfillmentFlatFeeLinkPPMTier3, - uint32 fulfillmentFlatFeeLinkPPMTier4, - uint32 fulfillmentFlatFeeLinkPPMTier5, - uint24 reqsForTier2, - uint24 reqsForTier3, - uint24 reqsForTier4, - uint24 reqsForTier5 - ); - } diff --git a/contracts/src/v0.8/vrf/VRFV2WrapperConsumerBase.sol b/contracts/src/v0.8/vrf/VRFV2WrapperConsumerBase.sol deleted file mode 100644 index 8e9f30e7f7..0000000000 --- a/contracts/src/v0.8/vrf/VRFV2WrapperConsumerBase.sol +++ /dev/null @@ -1,96 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {LinkTokenInterface} from "../shared/interfaces/LinkTokenInterface.sol"; -import {VRFV2WrapperInterface} from "./interfaces/VRFV2WrapperInterface.sol"; - -/** - * - * @notice Interface for contracts using VRF randomness through the VRF V2 wrapper - * ******************************************************************************** - * @dev PURPOSE - * - * @dev Create VRF V2 requests without the need for subscription management. Rather than creating - * @dev and funding a VRF V2 subscription, a user can use this wrapper to create one off requests, - * @dev paying up front rather than at fulfillment. - * - * @dev Since the price is determined using the gas price of the request transaction rather than - * @dev the fulfillment transaction, the wrapper charges an additional premium on callback gas - * @dev usage, in addition to some extra overhead costs associated with the VRFV2Wrapper contract. - * ***************************************************************************** - * @dev USAGE - * - * @dev Calling contracts must inherit from VRFV2WrapperConsumerBase. The consumer must be funded - * @dev with enough LINK to make the request, otherwise requests will revert. To request randomness, - * @dev call the 'requestRandomness' function with the desired VRF parameters. This function handles - * @dev paying for the request based on the current pricing. - * - * @dev Consumers must implement the fullfillRandomWords function, which will be called during - * @dev fulfillment with the randomness result. - */ -abstract contract VRFV2WrapperConsumerBase { - // solhint-disable-next-line chainlink-solidity/prefix-immutable-variables-with-i - LinkTokenInterface internal immutable LINK; - // solhint-disable-next-line chainlink-solidity/prefix-immutable-variables-with-i - VRFV2WrapperInterface internal immutable VRF_V2_WRAPPER; - - /** - * @param _link is the address of LinkToken - * @param _vrfV2Wrapper is the address of the VRFV2Wrapper contract - */ - constructor( - address _link, - address _vrfV2Wrapper - ) { - LINK = LinkTokenInterface(_link); - VRF_V2_WRAPPER = VRFV2WrapperInterface(_vrfV2Wrapper); - } - - /** - * @dev Requests randomness from the VRF V2 wrapper. - * - * @param _callbackGasLimit is the gas limit that should be used when calling the consumer's - * fulfillRandomWords function. - * @param _requestConfirmations is the number of confirmations to wait before fulfilling the - * request. A higher number of confirmations increases security by reducing the likelihood - * that a chain re-org changes a published randomness outcome. - * @param _numWords is the number of random words to request. - * - * @return requestId is the VRF V2 request ID of the newly created randomness request. - */ - // solhint-disable-next-line chainlink-solidity/prefix-internal-functions-with-underscore - function requestRandomness( - uint32 _callbackGasLimit, - uint16 _requestConfirmations, - uint32 _numWords - ) internal returns (uint256 requestId) { - LINK.transferAndCall( - address(VRF_V2_WRAPPER), - VRF_V2_WRAPPER.calculateRequestPrice(_callbackGasLimit), - abi.encode(_callbackGasLimit, _requestConfirmations, _numWords) - ); - return VRF_V2_WRAPPER.lastRequestId(); - } - - /** - * @notice fulfillRandomWords handles the VRF V2 wrapper response. The consuming contract must - * @notice implement it. - * - * @param _requestId is the VRF V2 request ID. - * @param _randomWords is the randomness result. - */ - // solhint-disable-next-line chainlink-solidity/prefix-internal-functions-with-underscore - function fulfillRandomWords( - uint256 _requestId, - uint256[] memory _randomWords - ) internal virtual; - - function rawFulfillRandomWords( - uint256 _requestId, - uint256[] memory _randomWords - ) external { - // solhint-disable-next-line gas-custom-errors - require(msg.sender == address(VRF_V2_WRAPPER), "only VRF V2 wrapper can fulfill"); - fulfillRandomWords(_requestId, _randomWords); - } -} diff --git a/contracts/src/v0.8/vrf/interfaces/IAuthorizedReceiver.sol b/contracts/src/v0.8/vrf/interfaces/IAuthorizedReceiver.sol deleted file mode 100644 index 1a050c54b4..0000000000 --- a/contracts/src/v0.8/vrf/interfaces/IAuthorizedReceiver.sol +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -interface IAuthorizedReceiver { - function isAuthorizedSender( - address sender - ) external view returns (bool); - - function getAuthorizedSenders() external returns (address[] memory); - - function setAuthorizedSenders( - address[] calldata senders - ) external; -} diff --git a/contracts/src/v0.8/vrf/interfaces/VRFCoordinatorV2Interface.sol b/contracts/src/v0.8/vrf/interfaces/VRFCoordinatorV2Interface.sol deleted file mode 100644 index 166481e16a..0000000000 --- a/contracts/src/v0.8/vrf/interfaces/VRFCoordinatorV2Interface.sol +++ /dev/null @@ -1,129 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -// solhint-disable-next-line interface-starts-with-i -interface VRFCoordinatorV2Interface { - /** - * @notice Get configuration relevant for making requests - * @return minimumRequestConfirmations global min for request confirmations - * @return maxGasLimit global max for request gas limit - * @return s_provingKeyHashes list of registered key hashes - */ - function getRequestConfig() external view returns (uint16, uint32, bytes32[] memory); - - /** - * @notice Request a set of random words. - * @param 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. - * @param subId - The ID of the VRF subscription. Must be funded - * with the minimum subscription balance required for the selected keyHash. - * @param minimumRequestConfirmations - 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]. - * @param 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] - * @param 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. - * @return requestId - A unique identifier of the request. Can be used to match - * a request to a response in fulfillRandomWords. - */ - function requestRandomWords( - bytes32 keyHash, - uint64 subId, - uint16 minimumRequestConfirmations, - uint32 callbackGasLimit, - uint32 numWords - ) external returns (uint256 requestId); - - /** - * @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, use transferAndCall. For example - * @dev LINKTOKEN.transferAndCall( - * @dev address(COORDINATOR), - * @dev amount, - * @dev abi.encode(subId)); - */ - function createSubscription() external returns (uint64 subId); - - /** - * @notice Get a VRF subscription. - * @param subId - ID of the subscription - * @return balance - LINK balance of the subscription in juels. - * @return reqCount - number of requests for this subscription, determines fee tier. - * @return owner - owner of the subscription. - * @return consumers - list of consumer address which are able to use this subscription. - */ - function getSubscription( - uint64 subId - ) external view returns (uint96 balance, uint64 reqCount, address owner, address[] memory consumers); - - /** - * @notice Request subscription owner transfer. - * @param subId - ID of the subscription - * @param newOwner - proposed new owner of the subscription - */ - function requestSubscriptionOwnerTransfer( - uint64 subId, - address newOwner - ) external; - - /** - * @notice Request 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( - uint64 subId - ) external; - - /** - * @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( - uint64 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( - uint64 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( - uint64 subId, - address to - ) external; - - /* - * @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( - uint64 subId - ) external view returns (bool); -} diff --git a/contracts/src/v0.8/vrf/interfaces/VRFV2WrapperInterface.sol b/contracts/src/v0.8/vrf/interfaces/VRFV2WrapperInterface.sol deleted file mode 100644 index 9b670b8bc3..0000000000 --- a/contracts/src/v0.8/vrf/interfaces/VRFV2WrapperInterface.sol +++ /dev/null @@ -1,38 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -// solhint-disable-next-line interface-starts-with-i -interface VRFV2WrapperInterface { - /** - * @return the request ID of the most recent VRF V2 request made by this wrapper. This should only - * be relied option within the same transaction that the request was made. - */ - function lastRequestId() external view returns (uint256); - - /** - * @notice Calculates the price of a VRF request with the given callbackGasLimit at the current - * @notice block. - * - * @dev This function relies on the transaction gas price which is not automatically set during - * @dev simulation. To estimate the price at a specific gas price, use the estimatePrice function. - * - * @param _callbackGasLimit is the gas limit used to estimate the price. - */ - function calculateRequestPrice( - uint32 _callbackGasLimit - ) external view returns (uint256); - - /** - * @notice Estimates the price of a VRF request with a specific gas limit and gas price. - * - * @dev This is a convenience function that can be called in simulation to better understand - * @dev pricing. - * - * @param _callbackGasLimit is the gas limit used to estimate the price. - * @param _requestGasPriceWei is the gas price in wei used for the estimation. - */ - function estimateRequestPrice( - uint32 _callbackGasLimit, - uint256 _requestGasPriceWei - ) external view returns (uint256); -} diff --git a/contracts/src/v0.8/vrf/mocks/VRFCoordinatorV2Mock.sol b/contracts/src/v0.8/vrf/mocks/VRFCoordinatorV2Mock.sol deleted file mode 100644 index 19f85690c6..0000000000 --- a/contracts/src/v0.8/vrf/mocks/VRFCoordinatorV2Mock.sol +++ /dev/null @@ -1,355 +0,0 @@ -// SPDX-License-Identifier: MIT -// A mock for testing code that relies on VRFCoordinatorV2. -pragma solidity ^0.8.4; - -import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol"; -import {VRFConsumerBaseV2} from "../VRFConsumerBaseV2.sol"; -import {VRFCoordinatorV2Interface} from "../interfaces/VRFCoordinatorV2Interface.sol"; - -// solhint-disable chainlink-solidity/prefix-immutable-variables-with-i -// solhint-disable gas-custom-errors -// solhint-disable avoid-low-level-calls - -contract VRFCoordinatorV2Mock is VRFCoordinatorV2Interface, ConfirmedOwner { - uint96 public immutable BASE_FEE; - uint96 public immutable GAS_PRICE_LINK; - uint16 public immutable MAX_CONSUMERS = 100; - - error InvalidSubscription(); - error InsufficientBalance(); - error MustBeSubOwner(address owner); - error TooManyConsumers(); - error InvalidConsumer(); - error InvalidRandomWords(); - error Reentrant(); - - event RandomWordsRequested( - bytes32 indexed keyHash, - uint256 requestId, - uint256 preSeed, - uint64 indexed subId, - uint16 minimumRequestConfirmations, - uint32 callbackGasLimit, - uint32 numWords, - address indexed sender - ); - event RandomWordsFulfilled(uint256 indexed requestId, uint256 outputSeed, uint96 payment, bool success); - event SubscriptionCreated(uint64 indexed subId, address owner); - event SubscriptionFunded(uint64 indexed subId, uint256 oldBalance, uint256 newBalance); - event SubscriptionCanceled(uint64 indexed subId, address to, uint256 amount); - event ConsumerAdded(uint64 indexed subId, address consumer); - event ConsumerRemoved(uint64 indexed subId, address consumer); - event ConfigSet(); - - struct Config { - // Reentrancy protection. - bool reentrancyLock; - } - - Config private s_config; - uint64 internal s_currentSubId; - uint256 internal s_nextRequestId = 1; - uint256 internal s_nextPreSeed = 100; - - struct Subscription { - address owner; - uint96 balance; - } - - mapping(uint64 => Subscription) internal s_subscriptions; /* subId */ /* subscription */ - mapping(uint64 => address[]) internal s_consumers; /* subId */ /* consumers */ - - struct Request { - uint64 subId; - uint32 callbackGasLimit; - uint32 numWords; - } - - mapping(uint256 => Request) internal s_requests; /* requestId */ /* request */ - - constructor( - uint96 _baseFee, - uint96 _gasPriceLink - ) ConfirmedOwner(msg.sender) { - BASE_FEE = _baseFee; - GAS_PRICE_LINK = _gasPriceLink; - setConfig(); - } - - /** - * @notice Sets the configuration of the vrfv2 mock coordinator - */ - function setConfig() public onlyOwner { - s_config = Config({reentrancyLock: false}); - emit ConfigSet(); - } - - function consumerIsAdded( - uint64 _subId, - address _consumer - ) public view returns (bool) { - address[] memory consumers = s_consumers[_subId]; - for (uint256 i = 0; i < consumers.length; i++) { - if (consumers[i] == _consumer) { - return true; - } - } - return false; - } - - modifier onlyValidConsumer( - uint64 _subId, - address _consumer - ) { - if (!consumerIsAdded(_subId, _consumer)) { - revert InvalidConsumer(); - } - _; - } - - /** - * @notice fulfillRandomWords fulfills the given request, sending the random words to the supplied - * @notice consumer. - * - * @dev This mock uses a simplified formula for calculating payment amount and gas usage, and does - * @dev not account for all edge cases handled in the real VRF coordinator. When making requests - * @dev against the real coordinator a small amount of additional LINK is required. - * - * @param _requestId the request to fulfill - * @param _consumer the VRF randomness consumer to send the result to - */ - function fulfillRandomWords( - uint256 _requestId, - address _consumer - ) external nonReentrant { - fulfillRandomWordsWithOverride(_requestId, _consumer, new uint256[](0)); - } - - /** - * @notice fulfillRandomWordsWithOverride allows the user to pass in their own random words. - * - * @param _requestId the request to fulfill - * @param _consumer the VRF randomness consumer to send the result to - * @param _words user-provided random words - */ - function fulfillRandomWordsWithOverride( - uint256 _requestId, - address _consumer, - uint256[] memory _words - ) public { - uint256 startGas = gasleft(); - if (s_requests[_requestId].subId == 0) { - revert("nonexistent request"); - } - Request memory req = s_requests[_requestId]; - - if (_words.length == 0) { - _words = new uint256[](req.numWords); - for (uint256 i = 0; i < req.numWords; i++) { - _words[i] = uint256(keccak256(abi.encode(_requestId, i))); - } - } else if (_words.length != req.numWords) { - revert InvalidRandomWords(); - } - - VRFConsumerBaseV2 v; - bytes memory callReq = abi.encodeWithSelector(v.rawFulfillRandomWords.selector, _requestId, _words); - s_config.reentrancyLock = true; - (bool success,) = _consumer.call{gas: req.callbackGasLimit}(callReq); - s_config.reentrancyLock = false; - - uint96 payment = uint96(BASE_FEE + ((startGas - gasleft()) * GAS_PRICE_LINK)); - if (s_subscriptions[req.subId].balance < payment) { - revert InsufficientBalance(); - } - s_subscriptions[req.subId].balance -= payment; - delete (s_requests[_requestId]); - emit RandomWordsFulfilled(_requestId, _requestId, payment, success); - } - - /** - * @notice fundSubscription allows funding a subscription with an arbitrary amount for testing. - * - * @param _subId the subscription to fund - * @param _amount the amount to fund - */ - function fundSubscription( - uint64 _subId, - uint96 _amount - ) public { - if (s_subscriptions[_subId].owner == address(0)) { - revert InvalidSubscription(); - } - uint96 oldBalance = s_subscriptions[_subId].balance; - s_subscriptions[_subId].balance += _amount; - emit SubscriptionFunded(_subId, oldBalance, oldBalance + _amount); - } - - function requestRandomWords( - bytes32 _keyHash, - uint64 _subId, - uint16 _minimumRequestConfirmations, - uint32 _callbackGasLimit, - uint32 _numWords - ) external override nonReentrant onlyValidConsumer(_subId, msg.sender) returns (uint256) { - if (s_subscriptions[_subId].owner == address(0)) { - revert InvalidSubscription(); - } - - uint256 requestId = s_nextRequestId++; - uint256 preSeed = s_nextPreSeed++; - - s_requests[requestId] = Request({subId: _subId, callbackGasLimit: _callbackGasLimit, numWords: _numWords}); - - emit RandomWordsRequested( - _keyHash, requestId, preSeed, _subId, _minimumRequestConfirmations, _callbackGasLimit, _numWords, msg.sender - ); - return requestId; - } - - function createSubscription() external override returns (uint64 _subId) { - s_currentSubId++; - s_subscriptions[s_currentSubId] = Subscription({owner: msg.sender, balance: 0}); - emit SubscriptionCreated(s_currentSubId, msg.sender); - return s_currentSubId; - } - - function getSubscription( - uint64 _subId - ) external view override returns (uint96 balance, uint64 reqCount, address owner, address[] memory consumers) { - if (s_subscriptions[_subId].owner == address(0)) { - revert InvalidSubscription(); - } - return (s_subscriptions[_subId].balance, 0, s_subscriptions[_subId].owner, s_consumers[_subId]); - } - - function cancelSubscription( - uint64 _subId, - address _to - ) external override onlySubOwner(_subId) nonReentrant { - emit SubscriptionCanceled(_subId, _to, s_subscriptions[_subId].balance); - delete (s_subscriptions[_subId]); - } - - modifier onlySubOwner( - uint64 _subId - ) { - address owner = s_subscriptions[_subId].owner; - if (owner == address(0)) { - revert InvalidSubscription(); - } - if (msg.sender != owner) { - revert MustBeSubOwner(owner); - } - _; - } - - function getRequestConfig() external pure override returns (uint16, uint32, bytes32[] memory) { - return (3, 2_000_000, new bytes32[](0)); - } - - function addConsumer( - uint64 _subId, - address _consumer - ) external override onlySubOwner(_subId) { - if (s_consumers[_subId].length == MAX_CONSUMERS) { - revert TooManyConsumers(); - } - - if (consumerIsAdded(_subId, _consumer)) { - return; - } - - s_consumers[_subId].push(_consumer); - emit ConsumerAdded(_subId, _consumer); - } - - function removeConsumer( - uint64 _subId, - address _consumer - ) external override onlySubOwner(_subId) onlyValidConsumer(_subId, _consumer) nonReentrant { - address[] storage consumers = s_consumers[_subId]; - for (uint256 i = 0; i < consumers.length; i++) { - if (consumers[i] == _consumer) { - address last = consumers[consumers.length - 1]; - consumers[i] = last; - consumers.pop(); - break; - } - } - - emit ConsumerRemoved(_subId, _consumer); - } - - function getConfig() - external - pure - returns ( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation - ) - { - return (4, 2_500_000, 2700, 33_285); - } - - function getFeeConfig() - external - pure - returns ( - uint32 fulfillmentFlatFeeLinkPPMTier1, - uint32 fulfillmentFlatFeeLinkPPMTier2, - uint32 fulfillmentFlatFeeLinkPPMTier3, - uint32 fulfillmentFlatFeeLinkPPMTier4, - uint32 fulfillmentFlatFeeLinkPPMTier5, - uint24 reqsForTier2, - uint24 reqsForTier3, - uint24 reqsForTier4, - uint24 reqsForTier5 - ) - { - return ( - 100_000, // 0.1 LINK - 100_000, // 0.1 LINK - 100_000, // 0.1 LINK - 100_000, // 0.1 LINK - 100_000, // 0.1 LINK - 0, - 0, - 0, - 0 - ); - } - - modifier nonReentrant() { - if (s_config.reentrancyLock) { - revert Reentrant(); - } - _; - } - - function getFallbackWeiPerUnitLink() external pure returns (int256) { - return 4_000_000_000_000_000; // 0.004 Ether - } - - function requestSubscriptionOwnerTransfer( - uint64, - /*_subId*/ - address /*_newOwner*/ - ) external pure override { - revert("not implemented"); - } - - function acceptSubscriptionOwnerTransfer( - uint64 /*_subId*/ - ) external pure override { - revert("not implemented"); - } - - function pendingRequestExists( - uint64 /*subId*/ - ) public pure override returns (bool) { - revert("not implemented"); - } -} diff --git a/contracts/src/v0.8/vrf/test/VRFCoordinatorV2Mock.t.sol b/contracts/src/v0.8/vrf/test/VRFCoordinatorV2Mock.t.sol deleted file mode 100644 index 2e08b3471c..0000000000 --- a/contracts/src/v0.8/vrf/test/VRFCoordinatorV2Mock.t.sol +++ /dev/null @@ -1,359 +0,0 @@ -pragma solidity ^0.8.6; - -import {MockV3Aggregator} from "../../shared/mocks/MockV3Aggregator.sol"; -import {VRF} from "../VRF.sol"; -import {VRFCoordinatorV2Mock} from "../mocks/VRFCoordinatorV2Mock.sol"; -import {MockLinkToken} from "../testhelpers/MockLinkToken.sol"; -import {VRFConsumerV2} from "../testhelpers/VRFConsumerV2.sol"; -import "./BaseTest.t.sol"; - -contract VRFCoordinatorV2MockTest is BaseTest { - MockLinkToken internal s_linkToken; - MockV3Aggregator internal s_linkEthFeed; - VRFCoordinatorV2Mock internal s_vrfCoordinatorV2Mock; - VRFConsumerV2 internal s_vrfConsumerV2; - address internal s_subOwner = address(1234); - address internal s_randomOwner = address(4567); - - // VRF KeyV2 generated from a node; not sensitive information. - // The secret key used to generate this key is: 10. - bytes internal constant UNCOMPRESSED_PUBLIC_KEY = - hex"a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7"; - bytes internal constant COMPRESSED_PUBLIC_KEY = - hex"a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c701"; - bytes32 internal constant KEY_HASH = hex"9f2353bde94264dbc3d554a94cceba2d7d2b4fdce4304d3e09a1fea9fbeb1528"; - - uint32 internal constant DEFAULT_CALLBACK_GAS_LIMIT = 500_000; - uint16 internal constant DEFAULT_REQUEST_CONFIRMATIONS = 3; - uint32 internal constant DEFAULT_NUM_WORDS = 1; - - uint96 pointOneLink = 0.1 ether; - uint96 oneLink = 1 ether; - - event SubscriptionCreated(uint64 indexed subId, address owner); - event SubscriptionFunded(uint64 indexed subId, uint256 oldBalance, uint256 newBalance); - event SubscriptionCanceled(uint64 indexed subId, address to, uint256 amount); - event ConsumerAdded(uint64 indexed subId, address consumer); - event ConsumerRemoved(uint64 indexed subId, address consumer); - event RandomWordsRequested( - bytes32 indexed keyHash, - uint256 requestId, - uint256 preSeed, - uint64 indexed subId, - uint16 minimumRequestConfirmations, - uint32 callbackGasLimit, - uint32 numWords, - address indexed sender - ); - event RandomWordsFulfilled(uint256 indexed requestId, uint256 outputSeed, uint96 payment, bool success); - - function setUp() public override { - BaseTest.setUp(); - - // Fund our users. - vm.roll(1); - vm.deal(OWNER, 10_000 ether); - vm.deal(s_subOwner, 20 ether); - - // Deploy link token and link/eth feed. - s_linkToken = new MockLinkToken(); - s_linkEthFeed = new MockV3Aggregator(18, 500_000_000_000_000_000); // .5 ETH (good for testing) - - // Deploy coordinator and consumer. - s_vrfCoordinatorV2Mock = new VRFCoordinatorV2Mock( - pointOneLink, - 1_000_000_000 // 0.000000001 LINK per gas - ); - address coordinatorAddr = address(s_vrfCoordinatorV2Mock); - s_vrfConsumerV2 = new VRFConsumerV2(coordinatorAddr, address(s_linkToken)); - - s_vrfCoordinatorV2Mock.setConfig(); - } - - function testCreateSubscription() public { - vm.startPrank(s_subOwner); - vm.expectEmit( - true, // no first indexed topic - false, // no second indexed topic - false, // no third indexed topic - true // check data (target coordinator address) - ); - emit SubscriptionCreated(1, s_subOwner); - uint64 subId = s_vrfCoordinatorV2Mock.createSubscription(); - assertEq(subId, 1); - - (uint96 balance, uint64 reqCount, address owner, address[] memory consumers) = - s_vrfCoordinatorV2Mock.getSubscription(subId); - assertEq(balance, 0); - assertEq(reqCount, 0); - assertEq(owner, s_subOwner); - assertEq(consumers.length, 0); - // s_testCoordinator.fundSubscriptionWithEth{value: 10 ether}(subId); - - // Test if subId increments - vm.expectEmit(true, false, false, true); - emit SubscriptionCreated(2, s_subOwner); - subId = s_vrfCoordinatorV2Mock.createSubscription(); - assertEq(subId, 2); - vm.stopPrank(); - } - - function testAddConsumer() public { - vm.startPrank(s_subOwner); - uint64 subId = s_vrfCoordinatorV2Mock.createSubscription(); - vm.expectEmit(true, false, false, true); - emit ConsumerAdded(subId, address(s_vrfConsumerV2)); - s_vrfCoordinatorV2Mock.addConsumer(subId, address(s_vrfConsumerV2)); - - (uint96 balance, uint64 reqCount, address owner, address[] memory consumers) = - s_vrfCoordinatorV2Mock.getSubscription(subId); - assertEq(balance, 0); - assertEq(reqCount, 0); - assertEq(owner, s_subOwner); - assertEq(consumers.length, 1); - assertEq(consumers[0], address(s_vrfConsumerV2)); - vm.stopPrank(); - } - - // cannot add a consumer to a nonexistent subscription - function testAddConsumerToInvalidSub() public { - vm.startPrank(s_subOwner); - bytes4 reason = bytes4(keccak256("InvalidSubscription()")); - vm.expectRevert(toBytes(reason)); - s_vrfCoordinatorV2Mock.addConsumer(1, address(s_vrfConsumerV2)); - vm.stopPrank(); - } - - // cannot add more than the consumer maximum - function testAddMaxConsumers() public { - vm.startPrank(s_subOwner); - uint64 subId = s_vrfCoordinatorV2Mock.createSubscription(); - // Add 100 consumers - for (uint64 i = 101; i <= 200; ++i) { - s_vrfCoordinatorV2Mock.addConsumer(subId, address(bytes20(keccak256(abi.encodePacked(i))))); - } - // Adding 101th consumer should revert - bytes4 reason = bytes4(keccak256("TooManyConsumers()")); - vm.expectRevert(toBytes(reason)); - s_vrfCoordinatorV2Mock.addConsumer(subId, address(s_vrfConsumerV2)); - vm.stopPrank(); - } - - // can remove a consumer from a subscription - function testRemoveConsumerFromSub() public { - vm.startPrank(s_subOwner); - uint64 subId = s_vrfCoordinatorV2Mock.createSubscription(); - - s_vrfCoordinatorV2Mock.addConsumer(subId, address(s_vrfConsumerV2)); - - (,,, address[] memory consumers) = s_vrfCoordinatorV2Mock.getSubscription(subId); - assertEq(consumers.length, 1); - assertEq(consumers[0], address(s_vrfConsumerV2)); - - vm.expectEmit(true, false, false, true); - emit ConsumerRemoved(subId, address(s_vrfConsumerV2)); - s_vrfCoordinatorV2Mock.removeConsumer(subId, address(s_vrfConsumerV2)); - - vm.stopPrank(); - } - - // cannot remove a consumer from a nonexistent subscription - function testRemoveConsumerFromInvalidSub() public { - vm.startPrank(s_subOwner); - bytes4 reason = bytes4(keccak256("InvalidSubscription()")); - vm.expectRevert(toBytes(reason)); - s_vrfCoordinatorV2Mock.removeConsumer(1, address(s_vrfConsumerV2)); - vm.stopPrank(); - } - - // cannot remove a consumer after it is already removed - function testRemoveConsumerAgain() public { - vm.startPrank(s_subOwner); - uint64 subId = s_vrfCoordinatorV2Mock.createSubscription(); - - s_vrfCoordinatorV2Mock.addConsumer(subId, address(s_vrfConsumerV2)); - - (,,, address[] memory consumers) = s_vrfCoordinatorV2Mock.getSubscription(subId); - assertEq(consumers.length, 1); - assertEq(consumers[0], address(s_vrfConsumerV2)); - - vm.expectEmit(true, false, false, true); - emit ConsumerRemoved(subId, address(s_vrfConsumerV2)); - s_vrfCoordinatorV2Mock.removeConsumer(subId, address(s_vrfConsumerV2)); - - // Removing consumer again should revert with InvalidConsumer - bytes4 reason = bytes4(keccak256("InvalidConsumer()")); - vm.expectRevert(toBytes(reason)); - s_vrfCoordinatorV2Mock.removeConsumer(subId, address(s_vrfConsumerV2)); - vm.stopPrank(); - } - - // can fund a subscription - function testFundSubscription() public { - vm.startPrank(s_subOwner); - uint64 subId = s_vrfCoordinatorV2Mock.createSubscription(); - - vm.expectEmit(true, false, false, true); - emit SubscriptionFunded(subId, 0, oneLink); - s_vrfCoordinatorV2Mock.fundSubscription(subId, oneLink); - - (uint96 balance,,, address[] memory consumers) = s_vrfCoordinatorV2Mock.getSubscription(subId); - assertEq(balance, oneLink); - assertEq(consumers.length, 0); - vm.stopPrank(); - } - - // cannot fund a nonexistent subscription - function testFundInvalidSubscription() public { - vm.startPrank(s_subOwner); - - // Removing consumer again should revert with InvalidConsumer - bytes4 reason = bytes4(keccak256("InvalidSubscription()")); - vm.expectRevert(toBytes(reason)); - s_vrfCoordinatorV2Mock.removeConsumer(1, address(s_vrfConsumerV2)); - - vm.stopPrank(); - } - - // can cancel a subscription - function testCancelSubscription() public { - vm.startPrank(s_subOwner); - uint64 subId = s_vrfCoordinatorV2Mock.createSubscription(); - - s_vrfCoordinatorV2Mock.fundSubscription(subId, oneLink); - - vm.expectEmit(true, false, false, true); - emit SubscriptionCanceled(subId, s_subOwner, oneLink); - s_vrfCoordinatorV2Mock.cancelSubscription(subId, s_subOwner); - - bytes4 reason = bytes4(keccak256("InvalidSubscription()")); - vm.expectRevert(toBytes(reason)); - s_vrfCoordinatorV2Mock.getSubscription(subId); - - vm.stopPrank(); - } - - // fails to fulfill without being a valid consumer - function testRequestRandomWordsInvalidConsumer() public { - vm.startPrank(s_subOwner); - uint64 subId = s_vrfCoordinatorV2Mock.createSubscription(); - - s_vrfCoordinatorV2Mock.fundSubscription(subId, oneLink); - - bytes4 reason = bytes4(keccak256("InvalidConsumer()")); - vm.expectRevert(toBytes(reason)); - s_vrfCoordinatorV2Mock.requestRandomWords( - KEY_HASH, subId, DEFAULT_REQUEST_CONFIRMATIONS, DEFAULT_CALLBACK_GAS_LIMIT, DEFAULT_NUM_WORDS - ); - vm.stopPrank(); - } - - // fails to fulfill with insufficient funds - function testRequestRandomWordsInsufficientFunds() public { - vm.startPrank(s_subOwner); - uint64 subId = s_vrfCoordinatorV2Mock.createSubscription(); - - address consumerAddr = address(s_vrfConsumerV2); - s_vrfCoordinatorV2Mock.addConsumer(subId, address(s_vrfConsumerV2)); - - vm.stopPrank(); - - vm.startPrank(consumerAddr); - - vm.expectEmit(true, false, false, true); - emit RandomWordsRequested( - KEY_HASH, - 1, - 100, - subId, - DEFAULT_REQUEST_CONFIRMATIONS, - DEFAULT_CALLBACK_GAS_LIMIT, - DEFAULT_NUM_WORDS, - address(s_subOwner) - ); - uint256 reqId = s_vrfCoordinatorV2Mock.requestRandomWords( - KEY_HASH, subId, DEFAULT_REQUEST_CONFIRMATIONS, DEFAULT_CALLBACK_GAS_LIMIT, DEFAULT_NUM_WORDS - ); - - bytes4 reason = bytes4(keccak256("InsufficientBalance()")); - vm.expectRevert(toBytes(reason)); - s_vrfCoordinatorV2Mock.fulfillRandomWords(reqId, consumerAddr); - - vm.stopPrank(); - } - - // can request and fulfill [ @skip-coverage ] - function testRequestRandomWordsHappyPath() public { - vm.startPrank(s_subOwner); - uint64 subId = s_vrfCoordinatorV2Mock.createSubscription(); - - s_vrfCoordinatorV2Mock.fundSubscription(subId, oneLink); - - address consumerAddr = address(s_vrfConsumerV2); - s_vrfCoordinatorV2Mock.addConsumer(subId, consumerAddr); - - vm.expectEmit(true, false, false, true); - emit RandomWordsRequested( - KEY_HASH, - 1, - 100, - subId, - DEFAULT_REQUEST_CONFIRMATIONS, - DEFAULT_CALLBACK_GAS_LIMIT, - DEFAULT_NUM_WORDS, - address(s_subOwner) - ); - uint256 reqId = s_vrfConsumerV2.requestRandomness( - KEY_HASH, subId, DEFAULT_REQUEST_CONFIRMATIONS, DEFAULT_CALLBACK_GAS_LIMIT, DEFAULT_NUM_WORDS - ); - - vm.expectEmit(true, false, false, true); - emit RandomWordsFulfilled(reqId, 1, 100_090_192_000_000_000, true); - s_vrfCoordinatorV2Mock.fulfillRandomWords(reqId, consumerAddr); - - vm.stopPrank(); - } - - // Correctly allows for user override of fulfillRandomWords [ @skip-coverage ] - function testRequestRandomWordsUserOverride() public { - vm.startPrank(s_subOwner); - uint64 subId = s_vrfCoordinatorV2Mock.createSubscription(); - - s_vrfCoordinatorV2Mock.fundSubscription(subId, oneLink); - - address consumerAddr = address(s_vrfConsumerV2); - s_vrfCoordinatorV2Mock.addConsumer(subId, consumerAddr); - - vm.expectEmit(true, false, false, true); - emit RandomWordsRequested( - KEY_HASH, 1, 100, subId, DEFAULT_REQUEST_CONFIRMATIONS, DEFAULT_CALLBACK_GAS_LIMIT, 2, address(s_subOwner) - ); - uint256 reqId = - s_vrfConsumerV2.requestRandomness(KEY_HASH, subId, DEFAULT_REQUEST_CONFIRMATIONS, DEFAULT_CALLBACK_GAS_LIMIT, 2); - - bytes4 reason = bytes4(keccak256("InvalidRandomWords()")); - vm.expectRevert(toBytes(reason)); - uint256[] memory words1 = new uint256[](5); - words1[0] = 1; - words1[1] = 2; - words1[2] = 3; - words1[3] = 4; - words1[4] = 5; - s_vrfCoordinatorV2Mock.fulfillRandomWordsWithOverride(reqId, consumerAddr, uint256[](words1)); - - vm.expectEmit(true, false, false, true); - uint256[] memory words2 = new uint256[](2); - words1[0] = 2533; - words1[1] = 1768; - emit RandomWordsFulfilled(reqId, 1, 100_072_264_000_000_000, true); - s_vrfCoordinatorV2Mock.fulfillRandomWordsWithOverride(reqId, consumerAddr, words2); - - vm.stopPrank(); - } - - function toBytes( - bytes4 _data - ) public pure returns (bytes memory) { - return abi.encodePacked(_data); - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFConsumerV2.sol b/contracts/src/v0.8/vrf/testhelpers/VRFConsumerV2.sol deleted file mode 100644 index e6b3f42b0a..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFConsumerV2.sol +++ /dev/null @@ -1,73 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {LinkTokenInterface} from "../../shared/interfaces/LinkTokenInterface.sol"; - -import {VRFConsumerBaseV2} from "../VRFConsumerBaseV2.sol"; -import {VRFCoordinatorV2Interface} from "../interfaces/VRFCoordinatorV2Interface.sol"; - -contract VRFConsumerV2 is VRFConsumerBaseV2 { - uint256[] public s_randomWords; - uint256 public s_requestId; - VRFCoordinatorV2Interface internal COORDINATOR; - LinkTokenInterface internal LINKTOKEN; - uint64 public s_subId; - uint256 public s_gasAvailable; - - constructor( - address vrfCoordinator, - address link - ) VRFConsumerBaseV2(vrfCoordinator) { - COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); - LINKTOKEN = LinkTokenInterface(link); - } - - function fulfillRandomWords( - uint256 requestId, - uint256[] memory randomWords - ) internal override { - require(requestId == s_requestId, "request ID is incorrect"); - - s_gasAvailable = gasleft(); - s_randomWords = randomWords; - } - - function createSubscriptionAndFund( - uint96 amount - ) external { - if (s_subId == 0) { - s_subId = COORDINATOR.createSubscription(); - COORDINATOR.addConsumer(s_subId, address(this)); - } - // Approve the link transfer. - LINKTOKEN.transferAndCall(address(COORDINATOR), amount, abi.encode(s_subId)); - } - - function topUpSubscription( - uint96 amount - ) external { - require(s_subId != 0, "sub not set"); - // Approve the link transfer. - LINKTOKEN.transferAndCall(address(COORDINATOR), amount, abi.encode(s_subId)); - } - - function updateSubscription( - address[] memory consumers - ) external { - require(s_subId != 0, "subID not set"); - for (uint256 i = 0; i < consumers.length; i++) { - COORDINATOR.addConsumer(s_subId, consumers[i]); - } - } - - function requestRandomness( - bytes32 keyHash, - uint64 subId, - uint16 minReqConfs, - uint32 callbackGasLimit, - uint32 numWords - ) external returns (uint256) { - s_requestId = COORDINATOR.requestRandomWords(keyHash, subId, minReqConfs, callbackGasLimit, numWords); - return s_requestId; - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFConsumerV2UpgradeableExample.sol b/contracts/src/v0.8/vrf/testhelpers/VRFConsumerV2UpgradeableExample.sol deleted file mode 100644 index 2cfccb28c6..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFConsumerV2UpgradeableExample.sol +++ /dev/null @@ -1,75 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {LinkTokenInterface} from "../../shared/interfaces/LinkTokenInterface.sol"; - -import {VRFConsumerBaseV2Upgradeable} from "../VRFConsumerBaseV2Upgradeable.sol"; -import {VRFCoordinatorV2Interface} from "../interfaces/VRFCoordinatorV2Interface.sol"; -import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; - -contract VRFConsumerV2UpgradeableExample is Initializable, VRFConsumerBaseV2Upgradeable { - uint256[] public s_randomWords; - uint256 public s_requestId; - VRFCoordinatorV2Interface public COORDINATOR; - LinkTokenInterface public LINKTOKEN; - uint64 public s_subId; - uint256 public s_gasAvailable; - - function initialize( - address _vrfCoordinator, - address _link - ) public initializer { - __VRFConsumerBaseV2_init(_vrfCoordinator); - COORDINATOR = VRFCoordinatorV2Interface(_vrfCoordinator); - LINKTOKEN = LinkTokenInterface(_link); - } - - function fulfillRandomWords( - uint256 requestId, - uint256[] memory randomWords - ) internal override { - require(requestId == s_requestId, "request ID is incorrect"); - - s_gasAvailable = gasleft(); - s_randomWords = randomWords; - } - - function createSubscriptionAndFund( - uint96 amount - ) external { - if (s_subId == 0) { - s_subId = COORDINATOR.createSubscription(); - COORDINATOR.addConsumer(s_subId, address(this)); - } - // Approve the link transfer. - LINKTOKEN.transferAndCall(address(COORDINATOR), amount, abi.encode(s_subId)); - } - - function topUpSubscription( - uint96 amount - ) external { - require(s_subId != 0, "sub not set"); - // Approve the link transfer. - LINKTOKEN.transferAndCall(address(COORDINATOR), amount, abi.encode(s_subId)); - } - - function updateSubscription( - address[] memory consumers - ) external { - require(s_subId != 0, "subID not set"); - for (uint256 i = 0; i < consumers.length; i++) { - COORDINATOR.addConsumer(s_subId, consumers[i]); - } - } - - function requestRandomness( - bytes32 keyHash, - uint64 subId, - uint16 minReqConfs, - uint32 callbackGasLimit, - uint32 numWords - ) external returns (uint256) { - s_requestId = COORDINATOR.requestRandomWords(keyHash, subId, minReqConfs, callbackGasLimit, numWords); - return s_requestId; - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFCoordinatorTestV2.sol b/contracts/src/v0.8/vrf/testhelpers/VRFCoordinatorTestV2.sol deleted file mode 100644 index a163bef9c1..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFCoordinatorTestV2.sol +++ /dev/null @@ -1,866 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.4; - -import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol"; -import {AggregatorV3Interface} from "../../shared/interfaces/AggregatorV3Interface.sol"; -import {IERC677Receiver} from "../../shared/interfaces/IERC677Receiver.sol"; -import {ITypeAndVersion} from "../../shared/interfaces/ITypeAndVersion.sol"; -import {LinkTokenInterface} from "../../shared/interfaces/LinkTokenInterface.sol"; - -import {VRF} from "../VRF.sol"; -import {VRFConsumerBaseV2} from "../VRFConsumerBaseV2.sol"; -import {BlockhashStoreInterface} from "../interfaces/BlockhashStoreInterface.sol"; -import {VRFCoordinatorV2Interface} from "../interfaces/VRFCoordinatorV2Interface.sol"; - -contract VRFCoordinatorTestV2 is VRF, ConfirmedOwner, ITypeAndVersion, VRFCoordinatorV2Interface, IERC677Receiver { - LinkTokenInterface public immutable LINK; - AggregatorV3Interface public immutable LINK_ETH_FEED; - BlockhashStoreInterface public immutable BLOCKHASH_STORE; - - // We need to maintain a list of consuming addresses. - // This bound ensures we are able to loop over them as needed. - // Should a user require more consumers, they can use multiple subscriptions. - uint16 public constant MAX_CONSUMERS = 100; - - error TooManyConsumers(); - error InsufficientBalance(); - error InvalidConsumer(uint64 subId, address consumer); - error InvalidSubscription(); - error OnlyCallableFromLink(); - error InvalidCalldata(); - error MustBeSubOwner(address owner); - error PendingRequestExists(); - error MustBeRequestedOwner(address proposedOwner); - error BalanceInvariantViolated(uint256 internalBalance, uint256 externalBalance); // Should never happen - - event FundsRecovered(address to, uint256 amount); - // We use the subscription struct (1 word) - // at fulfillment time. - - struct Subscription { - // There are only 1e9*1e18 = 1e27 juels in existence, so the balance can fit in uint96 (2^96 ~ 7e28) - uint96 balance; // Common link balance used for all consumer requests. - uint64 reqCount; // For fee tiers - } - // We use the config for the mgmt APIs - - struct SubscriptionConfig { - address owner; // Owner can fund/withdraw/cancel the sub. - address requestedOwner; // For safely transferring sub ownership. - // Maintains the list of keys in s_consumers. - // We do this for 2 reasons: - // 1. To be able to clean up all keys from s_consumers when canceling a subscription. - // 2. To be able to return the list of all consumers in getSubscription. - // Note that we need the s_consumers map to be able to directly check if a - // consumer is valid without reading all the consumers from storage. - address[] consumers; - } - // Note a nonce of 0 indicates an the consumer is not assigned to that subscription. - - mapping(address => mapping(uint64 => uint64)) private /* consumer */ /* subId */ /* nonce */ s_consumers; - mapping(uint64 => SubscriptionConfig) private /* subId */ /* subscriptionConfig */ s_subscriptionConfigs; - mapping(uint64 => Subscription) private /* subId */ /* subscription */ s_subscriptions; - // We make the sub count public so that its possible to - // get all the current subscriptions via getSubscription. - uint64 private s_currentSubId; - // s_totalBalance tracks the total link sent to/from - // this contract through onTokenTransfer, cancelSubscription and oracleWithdraw. - // A discrepancy with this contract's link balance indicates someone - // sent tokens using transfer and so we may need to use recoverFunds. - uint96 private s_totalBalance; - - event SubscriptionCreated(uint64 indexed subId, address owner); - event SubscriptionFunded(uint64 indexed subId, uint256 oldBalance, uint256 newBalance); - event SubscriptionConsumerAdded(uint64 indexed subId, address consumer); - event SubscriptionConsumerRemoved(uint64 indexed subId, address consumer); - event SubscriptionCanceled(uint64 indexed subId, address to, uint256 amount); - event SubscriptionOwnerTransferRequested(uint64 indexed subId, address from, address to); - event SubscriptionOwnerTransferred(uint64 indexed subId, address from, address to); - - // Set this maximum to 200 to give us a 56 block window to fulfill - // the request before requiring the block hash feeder. - uint16 public constant MAX_REQUEST_CONFIRMATIONS = 200; - uint32 public constant MAX_NUM_WORDS = 500; - // 5k is plenty for an EXTCODESIZE call (2600) + warm CALL (100) - // and some arithmetic operations. - uint256 private constant GAS_FOR_CALL_EXACT_CHECK = 5000; - - error InvalidRequestConfirmations(uint16 have, uint16 min, uint16 max); - error GasLimitTooBig(uint32 have, uint32 want); - error NumWordsTooBig(uint32 have, uint32 want); - error ProvingKeyAlreadyRegistered(bytes32 keyHash); - error NoSuchProvingKey(bytes32 keyHash); - error InvalidLinkWeiPrice(int256 linkWei); - error InsufficientGasForConsumer(uint256 have, uint256 want); - error NoCorrespondingRequest(); - error IncorrectCommitment(); - error BlockhashNotInStore(uint256 blockNum); - error PaymentTooLarge(); - error Reentrant(); - - struct RequestCommitment { - uint64 blockNum; - uint64 subId; - uint32 callbackGasLimit; - uint32 numWords; - address sender; - } - - mapping(bytes32 => address) private /* keyHash */ /* oracle */ s_provingKeys; - bytes32[] private s_provingKeyHashes; - mapping(address => uint96) private /* oracle */ /* LINK balance */ s_withdrawableTokens; - mapping(uint256 => bytes32) private /* requestID */ /* commitment */ s_requestCommitments; - - event ProvingKeyRegistered(bytes32 keyHash, address indexed oracle); - event ProvingKeyDeregistered(bytes32 keyHash, address indexed oracle); - event RandomWordsRequested( - bytes32 indexed keyHash, - uint256 requestId, - uint256 preSeed, - uint64 indexed subId, - uint16 minimumRequestConfirmations, - uint32 callbackGasLimit, - uint32 numWords, - address indexed sender - ); - event RandomWordsFulfilled(uint256 indexed requestId, uint256 outputSeed, uint96 payment, bool success); - - struct Config { - uint16 minimumRequestConfirmations; - uint32 maxGasLimit; - // Reentrancy protection. - bool reentrancyLock; - // stalenessSeconds is how long before we consider the feed price to be stale - // and fallback to fallbackWeiPerUnitLink. - uint32 stalenessSeconds; - // Gas to cover oracle payment after we calculate the payment. - // We make it configurable in case those operations are repriced. - uint32 gasAfterPaymentCalculation; - } - - int256 private s_fallbackWeiPerUnitLink; - Config private s_config; - FeeConfig private s_feeConfig; - - struct FeeConfig { - // Flat fee charged per fulfillment in millionths of link - // So fee range is [0, 2^32/10^6]. - uint32 fulfillmentFlatFeeLinkPPMTier1; - uint32 fulfillmentFlatFeeLinkPPMTier2; - uint32 fulfillmentFlatFeeLinkPPMTier3; - uint32 fulfillmentFlatFeeLinkPPMTier4; - uint32 fulfillmentFlatFeeLinkPPMTier5; - uint24 reqsForTier2; - uint24 reqsForTier3; - uint24 reqsForTier4; - uint24 reqsForTier5; - } - - event ConfigSet( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation, - int256 fallbackWeiPerUnitLink, - FeeConfig feeConfig - ); - - constructor( - address link, - address blockhashStore, - address linkEthFeed - ) ConfirmedOwner(msg.sender) { - LINK = LinkTokenInterface(link); - LINK_ETH_FEED = AggregatorV3Interface(linkEthFeed); - BLOCKHASH_STORE = BlockhashStoreInterface(blockhashStore); - } - - /** - * @notice Registers a proving key to an oracle. - * @param oracle address of the oracle - * @param publicProvingKey key that oracle can use to submit vrf fulfillments - */ - function registerProvingKey( - address oracle, - uint256[2] calldata publicProvingKey - ) external onlyOwner { - bytes32 kh = hashOfKey(publicProvingKey); - if (s_provingKeys[kh] != address(0)) { - revert ProvingKeyAlreadyRegistered(kh); - } - s_provingKeys[kh] = oracle; - s_provingKeyHashes.push(kh); - emit ProvingKeyRegistered(kh, oracle); - } - - /** - * @notice Deregisters a proving key to an oracle. - * @param publicProvingKey key that oracle can use to submit vrf fulfillments - */ - function deregisterProvingKey( - uint256[2] calldata publicProvingKey - ) external onlyOwner { - bytes32 kh = hashOfKey(publicProvingKey); - address oracle = s_provingKeys[kh]; - if (oracle == address(0)) { - revert NoSuchProvingKey(kh); - } - delete s_provingKeys[kh]; - for (uint256 i = 0; i < s_provingKeyHashes.length; i++) { - if (s_provingKeyHashes[i] == kh) { - bytes32 last = s_provingKeyHashes[s_provingKeyHashes.length - 1]; - // Copy last element and overwrite kh to be deleted with it - s_provingKeyHashes[i] = last; - s_provingKeyHashes.pop(); - } - } - emit ProvingKeyDeregistered(kh, oracle); - } - - /** - * @notice Returns the proving key hash key associated with this public key - * @param publicKey the key to return the hash of - */ - function hashOfKey( - uint256[2] memory publicKey - ) public pure returns (bytes32) { - return keccak256(abi.encode(publicKey)); - } - - /** - * @notice Sets the configuration of the vrfv2 coordinator - * @param minimumRequestConfirmations global min for request confirmations - * @param maxGasLimit global max for request gas limit - * @param stalenessSeconds if the eth/link feed is more stale then this, use the fallback price - * @param gasAfterPaymentCalculation gas used in doing accounting after completing the gas measurement - * @param fallbackWeiPerUnitLink fallback eth/link price in the case of a stale feed - * @param feeConfig fee tier configuration - */ - function setConfig( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation, - int256 fallbackWeiPerUnitLink, - FeeConfig memory feeConfig - ) external onlyOwner { - if (minimumRequestConfirmations > MAX_REQUEST_CONFIRMATIONS) { - revert InvalidRequestConfirmations( - minimumRequestConfirmations, minimumRequestConfirmations, MAX_REQUEST_CONFIRMATIONS - ); - } - if (fallbackWeiPerUnitLink <= 0) { - revert InvalidLinkWeiPrice(fallbackWeiPerUnitLink); - } - s_config = Config({ - minimumRequestConfirmations: minimumRequestConfirmations, - maxGasLimit: maxGasLimit, - stalenessSeconds: stalenessSeconds, - gasAfterPaymentCalculation: gasAfterPaymentCalculation, - reentrancyLock: false - }); - s_feeConfig = feeConfig; - s_fallbackWeiPerUnitLink = fallbackWeiPerUnitLink; - emit ConfigSet( - minimumRequestConfirmations, - maxGasLimit, - stalenessSeconds, - gasAfterPaymentCalculation, - fallbackWeiPerUnitLink, - s_feeConfig - ); - } - - function getConfig() - external - view - returns ( - uint16 minimumRequestConfirmations, - uint32 maxGasLimit, - uint32 stalenessSeconds, - uint32 gasAfterPaymentCalculation - ) - { - return ( - s_config.minimumRequestConfirmations, - s_config.maxGasLimit, - s_config.stalenessSeconds, - s_config.gasAfterPaymentCalculation - ); - } - - function getFeeConfig() - external - view - returns ( - uint32 fulfillmentFlatFeeLinkPPMTier1, - uint32 fulfillmentFlatFeeLinkPPMTier2, - uint32 fulfillmentFlatFeeLinkPPMTier3, - uint32 fulfillmentFlatFeeLinkPPMTier4, - uint32 fulfillmentFlatFeeLinkPPMTier5, - uint24 reqsForTier2, - uint24 reqsForTier3, - uint24 reqsForTier4, - uint24 reqsForTier5 - ) - { - return ( - s_feeConfig.fulfillmentFlatFeeLinkPPMTier1, - s_feeConfig.fulfillmentFlatFeeLinkPPMTier2, - s_feeConfig.fulfillmentFlatFeeLinkPPMTier3, - s_feeConfig.fulfillmentFlatFeeLinkPPMTier4, - s_feeConfig.fulfillmentFlatFeeLinkPPMTier5, - s_feeConfig.reqsForTier2, - s_feeConfig.reqsForTier3, - s_feeConfig.reqsForTier4, - s_feeConfig.reqsForTier5 - ); - } - - function getTotalBalance() external view returns (uint256) { - return s_totalBalance; - } - - function getFallbackWeiPerUnitLink() external view returns (int256) { - return s_fallbackWeiPerUnitLink; - } - - /** - * @notice Owner cancel subscription, sends remaining link directly to the subscription owner. - * @param subId subscription id - * @dev notably can be called even if there are pending requests, outstanding ones may fail onchain - */ - function ownerCancelSubscription( - uint64 subId - ) external onlyOwner { - if (s_subscriptionConfigs[subId].owner == address(0)) { - revert InvalidSubscription(); - } - cancelSubscriptionHelper(subId, s_subscriptionConfigs[subId].owner); - } - - /** - * @notice Recover link sent with transfer instead of transferAndCall. - * @param to address to send link to - */ - function recoverFunds( - address to - ) external onlyOwner { - uint256 externalBalance = LINK.balanceOf(address(this)); - uint256 internalBalance = uint256(s_totalBalance); - if (internalBalance > externalBalance) { - revert BalanceInvariantViolated(internalBalance, externalBalance); - } - if (internalBalance < externalBalance) { - uint256 amount = externalBalance - internalBalance; - LINK.transfer(to, amount); - emit FundsRecovered(to, amount); - } - // If the balances are equal, nothing to be done. - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function getRequestConfig() external view override returns (uint16, uint32, bytes32[] memory) { - return (s_config.minimumRequestConfirmations, s_config.maxGasLimit, s_provingKeyHashes); - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function requestRandomWords( - bytes32 keyHash, - uint64 subId, - uint16 requestConfirmations, - uint32 callbackGasLimit, - uint32 numWords - ) external override nonReentrant returns (uint256) { - // Input validation using the subscription storage. - if (s_subscriptionConfigs[subId].owner == address(0)) { - revert InvalidSubscription(); - } - // Its important to ensure that the consumer is in fact who they say they - // are, otherwise they could use someone else's subscription balance. - // A nonce of 0 indicates consumer is not allocated to the sub. - uint64 currentNonce = s_consumers[msg.sender][subId]; - if (currentNonce == 0) { - revert InvalidConsumer(subId, msg.sender); - } - // Input validation using the config storage word. - if (requestConfirmations < s_config.minimumRequestConfirmations || requestConfirmations > MAX_REQUEST_CONFIRMATIONS) - { - revert InvalidRequestConfirmations( - requestConfirmations, s_config.minimumRequestConfirmations, MAX_REQUEST_CONFIRMATIONS - ); - } - // No lower bound on the requested gas limit. A user could request 0 - // and they would simply be billed for the proof verification and wouldn't be - // able to do anything with the random value. - if (callbackGasLimit > s_config.maxGasLimit) { - revert GasLimitTooBig(callbackGasLimit, s_config.maxGasLimit); - } - if (numWords > MAX_NUM_WORDS) { - revert NumWordsTooBig(numWords, MAX_NUM_WORDS); - } - // Note we do not check whether the keyHash is valid to save gas. - // The consequence for users is that they can send requests - // for invalid keyHashes which will simply not be fulfilled. - uint64 nonce = currentNonce + 1; - (uint256 requestId, uint256 preSeed) = computeRequestId(keyHash, msg.sender, subId, nonce); - - s_requestCommitments[requestId] = - keccak256(abi.encode(requestId, block.number, subId, callbackGasLimit, numWords, msg.sender)); - emit RandomWordsRequested( - keyHash, requestId, preSeed, subId, requestConfirmations, callbackGasLimit, numWords, msg.sender - ); - s_consumers[msg.sender][subId] = nonce; - - return requestId; - } - - /** - * @notice Get request commitment - * @param requestId id of request - * @dev used to determine if a request is fulfilled or not - */ - function getCommitment( - uint256 requestId - ) external view returns (bytes32) { - return s_requestCommitments[requestId]; - } - - function computeRequestId( - bytes32 keyHash, - address sender, - uint64 subId, - uint64 nonce - ) private pure returns (uint256, uint256) { - uint256 preSeed = uint256(keccak256(abi.encode(keyHash, sender, subId, nonce))); - return (uint256(keccak256(abi.encode(keyHash, preSeed))), preSeed); - } - - /** - * @dev calls target address with exactly gasAmount gas and data as calldata - * or reverts if at least gasAmount gas is not available. - */ - function callWithExactGas( - uint256 gasAmount, - address target, - bytes memory data - ) private returns (bool success) { - // solhint-disable-next-line no-inline-assembly - assembly { - let g := gas() - // Compute g -= GAS_FOR_CALL_EXACT_CHECK and check for underflow - // The gas actually passed to the callee is min(gasAmount, 63//64*gas available). - // We want to ensure that we revert if gasAmount > 63//64*gas available - // as we do not want to provide them with less, however that check itself costs - // gas. GAS_FOR_CALL_EXACT_CHECK ensures we have at least enough gas to be able - // to revert if gasAmount > 63//64*gas available. - if lt(g, GAS_FOR_CALL_EXACT_CHECK) { revert(0, 0) } - g := sub(g, GAS_FOR_CALL_EXACT_CHECK) - // if g - g//64 <= gasAmount, revert - // (we subtract g//64 because of EIP-150) - if iszero(gt(sub(g, div(g, 64)), gasAmount)) { revert(0, 0) } - // solidity calls check that a contract actually exists at the destination, so we do the same - if iszero(extcodesize(target)) { revert(0, 0) } - // call and return whether we succeeded. ignore return data - // call(gas,addr,value,argsOffset,argsLength,retOffset,retLength) - success := call(gasAmount, target, 0, add(data, 0x20), mload(data), 0, 0) - } - return success; - } - - function getRandomnessFromProof( - Proof calldata proof, - RequestCommitment calldata rc - ) private view returns (bytes32 keyHash, uint256 requestId, uint256 randomness) { - keyHash = hashOfKey(proof.pk); - // Only registered proving keys are permitted. - address oracle = s_provingKeys[keyHash]; - if (oracle == address(0)) { - revert NoSuchProvingKey(keyHash); - } - requestId = uint256(keccak256(abi.encode(keyHash, proof.seed))); - bytes32 commitment = s_requestCommitments[requestId]; - if (commitment == 0) { - revert NoCorrespondingRequest(); - } - if ( - commitment != keccak256(abi.encode(requestId, rc.blockNum, rc.subId, rc.callbackGasLimit, rc.numWords, rc.sender)) - ) { - revert IncorrectCommitment(); - } - - bytes32 blockHash = blockhash(rc.blockNum); - if (blockHash == bytes32(0)) { - blockHash = BLOCKHASH_STORE.getBlockhash(rc.blockNum); - if (blockHash == bytes32(0)) { - revert BlockhashNotInStore(rc.blockNum); - } - } - - // The seed actually used by the VRF machinery, mixing in the blockhash - uint256 actualSeed = uint256(keccak256(abi.encodePacked(proof.seed, blockHash))); - randomness = VRF._randomValueFromVRFProof(proof, actualSeed); // Reverts on failure - } - - /* - * @notice Compute fee based on the request count - * @param reqCount number of requests - * @return feePPM fee in LINK PPM - */ - function getFeeTier( - uint64 reqCount - ) public view returns (uint32) { - FeeConfig memory fc = s_feeConfig; - if (0 <= reqCount && reqCount <= fc.reqsForTier2) { - return fc.fulfillmentFlatFeeLinkPPMTier1; - } - if (fc.reqsForTier2 < reqCount && reqCount <= fc.reqsForTier3) { - return fc.fulfillmentFlatFeeLinkPPMTier2; - } - if (fc.reqsForTier3 < reqCount && reqCount <= fc.reqsForTier4) { - return fc.fulfillmentFlatFeeLinkPPMTier3; - } - if (fc.reqsForTier4 < reqCount && reqCount <= fc.reqsForTier5) { - return fc.fulfillmentFlatFeeLinkPPMTier4; - } - return fc.fulfillmentFlatFeeLinkPPMTier5; - } - - /* - * @notice Fulfill a randomness request - * @param proof contains the proof and randomness - * @param rc request commitment pre-image, committed to at request time - * @return payment amount billed to the subscription - * @dev simulated offchain to determine if sufficient balance is present to fulfill the request - */ - function fulfillRandomWords( - Proof calldata proof, - RequestCommitment calldata rc - ) external nonReentrant returns (uint96) { - uint256 startGas = gasleft(); - (bytes32 keyHash, uint256 requestId, uint256 randomness) = getRandomnessFromProof(proof, rc); - - uint256[] memory randomWords = new uint256[](rc.numWords); - for (uint256 i = 0; i < rc.numWords; i++) { - randomWords[i] = uint256(keccak256(abi.encode(randomness, i))); - } - - delete s_requestCommitments[requestId]; - VRFConsumerBaseV2 v; - bytes memory resp = abi.encodeWithSelector(v.rawFulfillRandomWords.selector, requestId, randomWords); - // Call with explicitly the amount of callback gas requested - // Important to not let them exhaust the gas budget and avoid oracle payment. - // Do not allow any non-view/non-pure coordinator functions to be called - // during the consumers callback code via reentrancyLock. - // Note that callWithExactGas will revert if we do not have sufficient gas - // to give the callee their requested amount. - s_config.reentrancyLock = true; - bool success = callWithExactGas(rc.callbackGasLimit, rc.sender, resp); - s_config.reentrancyLock = false; - - // Increment the req count for fee tier selection. - uint64 reqCount = s_subscriptions[rc.subId].reqCount; - s_subscriptions[rc.subId].reqCount += 1; - - // We want to charge users exactly for how much gas they use in their callback. - // The gasAfterPaymentCalculation is meant to cover these additional operations where we - // decrement the subscription balance and increment the oracles withdrawable balance. - // We also add the flat link fee to the payment amount. - // Its specified in millionths of link, if s_config.fulfillmentFlatFeeLinkPPM = 1 - // 1 link / 1e6 = 1e18 juels / 1e6 = 1e12 juels. - uint96 payment = - calculatePaymentAmount(startGas, s_config.gasAfterPaymentCalculation, getFeeTier(reqCount), tx.gasprice); - if (s_subscriptions[rc.subId].balance < payment) { - revert InsufficientBalance(); - } - s_subscriptions[rc.subId].balance -= payment; - s_withdrawableTokens[s_provingKeys[keyHash]] += payment; - // Include payment in the event for tracking costs. - emit RandomWordsFulfilled(requestId, randomness, payment, success); - return payment; - } - - // Get the amount of gas used for fulfillment - function calculatePaymentAmount( - uint256 startGas, - uint256 gasAfterPaymentCalculation, - uint32 fulfillmentFlatFeeLinkPPM, - uint256 weiPerUnitGas - ) internal view returns (uint96) { - int256 weiPerUnitLink; - weiPerUnitLink = getFeedData(); - if (weiPerUnitLink <= 0) { - revert InvalidLinkWeiPrice(weiPerUnitLink); - } - // (1e18 juels/link) (wei/gas * gas) / (wei/link) = juels - uint256 paymentNoFee = - (1e18 * weiPerUnitGas * (gasAfterPaymentCalculation + startGas - gasleft())) / uint256(weiPerUnitLink); - uint256 fee = 1e12 * uint256(fulfillmentFlatFeeLinkPPM); - if (paymentNoFee > (1e27 - fee)) { - revert PaymentTooLarge(); // Payment + fee cannot be more than all of the link in existence. - } - return uint96(paymentNoFee + fee); - } - - function getFeedData() private view returns (int256) { - uint32 stalenessSeconds = s_config.stalenessSeconds; - bool staleFallback = stalenessSeconds > 0; - uint256 timestamp; - int256 weiPerUnitLink; - (, weiPerUnitLink,, timestamp,) = LINK_ETH_FEED.latestRoundData(); - // solhint-disable-next-line not-rely-on-time - if (staleFallback && stalenessSeconds < block.timestamp - timestamp) { - weiPerUnitLink = s_fallbackWeiPerUnitLink; - } - return weiPerUnitLink; - } - - /* - * @notice Oracle withdraw LINK earned through fulfilling requests - * @param recipient where to send the funds - * @param amount amount to withdraw - */ - function oracleWithdraw( - address recipient, - uint96 amount - ) external nonReentrant { - if (s_withdrawableTokens[msg.sender] < amount) { - revert InsufficientBalance(); - } - s_withdrawableTokens[msg.sender] -= amount; - s_totalBalance -= amount; - if (!LINK.transfer(recipient, amount)) { - revert InsufficientBalance(); - } - } - - function onTokenTransfer( - address, - /* sender */ - uint256 amount, - bytes calldata data - ) external override nonReentrant { - if (msg.sender != address(LINK)) { - revert OnlyCallableFromLink(); - } - if (data.length != 32) { - revert InvalidCalldata(); - } - uint64 subId = abi.decode(data, (uint64)); - if (s_subscriptionConfigs[subId].owner == address(0)) { - revert InvalidSubscription(); - } - // We do not check that the msg.sender is the subscription owner, - // anyone can fund a subscription. - uint256 oldBalance = s_subscriptions[subId].balance; - s_subscriptions[subId].balance += uint96(amount); - s_totalBalance += uint96(amount); - emit SubscriptionFunded(subId, oldBalance, oldBalance + amount); - } - - function getCurrentSubId() external view returns (uint64) { - return s_currentSubId; - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function getSubscription( - uint64 subId - ) external view override returns (uint96 balance, uint64 reqCount, address owner, address[] memory consumers) { - if (s_subscriptionConfigs[subId].owner == address(0)) { - revert InvalidSubscription(); - } - return ( - s_subscriptions[subId].balance, - s_subscriptions[subId].reqCount, - s_subscriptionConfigs[subId].owner, - s_subscriptionConfigs[subId].consumers - ); - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function createSubscription() external override nonReentrant returns (uint64) { - s_currentSubId++; - uint64 currentSubId = s_currentSubId; - address[] memory consumers = new address[](0); - s_subscriptions[currentSubId] = Subscription({balance: 0, reqCount: 0}); - s_subscriptionConfigs[currentSubId] = - SubscriptionConfig({owner: msg.sender, requestedOwner: address(0), consumers: consumers}); - - emit SubscriptionCreated(currentSubId, msg.sender); - return currentSubId; - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function requestSubscriptionOwnerTransfer( - uint64 subId, - address newOwner - ) external override onlySubOwner(subId) nonReentrant { - // Proposing to address(0) would never be claimable so don't need to check. - if (s_subscriptionConfigs[subId].requestedOwner != newOwner) { - s_subscriptionConfigs[subId].requestedOwner = newOwner; - emit SubscriptionOwnerTransferRequested(subId, msg.sender, newOwner); - } - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function acceptSubscriptionOwnerTransfer( - uint64 subId - ) external override nonReentrant { - if (s_subscriptionConfigs[subId].owner == address(0)) { - revert InvalidSubscription(); - } - if (s_subscriptionConfigs[subId].requestedOwner != msg.sender) { - revert MustBeRequestedOwner(s_subscriptionConfigs[subId].requestedOwner); - } - address oldOwner = s_subscriptionConfigs[subId].owner; - s_subscriptionConfigs[subId].owner = msg.sender; - s_subscriptionConfigs[subId].requestedOwner = address(0); - emit SubscriptionOwnerTransferred(subId, oldOwner, msg.sender); - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function removeConsumer( - uint64 subId, - address consumer - ) external override onlySubOwner(subId) nonReentrant { - if (s_consumers[consumer][subId] == 0) { - revert InvalidConsumer(subId, consumer); - } - // Note bounded by MAX_CONSUMERS - address[] memory consumers = s_subscriptionConfigs[subId].consumers; - uint256 lastConsumerIndex = consumers.length - 1; - for (uint256 i = 0; i < consumers.length; i++) { - if (consumers[i] == consumer) { - address last = consumers[lastConsumerIndex]; - // Storage write to preserve last element - s_subscriptionConfigs[subId].consumers[i] = last; - // Storage remove last element - s_subscriptionConfigs[subId].consumers.pop(); - break; - } - } - delete s_consumers[consumer][subId]; - emit SubscriptionConsumerRemoved(subId, consumer); - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function addConsumer( - uint64 subId, - address consumer - ) external override onlySubOwner(subId) nonReentrant { - // Already maxed, cannot add any more consumers. - if (s_subscriptionConfigs[subId].consumers.length == MAX_CONSUMERS) { - revert TooManyConsumers(); - } - if (s_consumers[consumer][subId] != 0) { - // Idempotence - do nothing if already added. - // Ensures uniqueness in s_subscriptions[subId].consumers. - return; - } - // Initialize the nonce to 1, indicating the consumer is allocated. - s_consumers[consumer][subId] = 1; - s_subscriptionConfigs[subId].consumers.push(consumer); - - emit SubscriptionConsumerAdded(subId, consumer); - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - */ - function cancelSubscription( - uint64 subId, - address to - ) external override onlySubOwner(subId) nonReentrant { - if (pendingRequestExists(subId)) { - revert PendingRequestExists(); - } - cancelSubscriptionHelper(subId, to); - } - - function cancelSubscriptionHelper( - uint64 subId, - address to - ) private nonReentrant { - SubscriptionConfig memory subConfig = s_subscriptionConfigs[subId]; - Subscription memory sub = s_subscriptions[subId]; - uint96 balance = sub.balance; - // Note bounded by MAX_CONSUMERS; - // If no consumers, does nothing. - for (uint256 i = 0; i < subConfig.consumers.length; i++) { - delete s_consumers[subConfig.consumers[i]][subId]; - } - delete s_subscriptionConfigs[subId]; - delete s_subscriptions[subId]; - s_totalBalance -= balance; - if (!LINK.transfer(to, uint256(balance))) { - revert InsufficientBalance(); - } - emit SubscriptionCanceled(subId, to, balance); - } - - /** - * @inheritdoc VRFCoordinatorV2Interface - * @dev Looping is bounded to MAX_CONSUMERS*(number of keyhashes). - * @dev Used to disable subscription canceling while outstanding request are present. - */ - function pendingRequestExists( - uint64 subId - ) public view override returns (bool) { - SubscriptionConfig memory subConfig = s_subscriptionConfigs[subId]; - for (uint256 i = 0; i < subConfig.consumers.length; i++) { - for (uint256 j = 0; j < s_provingKeyHashes.length; j++) { - (uint256 reqId,) = computeRequestId( - s_provingKeyHashes[j], subConfig.consumers[i], subId, s_consumers[subConfig.consumers[i]][subId] - ); - if (s_requestCommitments[reqId] != 0) { - return true; - } - } - } - return false; - } - - modifier onlySubOwner( - uint64 subId - ) { - address owner = s_subscriptionConfigs[subId].owner; - if (owner == address(0)) { - revert InvalidSubscription(); - } - if (msg.sender != owner) { - revert MustBeSubOwner(owner); - } - _; - } - - modifier nonReentrant() { - if (s_config.reentrancyLock) { - revert Reentrant(); - } - _; - } - - /** - * @notice The type and version of this contract - * @return Type and version string - */ - function typeAndVersion() external pure virtual override returns (string memory) { - return "VRFCoordinatorV2 1.0.0"; - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFCoordinatorV2TestHelper.sol b/contracts/src/v0.8/vrf/testhelpers/VRFCoordinatorV2TestHelper.sol deleted file mode 100644 index d94ffa7ced..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFCoordinatorV2TestHelper.sol +++ /dev/null @@ -1,85 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {AggregatorV3Interface} from "../../shared/interfaces/AggregatorV3Interface.sol"; - -// Ideally this contract should inherit from VRFCoordinatorV2 and delegate calls to VRFCoordinatorV2 -// However, due to exceeding contract size limit, the logic from VRFCoordinatorV2 is ported over to this contract -contract VRFCoordinatorV2TestHelper { - uint96 internal s_paymentAmount; - - AggregatorV3Interface public immutable LINK_ETH_FEED; - - struct Config { - uint16 minimumRequestConfirmations; - uint32 maxGasLimit; - // Reentrancy protection. - bool reentrancyLock; - // stalenessSeconds is how long before we consider the feed price to be stale - // and fallback to fallbackWeiPerUnitLink. - uint32 stalenessSeconds; - // Gas to cover oracle payment after we calculate the payment. - // We make it configurable in case those operations are repriced. - uint32 gasAfterPaymentCalculation; - } - - int256 private s_fallbackWeiPerUnitLink; - Config private s_config; - - constructor( - address linkEthFeed // solhint-disable-next-line no-empty-blocks - ) { - LINK_ETH_FEED = AggregatorV3Interface(linkEthFeed); - } - - function calculatePaymentAmountTest( - uint256 gasAfterPaymentCalculation, - uint32 fulfillmentFlatFeeLinkPPM, - uint256 weiPerUnitGas - ) external { - s_paymentAmount = - calculatePaymentAmount(gasleft(), gasAfterPaymentCalculation, fulfillmentFlatFeeLinkPPM, weiPerUnitGas); - } - - error InvalidLinkWeiPrice(int256 linkWei); - error PaymentTooLarge(); - - function getFeedData() private view returns (int256) { - uint32 stalenessSeconds = s_config.stalenessSeconds; - bool staleFallback = stalenessSeconds > 0; - uint256 timestamp; - int256 weiPerUnitLink; - (, weiPerUnitLink,, timestamp,) = LINK_ETH_FEED.latestRoundData(); - // solhint-disable-next-line not-rely-on-time - if (staleFallback && stalenessSeconds < block.timestamp - timestamp) { - weiPerUnitLink = s_fallbackWeiPerUnitLink; - } - return weiPerUnitLink; - } - - // Get the amount of gas used for fulfillment - function calculatePaymentAmount( - uint256 startGas, - uint256 gasAfterPaymentCalculation, - uint32 fulfillmentFlatFeeLinkPPM, - uint256 weiPerUnitGas - ) internal view returns (uint96) { - int256 weiPerUnitLink; - weiPerUnitLink = getFeedData(); - if (weiPerUnitLink <= 0) { - revert InvalidLinkWeiPrice(weiPerUnitLink); - } - // (1e18 juels/link) (wei/gas * gas) / (wei/link) = juels - uint256 paymentNoFee = - (1e18 * weiPerUnitGas * (gasAfterPaymentCalculation + startGas - gasleft())) / uint256(weiPerUnitLink); - uint256 fee = 1e12 * uint256(fulfillmentFlatFeeLinkPPM); - if (paymentNoFee > (1e27 - fee)) { - revert PaymentTooLarge(); // Payment + fee cannot be more than all of the link in existence. - } - return uint96(paymentNoFee + fee); - } - - function getPaymentAmount() public view returns (uint96) { - return s_paymentAmount; - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFExternalSubOwnerExample.sol b/contracts/src/v0.8/vrf/testhelpers/VRFExternalSubOwnerExample.sol deleted file mode 100644 index d0e331164c..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFExternalSubOwnerExample.sol +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {LinkTokenInterface} from "../../shared/interfaces/LinkTokenInterface.sol"; - -import {VRFConsumerBaseV2} from "../VRFConsumerBaseV2.sol"; -import {VRFCoordinatorV2Interface} from "../interfaces/VRFCoordinatorV2Interface.sol"; - -contract VRFExternalSubOwnerExample is VRFConsumerBaseV2 { - VRFCoordinatorV2Interface internal COORDINATOR; - LinkTokenInterface internal LINKTOKEN; - - uint256[] public s_randomWords; - uint256 public s_requestId; - address internal s_owner; - - constructor( - address vrfCoordinator, - address link - ) VRFConsumerBaseV2(vrfCoordinator) { - COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); - LINKTOKEN = LinkTokenInterface(link); - s_owner = msg.sender; - } - - function fulfillRandomWords( - uint256 requestId, - uint256[] memory randomWords - ) internal override { - require(requestId == s_requestId, "request ID is incorrect"); - s_randomWords = randomWords; - } - - function requestRandomWords( - uint64 subId, - uint32 callbackGasLimit, - uint16 requestConfirmations, - uint32 numWords, - bytes32 keyHash - ) external onlyOwner { - // Will revert if subscription is not funded. - s_requestId = COORDINATOR.requestRandomWords(keyHash, subId, requestConfirmations, callbackGasLimit, numWords); - } - - function transferOwnership( - address newOwner - ) external onlyOwner { - s_owner = newOwner; - } - - modifier onlyOwner() { - require(msg.sender == s_owner); - _; - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFLoadTestExternalSubOwner.sol b/contracts/src/v0.8/vrf/testhelpers/VRFLoadTestExternalSubOwner.sol deleted file mode 100644 index 2ee374c0cf..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFLoadTestExternalSubOwner.sol +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol"; -import {LinkTokenInterface} from "../../shared/interfaces/LinkTokenInterface.sol"; -import {VRFConsumerBaseV2} from "../VRFConsumerBaseV2.sol"; -import {VRFCoordinatorV2Interface} from "../interfaces/VRFCoordinatorV2Interface.sol"; - -/** - * @title The VRFLoadTestExternalSubOwner contract. - * @notice Allows making many VRF V2 randomness requests in a single transaction for load testing. - */ -contract VRFLoadTestExternalSubOwner is VRFConsumerBaseV2, ConfirmedOwner { - VRFCoordinatorV2Interface public immutable COORDINATOR; - LinkTokenInterface public immutable LINK; - - uint256 public s_responseCount; - - constructor( - address _vrfCoordinator, - address _link - ) VRFConsumerBaseV2(_vrfCoordinator) ConfirmedOwner(msg.sender) { - COORDINATOR = VRFCoordinatorV2Interface(_vrfCoordinator); - LINK = LinkTokenInterface(_link); - } - - function fulfillRandomWords( - uint256, - uint256[] memory - ) internal override { - s_responseCount++; - } - - function requestRandomWords( - uint64 _subId, - uint16 _requestConfirmations, - bytes32 _keyHash, - uint16 _requestCount - ) external onlyOwner { - for (uint16 i = 0; i < _requestCount; i++) { - COORDINATOR.requestRandomWords(_keyHash, _subId, _requestConfirmations, 50_000, 1); - } - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFMaliciousConsumerV2.sol b/contracts/src/v0.8/vrf/testhelpers/VRFMaliciousConsumerV2.sol deleted file mode 100644 index a41edbb21a..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFMaliciousConsumerV2.sol +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {LinkTokenInterface} from "../../shared/interfaces/LinkTokenInterface.sol"; - -import {VRFConsumerBaseV2} from "../VRFConsumerBaseV2.sol"; -import {VRFCoordinatorV2Interface} from "../interfaces/VRFCoordinatorV2Interface.sol"; - -contract VRFMaliciousConsumerV2 is VRFConsumerBaseV2 { - uint256[] public s_randomWords; - uint256 public s_requestId; - VRFCoordinatorV2Interface internal COORDINATOR; - LinkTokenInterface internal LINKTOKEN; - uint64 public s_subId; - uint256 public s_gasAvailable; - bytes32 internal s_keyHash; - - constructor( - address vrfCoordinator, - address link - ) VRFConsumerBaseV2(vrfCoordinator) { - COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); - LINKTOKEN = LinkTokenInterface(link); - } - - function fulfillRandomWords( - uint256 requestId, - uint256[] memory randomWords - ) internal override { - s_gasAvailable = gasleft(); - s_randomWords = randomWords; - s_requestId = requestId; - // Should revert - COORDINATOR.requestRandomWords(s_keyHash, s_subId, 1, 200_000, 1); - } - - function createSubscriptionAndFund( - uint96 amount - ) external { - if (s_subId == 0) { - s_subId = COORDINATOR.createSubscription(); - COORDINATOR.addConsumer(s_subId, address(this)); - } - // Approve the link transfer. - LINKTOKEN.transferAndCall(address(COORDINATOR), amount, abi.encode(s_subId)); - } - - function updateSubscription( - address[] memory consumers - ) external { - require(s_subId != 0, "subID not set"); - for (uint256 i = 0; i < consumers.length; i++) { - COORDINATOR.addConsumer(s_subId, consumers[i]); - } - } - - function requestRandomness( - bytes32 keyHash - ) external returns (uint256) { - s_keyHash = keyHash; - return COORDINATOR.requestRandomWords(keyHash, s_subId, 1, 500_000, 1); - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFSingleConsumerExample.sol b/contracts/src/v0.8/vrf/testhelpers/VRFSingleConsumerExample.sol deleted file mode 100644 index 4c29ab988f..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFSingleConsumerExample.sol +++ /dev/null @@ -1,114 +0,0 @@ -// SPDX-License-Identifier: MIT -// Example of a single consumer contract which owns the subscription. -pragma solidity ^0.8.0; - -import {LinkTokenInterface} from "../../shared/interfaces/LinkTokenInterface.sol"; - -import {VRFConsumerBaseV2} from "../VRFConsumerBaseV2.sol"; -import {VRFCoordinatorV2Interface} from "../interfaces/VRFCoordinatorV2Interface.sol"; - -contract VRFSingleConsumerExample is VRFConsumerBaseV2 { - VRFCoordinatorV2Interface internal COORDINATOR; - LinkTokenInterface internal LINKTOKEN; - - struct RequestConfig { - uint64 subId; - uint32 callbackGasLimit; - uint16 requestConfirmations; - uint32 numWords; - bytes32 keyHash; - } - - RequestConfig public s_requestConfig; - uint256[] public s_randomWords; - uint256 public s_requestId; - address s_owner; - - constructor( - address vrfCoordinator, - address link, - uint32 callbackGasLimit, - uint16 requestConfirmations, - uint32 numWords, - bytes32 keyHash - ) VRFConsumerBaseV2(vrfCoordinator) { - COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); - LINKTOKEN = LinkTokenInterface(link); - s_owner = msg.sender; - s_requestConfig = RequestConfig({ - subId: 0, // Unset initially - callbackGasLimit: callbackGasLimit, - requestConfirmations: requestConfirmations, - numWords: numWords, - keyHash: keyHash - }); - subscribe(); - } - - function fulfillRandomWords( - uint256 requestId, - uint256[] memory randomWords - ) internal override { - require(requestId == s_requestId, "request ID is incorrect"); - s_randomWords = randomWords; - } - - // Assumes the subscription is funded sufficiently. - function requestRandomWords() external onlyOwner { - RequestConfig memory rc = s_requestConfig; - // Will revert if subscription is not set and funded. - s_requestId = - COORDINATOR.requestRandomWords(rc.keyHash, rc.subId, rc.requestConfirmations, rc.callbackGasLimit, rc.numWords); - } - - // Assumes this contract owns link - // This method is analogous to VRFv1, except the amount - // should be selected based on the keyHash (each keyHash functions like a "gas lane" - // with different link costs). - function fundAndRequestRandomWords( - uint256 amount - ) external onlyOwner { - RequestConfig memory rc = s_requestConfig; - LINKTOKEN.transferAndCall(address(COORDINATOR), amount, abi.encode(s_requestConfig.subId)); - // Will revert if subscription is not set and funded. - s_requestId = - COORDINATOR.requestRandomWords(rc.keyHash, rc.subId, rc.requestConfirmations, rc.callbackGasLimit, rc.numWords); - } - - // Assumes this contract owns link - function topUpSubscription( - uint256 amount - ) external onlyOwner { - LINKTOKEN.transferAndCall(address(COORDINATOR), amount, abi.encode(s_requestConfig.subId)); - } - - function withdraw( - uint256 amount, - address to - ) external onlyOwner { - LINKTOKEN.transfer(to, amount); - } - - function unsubscribe( - address to - ) external onlyOwner { - // Returns funds to this address - COORDINATOR.cancelSubscription(s_requestConfig.subId, to); - s_requestConfig.subId = 0; - } - - // Keep this separate in case the contract want to unsubscribe and then - // resubscribe. - function subscribe() public onlyOwner { - // Create a subscription, current subId - address[] memory consumers = new address[](1); - consumers[0] = address(this); - s_requestConfig.subId = COORDINATOR.createSubscription(); - COORDINATOR.addConsumer(s_requestConfig.subId, consumers[0]); - } - - modifier onlyOwner() { - require(msg.sender == s_owner); - _; - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFSubscriptionBalanceMonitorExposed.sol b/contracts/src/v0.8/vrf/testhelpers/VRFSubscriptionBalanceMonitorExposed.sol deleted file mode 100644 index 148b504f1c..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFSubscriptionBalanceMonitorExposed.sol +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.6; - -import {VRFSubscriptionBalanceMonitor} from "../VRFSubscriptionBalanceMonitor.sol"; - -contract VRFSubscriptionBalanceMonitorExposed is VRFSubscriptionBalanceMonitor { - constructor( - address linkTokenAddress, - address coordinatorAddress, - address keeperRegistryAddress, - uint256 minWaitPeriodSeconds - ) VRFSubscriptionBalanceMonitor(linkTokenAddress, coordinatorAddress, keeperRegistryAddress, minWaitPeriodSeconds) {} - - function setLastTopUpXXXTestOnly( - uint64 target, - uint56 lastTopUpTimestamp - ) external { - s_targets[target].lastTopUpTimestamp = lastTopUpTimestamp; - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFV2LoadTestWithMetrics.sol b/contracts/src/v0.8/vrf/testhelpers/VRFV2LoadTestWithMetrics.sol deleted file mode 100644 index 0aae0a74bc..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFV2LoadTestWithMetrics.sol +++ /dev/null @@ -1,167 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {LinkTokenInterface} from "../../shared/interfaces/LinkTokenInterface.sol"; -import {ChainSpecificUtil} from "../ChainSpecificUtil_v0_8_6.sol"; -import {VRFConsumerBaseV2} from "../VRFConsumerBaseV2.sol"; -import {VRFCoordinatorV2Interface} from "../interfaces/VRFCoordinatorV2Interface.sol"; - -/** - * @title The VRFLoadTestExternalSubOwner contract. - * @notice Allows making many VRF V2 randomness requests in a single transaction for load testing. - */ -contract VRFV2LoadTestWithMetrics is VRFConsumerBaseV2 { - VRFCoordinatorV2Interface public immutable COORDINATOR; - LinkTokenInterface public LINKTOKEN; - uint256 public s_responseCount; - uint256 public s_requestCount; - uint256 public s_averageFulfillmentInMillions = 0; // in millions for better precision - uint256 public s_slowestFulfillment = 0; - uint256 public s_fastestFulfillment = 999; - uint256 public s_lastRequestId; - mapping(uint256 => uint256) internal requestHeights; // requestIds to block number when rand request was made - - event SubscriptionCreatedFundedAndConsumerAdded(uint64 subId, address consumer, uint256 amount); - - struct RequestStatus { - bool fulfilled; - uint256[] randomWords; - uint256 requestTimestamp; - uint256 fulfilmentTimestamp; - uint256 requestBlockNumber; - uint256 fulfilmentBlockNumber; - } - - mapping(uint256 => RequestStatus) public /* requestId */ /* requestStatus */ s_requests; - - constructor( - address _vrfCoordinator - ) VRFConsumerBaseV2(_vrfCoordinator) { - COORDINATOR = VRFCoordinatorV2Interface(_vrfCoordinator); - } - - function fulfillRandomWords( - uint256 _requestId, - uint256[] memory _randomWords - ) internal override { - uint256 fulfilmentBlockNumber = ChainSpecificUtil._getBlockNumber(); - uint256 requestDelay = fulfilmentBlockNumber - requestHeights[_requestId]; - uint256 requestDelayInMillions = requestDelay * 1_000_000; - - if (requestDelay > s_slowestFulfillment) { - s_slowestFulfillment = requestDelay; - } - s_fastestFulfillment = requestDelay < s_fastestFulfillment ? requestDelay : s_fastestFulfillment; - s_averageFulfillmentInMillions = s_responseCount > 0 - ? (s_averageFulfillmentInMillions * s_responseCount + requestDelayInMillions) / (s_responseCount + 1) - : requestDelayInMillions; - - s_requests[_requestId].fulfilled = true; - s_requests[_requestId].randomWords = _randomWords; - s_requests[_requestId].fulfilmentTimestamp = block.timestamp; - s_requests[_requestId].fulfilmentBlockNumber = fulfilmentBlockNumber; - - s_responseCount++; - } - - function requestRandomWords( - uint64 _subId, - uint16 _requestConfirmations, - bytes32 _keyHash, - uint32 _callbackGasLimit, - uint32 _numWords, - uint16 _requestCount - ) external { - _makeLoadTestRequests(_subId, _requestConfirmations, _keyHash, _callbackGasLimit, _numWords, _requestCount); - } - - function requestRandomWordsWithForceFulfill( - uint16 _requestConfirmations, - bytes32 _keyHash, - uint32 _callbackGasLimit, - uint32 _numWords, - uint16 _requestCount, - uint256 _subTopUpAmount, - address _link - ) external { - // create a subscription, address(this) will be the owner - uint64 _subId = COORDINATOR.createSubscription(); - // add address(this) as a consumer on the subscription - COORDINATOR.addConsumer(_subId, address(this)); - topUpSubscription(_subId, _subTopUpAmount, _link); - emit SubscriptionCreatedFundedAndConsumerAdded(_subId, address(this), _subTopUpAmount); - - _makeLoadTestRequests(_subId, _requestConfirmations, _keyHash, _callbackGasLimit, _numWords, _requestCount); - - COORDINATOR.removeConsumer(_subId, address(this)); - COORDINATOR.cancelSubscription(_subId, msg.sender); - } - - function reset() external { - s_averageFulfillmentInMillions = 0; // in millions for better precision - s_slowestFulfillment = 0; - s_fastestFulfillment = 999; - s_requestCount = 0; - s_responseCount = 0; - } - - function getRequestStatus( - uint256 _requestId - ) - external - view - returns ( - bool fulfilled, - uint256[] memory randomWords, - uint256 requestTimestamp, - uint256 fulfilmentTimestamp, - uint256 requestBlockNumber, - uint256 fulfilmentBlockNumber - ) - { - RequestStatus memory request = s_requests[_requestId]; - return ( - request.fulfilled, - request.randomWords, - request.requestTimestamp, - request.fulfilmentTimestamp, - request.requestBlockNumber, - request.fulfilmentBlockNumber - ); - } - - function _makeLoadTestRequests( - uint64 _subId, - uint16 _requestConfirmations, - bytes32 _keyHash, - uint32 _callbackGasLimit, - uint32 _numWords, - uint16 _requestCount - ) internal { - for (uint16 i = 0; i < _requestCount; i++) { - uint256 requestId = - COORDINATOR.requestRandomWords(_keyHash, _subId, _requestConfirmations, _callbackGasLimit, _numWords); - s_lastRequestId = requestId; - uint256 requestBlockNumber = ChainSpecificUtil._getBlockNumber(); - s_requests[requestId] = RequestStatus({ - randomWords: new uint256[](0), - fulfilled: false, - requestTimestamp: block.timestamp, - fulfilmentTimestamp: 0, - requestBlockNumber: requestBlockNumber, - fulfilmentBlockNumber: 0 - }); - s_requestCount++; - requestHeights[requestId] = requestBlockNumber; - } - } - - function topUpSubscription( - uint64 _subId, - uint256 _amount, - address _link - ) public { - LINKTOKEN = LinkTokenInterface(_link); - LINKTOKEN.transferAndCall(address(COORDINATOR), _amount, abi.encode(_subId)); - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFV2OwnerTestConsumer.sol b/contracts/src/v0.8/vrf/testhelpers/VRFV2OwnerTestConsumer.sol deleted file mode 100644 index 023c5b1c36..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFV2OwnerTestConsumer.sol +++ /dev/null @@ -1,142 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol"; - -import {LinkTokenInterface} from "../../shared/interfaces/LinkTokenInterface.sol"; -import {ChainSpecificUtil} from "../ChainSpecificUtil_v0_8_6.sol"; -import {VRFConsumerBaseV2} from "../VRFConsumerBaseV2.sol"; -import {VRFCoordinatorV2Interface} from "../interfaces/VRFCoordinatorV2Interface.sol"; - -contract VRFV2OwnerTestConsumer is VRFConsumerBaseV2, ConfirmedOwner { - VRFCoordinatorV2Interface public COORDINATOR; - LinkTokenInterface public LINKTOKEN; - uint64 public subId; - uint256 public s_responseCount; - uint256 public s_requestCount; - uint256 public s_averageFulfillmentInMillions = 0; // in millions for better precision - uint256 public s_slowestFulfillment = 0; - uint256 public s_fastestFulfillment = 999; - uint256 public s_lastRequestId; - mapping(uint256 => uint256) internal requestHeights; // requestIds to block number when rand request was made - - event SubscriptionCreatedFundedAndConsumerAdded(uint64 subId, address consumer, uint256 amount); - - struct RequestStatus { - bool fulfilled; - uint256[] randomWords; - uint256 requestTimestamp; - uint256 fulfilmentTimestamp; - uint256 requestBlockNumber; - uint256 fulfilmentBlockNumber; - } - - mapping(uint256 => RequestStatus) public /* requestId */ /* requestStatus */ s_requests; - - constructor( - address _vrfCoordinator, - address _link - ) VRFConsumerBaseV2(_vrfCoordinator) ConfirmedOwner(msg.sender) { - COORDINATOR = VRFCoordinatorV2Interface(_vrfCoordinator); - LINKTOKEN = LinkTokenInterface(_link); - } - - function fulfillRandomWords( - uint256 _requestId, - uint256[] memory _randomWords - ) internal override { - uint256 fulfilmentBlockNumber = ChainSpecificUtil._getBlockNumber(); - uint256 requestDelay = fulfilmentBlockNumber - requestHeights[_requestId]; - uint256 requestDelayInMillions = requestDelay * 1_000_000; - - if (requestDelay > s_slowestFulfillment) { - s_slowestFulfillment = requestDelay; - } - s_fastestFulfillment = requestDelay < s_fastestFulfillment ? requestDelay : s_fastestFulfillment; - s_averageFulfillmentInMillions = s_responseCount > 0 - ? (s_averageFulfillmentInMillions * s_responseCount + requestDelayInMillions) / (s_responseCount + 1) - : requestDelayInMillions; - - s_requests[_requestId].fulfilled = true; - s_requests[_requestId].randomWords = _randomWords; - s_requests[_requestId].fulfilmentTimestamp = block.timestamp; - s_requests[_requestId].fulfilmentBlockNumber = fulfilmentBlockNumber; - - s_responseCount++; - } - - function requestRandomWords( - uint16 _requestConfirmations, - bytes32 _keyHash, - uint32 _callbackGasLimit, - uint32 _numWords, - uint16 _requestCount, - uint256 _subTopUpAmount - ) external onlyOwner { - // create a subscription, address(this) will be the owner - subId = COORDINATOR.createSubscription(); - // add address(this) as a consumer on the subscription - COORDINATOR.addConsumer(subId, address(this)); - topUpSubscription(_subTopUpAmount); - emit SubscriptionCreatedFundedAndConsumerAdded(subId, address(this), _subTopUpAmount); - - for (uint16 i = 0; i < _requestCount; i++) { - uint256 requestId = - COORDINATOR.requestRandomWords(_keyHash, subId, _requestConfirmations, _callbackGasLimit, _numWords); - s_lastRequestId = requestId; - uint256 requestBlockNumber = ChainSpecificUtil._getBlockNumber(); - s_requests[requestId] = RequestStatus({ - randomWords: new uint256[](0), - fulfilled: false, - requestTimestamp: block.timestamp, - fulfilmentTimestamp: 0, - requestBlockNumber: requestBlockNumber, - fulfilmentBlockNumber: 0 - }); - s_requestCount++; - requestHeights[requestId] = requestBlockNumber; - } - - COORDINATOR.removeConsumer(subId, address(this)); - COORDINATOR.cancelSubscription(subId, msg.sender); - } - - function reset() external { - s_averageFulfillmentInMillions = 0; // in millions for better precision - s_slowestFulfillment = 0; - s_fastestFulfillment = 999; - s_requestCount = 0; - s_responseCount = 0; - } - - function getRequestStatus( - uint256 _requestId - ) - external - view - returns ( - bool fulfilled, - uint256[] memory randomWords, - uint256 requestTimestamp, - uint256 fulfilmentTimestamp, - uint256 requestBlockNumber, - uint256 fulfilmentBlockNumber - ) - { - RequestStatus memory request = s_requests[_requestId]; - return ( - request.fulfilled, - request.randomWords, - request.requestTimestamp, - request.fulfilmentTimestamp, - request.requestBlockNumber, - request.fulfilmentBlockNumber - ); - } - - function topUpSubscription( - uint256 amount - ) public onlyOwner { - LINKTOKEN.transferAndCall(address(COORDINATOR), amount, abi.encode(subId)); - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFV2ProxyAdmin.sol b/contracts/src/v0.8/vrf/testhelpers/VRFV2ProxyAdmin.sol deleted file mode 100644 index c7b7a5f09e..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFV2ProxyAdmin.sol +++ /dev/null @@ -1,8 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts@4.9.6/proxy/transparent/ProxyAdmin.sol"; - -contract VRFV2ProxyAdmin is ProxyAdmin { - // Nothing here, this is just to generate the gethwrapper for tests. -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFV2RevertingExample.sol b/contracts/src/v0.8/vrf/testhelpers/VRFV2RevertingExample.sol deleted file mode 100644 index 2b4807d845..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFV2RevertingExample.sol +++ /dev/null @@ -1,74 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {LinkTokenInterface} from "../../shared/interfaces/LinkTokenInterface.sol"; - -import {VRFConsumerBaseV2} from "../VRFConsumerBaseV2.sol"; -import {VRFCoordinatorV2Interface} from "../interfaces/VRFCoordinatorV2Interface.sol"; - -// VRFV2RevertingExample will always revert. Used for testing only, useless in prod. -contract VRFV2RevertingExample is VRFConsumerBaseV2 { - uint256[] public s_randomWords; - uint256 public s_requestId; - VRFCoordinatorV2Interface internal COORDINATOR; - LinkTokenInterface internal LINKTOKEN; - uint64 public s_subId; - uint256 public s_gasAvailable; - - constructor( - address vrfCoordinator, - address link - ) VRFConsumerBaseV2(vrfCoordinator) { - COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); - LINKTOKEN = LinkTokenInterface(link); - } - - function fulfillRandomWords( - uint256, - uint256[] memory - ) internal pure override { - // solhint-disable-next-line gas-custom-errors, reason-string - revert(); - } - - function createSubscriptionAndFund( - uint96 amount - ) external { - if (s_subId == 0) { - s_subId = COORDINATOR.createSubscription(); - COORDINATOR.addConsumer(s_subId, address(this)); - } - // Approve the link transfer. - LINKTOKEN.transferAndCall(address(COORDINATOR), amount, abi.encode(s_subId)); - } - - function topUpSubscription( - uint96 amount - ) external { - // solhint-disable-next-line gas-custom-errors - require(s_subId != 0, "sub not set"); - // Approve the link transfer. - LINKTOKEN.transferAndCall(address(COORDINATOR), amount, abi.encode(s_subId)); - } - - function updateSubscription( - address[] memory consumers - ) external { - // solhint-disable-next-line gas-custom-errors - require(s_subId != 0, "subID not set"); - for (uint256 i = 0; i < consumers.length; i++) { - COORDINATOR.addConsumer(s_subId, consumers[i]); - } - } - - function requestRandomness( - bytes32 keyHash, - uint64 subId, - uint16 minReqConfs, - uint32 callbackGasLimit, - uint32 numWords - ) external returns (uint256) { - s_requestId = COORDINATOR.requestRandomWords(keyHash, subId, minReqConfs, callbackGasLimit, numWords); - return s_requestId; - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFV2TransparentUpgradeableProxy.sol b/contracts/src/v0.8/vrf/testhelpers/VRFV2TransparentUpgradeableProxy.sol deleted file mode 100644 index 781a017de6..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFV2TransparentUpgradeableProxy.sol +++ /dev/null @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import "@openzeppelin/contracts@4.9.6/proxy/transparent/TransparentUpgradeableProxy.sol"; - -contract VRFV2TransparentUpgradeableProxy is TransparentUpgradeableProxy { - // Nothing special here, this is just to generate the gethwrapper for tests. - constructor( - address _logic, - address admin_, - bytes memory _data - ) payable TransparentUpgradeableProxy(_logic, admin_, _data) {} -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperConsumerExample.sol b/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperConsumerExample.sol deleted file mode 100644 index 53e8cad366..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperConsumerExample.sol +++ /dev/null @@ -1,63 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.6; - -import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol"; -import {VRFV2WrapperConsumerBase} from "../VRFV2WrapperConsumerBase.sol"; - -contract VRFV2WrapperConsumerExample is VRFV2WrapperConsumerBase, ConfirmedOwner { - event WrappedRequestFulfilled(uint256 requestId, uint256[] randomWords, uint256 payment); - event WrapperRequestMade(uint256 indexed requestId, uint256 paid); - - struct RequestStatus { - uint256 paid; - bool fulfilled; - uint256[] randomWords; - } - - mapping(uint256 => RequestStatus) public /* requestId */ /* requestStatus */ s_requests; - - constructor( - address _link, - address _vrfV2Wrapper - ) ConfirmedOwner(msg.sender) VRFV2WrapperConsumerBase(_link, _vrfV2Wrapper) {} - - function makeRequest( - uint32 _callbackGasLimit, - uint16 _requestConfirmations, - uint32 _numWords - ) external onlyOwner returns (uint256 requestId) { - requestId = requestRandomness(_callbackGasLimit, _requestConfirmations, _numWords); - uint256 paid = VRF_V2_WRAPPER.calculateRequestPrice(_callbackGasLimit); - s_requests[requestId] = RequestStatus({paid: paid, randomWords: new uint256[](0), fulfilled: false}); - emit WrapperRequestMade(requestId, paid); - return requestId; - } - - function fulfillRandomWords( - uint256 _requestId, - uint256[] memory _randomWords - ) internal override { - // solhint-disable-next-line gas-custom-errors - require(s_requests[_requestId].paid > 0, "request not found"); - s_requests[_requestId].fulfilled = true; - s_requests[_requestId].randomWords = _randomWords; - emit WrappedRequestFulfilled(_requestId, _randomWords, s_requests[_requestId].paid); - } - - function getRequestStatus( - uint256 _requestId - ) external view returns (uint256 paid, bool fulfilled, uint256[] memory randomWords) { - // solhint-disable-next-line gas-custom-errors - require(s_requests[_requestId].paid > 0, "request not found"); - RequestStatus memory request = s_requests[_requestId]; - return (request.paid, request.fulfilled, request.randomWords); - } - - /// @notice withdrawLink withdraws the amount specified in amount to the owner - /// @param amount the amount to withdraw, in juels - function withdrawLink( - uint256 amount - ) external onlyOwner { - LINK.transfer(owner(), amount); - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperLoadTestConsumer.sol b/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperLoadTestConsumer.sol deleted file mode 100644 index c54d98282b..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperLoadTestConsumer.sol +++ /dev/null @@ -1,142 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.6; - -import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol"; -import {ChainSpecificUtil} from "../ChainSpecificUtil_v0_8_6.sol"; -import {VRFV2WrapperConsumerBase} from "../VRFV2WrapperConsumerBase.sol"; -import {VRFV2WrapperInterface} from "../interfaces/VRFV2WrapperInterface.sol"; - -contract VRFV2WrapperLoadTestConsumer is VRFV2WrapperConsumerBase, ConfirmedOwner { - VRFV2WrapperInterface public immutable i_vrfV2Wrapper; - uint256 public s_responseCount; - uint256 public s_requestCount; - uint256 public s_averageFulfillmentInMillions = 0; // in millions for better precision - uint256 public s_slowestFulfillment = 0; - uint256 public s_fastestFulfillment = 999; - uint256 public s_lastRequestId; - // solhint-disable-next-line chainlink-solidity/prefix-storage-variables-with-s-underscore - mapping(uint256 => uint256) internal requestHeights; // requestIds to block number when rand request was made - mapping(uint256 => RequestStatus) public /* requestId */ /* requestStatus */ s_requests; - - event WrappedRequestFulfilled(uint256 requestId, uint256[] randomWords, uint256 payment); - event WrapperRequestMade(uint256 indexed requestId, uint256 paid); - - struct RequestStatus { - uint256 paid; - bool fulfilled; - uint256[] randomWords; - uint256 requestTimestamp; - uint256 fulfilmentTimestamp; - uint256 requestBlockNumber; - uint256 fulfilmentBlockNumber; - } - - constructor( - address _link, - address _vrfV2Wrapper - ) ConfirmedOwner(msg.sender) VRFV2WrapperConsumerBase(_link, _vrfV2Wrapper) { - i_vrfV2Wrapper = VRFV2WrapperInterface(_vrfV2Wrapper); - } - - function makeRequests( - uint32 _callbackGasLimit, - uint16 _requestConfirmations, - uint32 _numWords, - uint16 _requestCount - ) external { - for (uint16 i = 0; i < _requestCount; i++) { - uint256 requestId = requestRandomness(_callbackGasLimit, _requestConfirmations, _numWords); - s_lastRequestId = requestId; - uint256 requestBlockNumber = ChainSpecificUtil._getBlockNumber(); - uint256 paid = VRF_V2_WRAPPER.calculateRequestPrice(_callbackGasLimit); - s_requests[requestId] = RequestStatus({ - paid: paid, - fulfilled: false, - randomWords: new uint256[](0), - requestTimestamp: block.timestamp, - fulfilmentTimestamp: 0, - requestBlockNumber: requestBlockNumber, - fulfilmentBlockNumber: 0 - }); - s_requestCount++; - requestHeights[requestId] = requestBlockNumber; - emit WrapperRequestMade(requestId, paid); - } - } - - function fulfillRandomWords( - uint256 _requestId, - uint256[] memory _randomWords - ) internal override { - // solhint-disable-next-line gas-custom-errors - require(s_requests[_requestId].paid > 0, "request not found"); - uint256 fulfilmentBlockNumber = ChainSpecificUtil._getBlockNumber(); - uint256 requestDelay = fulfilmentBlockNumber - requestHeights[_requestId]; - uint256 requestDelayInMillions = requestDelay * 1_000_000; - - if (requestDelay > s_slowestFulfillment) { - s_slowestFulfillment = requestDelay; - } - if (requestDelay < s_fastestFulfillment) { - s_fastestFulfillment = requestDelay; - } - s_averageFulfillmentInMillions = s_responseCount > 0 - ? (s_averageFulfillmentInMillions * s_responseCount + requestDelayInMillions) / (s_responseCount + 1) - : requestDelayInMillions; - - s_responseCount++; - s_requests[_requestId].fulfilled = true; - s_requests[_requestId].randomWords = _randomWords; - s_requests[_requestId].fulfilmentTimestamp = block.timestamp; - s_requests[_requestId].fulfilmentBlockNumber = fulfilmentBlockNumber; - - emit WrappedRequestFulfilled(_requestId, _randomWords, s_requests[_requestId].paid); - } - - function getRequestStatus( - uint256 _requestId - ) - external - view - returns ( - uint256 paid, - bool fulfilled, - uint256[] memory randomWords, - uint256 requestTimestamp, - uint256 fulfilmentTimestamp, - uint256 requestBlockNumber, - uint256 fulfilmentBlockNumber - ) - { - // solhint-disable-next-line gas-custom-errors - require(s_requests[_requestId].paid > 0, "request not found"); - RequestStatus memory request = s_requests[_requestId]; - return ( - request.paid, - request.fulfilled, - request.randomWords, - request.requestTimestamp, - request.fulfilmentTimestamp, - request.requestBlockNumber, - request.fulfilmentBlockNumber - ); - } - - /// @notice withdrawLink withdraws the amount specified in amount to the owner - /// @param amount the amount to withdraw, in juels - function withdrawLink( - uint256 amount - ) external onlyOwner { - LINK.transfer(owner(), amount); - } - - function reset() external { - s_averageFulfillmentInMillions = 0; - s_slowestFulfillment = 0; - s_fastestFulfillment = 999; - s_requestCount = 0; - s_responseCount = 0; - } - - receive() external payable {} -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperOutOfGasConsumerExample.sol b/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperOutOfGasConsumerExample.sol deleted file mode 100644 index 1649f896c1..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperOutOfGasConsumerExample.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.6; - -import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol"; -import {VRFV2WrapperConsumerBase} from "../VRFV2WrapperConsumerBase.sol"; - -contract VRFV2WrapperOutOfGasConsumerExample is VRFV2WrapperConsumerBase, ConfirmedOwner { - constructor( - address _link, - address _vrfV2Wrapper - ) ConfirmedOwner(msg.sender) VRFV2WrapperConsumerBase(_link, _vrfV2Wrapper) {} - - function makeRequest( - uint32 _callbackGasLimit, - uint16 _requestConfirmations, - uint32 _numWords - ) external onlyOwner returns (uint256 requestId) { - return requestRandomness(_callbackGasLimit, _requestConfirmations, _numWords); - } - - function fulfillRandomWords( - uint256, - /* _requestId */ - uint256[] memory /* _randomWords */ - ) internal view override { - while (gasleft() > 0) {} - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperRevertingConsumerExample.sol b/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperRevertingConsumerExample.sol deleted file mode 100644 index 19f5315029..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperRevertingConsumerExample.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.6; - -import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol"; -import {VRFV2WrapperConsumerBase} from "../VRFV2WrapperConsumerBase.sol"; - -contract VRFV2WrapperRevertingConsumerExample is VRFV2WrapperConsumerBase, ConfirmedOwner { - constructor( - address _link, - address _vrfV2Wrapper - ) ConfirmedOwner(msg.sender) VRFV2WrapperConsumerBase(_link, _vrfV2Wrapper) {} - - function makeRequest( - uint32 _callbackGasLimit, - uint16 _requestConfirmations, - uint32 _numWords - ) external onlyOwner returns (uint256 requestId) { - return requestRandomness(_callbackGasLimit, _requestConfirmations, _numWords); - } - - function fulfillRandomWords( - uint256, - /* _requestId */ - uint256[] memory /* _randomWords */ - ) internal pure override { - revert("reverting example"); - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperUnderFundingConsumer.sol b/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperUnderFundingConsumer.sol deleted file mode 100644 index 9e2971a001..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFV2WrapperUnderFundingConsumer.sol +++ /dev/null @@ -1,32 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {ConfirmedOwner} from "../../shared/access/ConfirmedOwner.sol"; -import {LinkTokenInterface} from "../../shared/interfaces/LinkTokenInterface.sol"; -import {VRFV2WrapperInterface} from "../interfaces/VRFV2WrapperInterface.sol"; - -contract VRFV2WrapperUnderFundingConsumer is ConfirmedOwner { - LinkTokenInterface internal immutable LINK; - VRFV2WrapperInterface internal immutable VRF_V2_WRAPPER; - - constructor( - address _link, - address _vrfV2Wrapper - ) ConfirmedOwner(msg.sender) { - LINK = LinkTokenInterface(_link); - VRF_V2_WRAPPER = VRFV2WrapperInterface(_vrfV2Wrapper); - } - - function makeRequest( - uint32 _callbackGasLimit, - uint16 _requestConfirmations, - uint32 _numWords - ) external onlyOwner { - LINK.transferAndCall( - address(VRF_V2_WRAPPER), - // Pay less than the needed amount - VRF_V2_WRAPPER.calculateRequestPrice(_callbackGasLimit) - 1, - abi.encode(_callbackGasLimit, _requestConfirmations, _numWords) - ); - } -} diff --git a/contracts/src/v0.8/vrf/testhelpers/VRFv2Consumer.sol b/contracts/src/v0.8/vrf/testhelpers/VRFv2Consumer.sol deleted file mode 100644 index 4be4ecb37f..0000000000 --- a/contracts/src/v0.8/vrf/testhelpers/VRFv2Consumer.sol +++ /dev/null @@ -1,71 +0,0 @@ -// SPDX-License-Identifier: MIT -// An example of a consumer contract that relies on a subscription for funding. -pragma solidity ^0.8.6; - -import "../../shared/access/ConfirmedOwner.sol"; -import "../VRFConsumerBaseV2.sol"; -import "../interfaces/VRFCoordinatorV2Interface.sol"; - -/** - * THIS IS AN EXAMPLE CONTRACT THAT USES HARDCODED VALUES FOR CLARITY. - * THIS IS AN EXAMPLE CONTRACT THAT USES UN-AUDITED CODE. - * DO NOT USE THIS CODE IN PRODUCTION. - */ -contract VRFv2Consumer is VRFConsumerBaseV2, ConfirmedOwner { - event RequestSent(uint256 requestId, uint32 numWords); - event RequestFulfilled(uint256 requestId, uint256[] randomWords); - - struct RequestStatus { - bool fulfilled; // whether the request has been successfully fulfilled - bool exists; // whether a requestId exists - uint256[] randomWords; - } - - mapping(uint256 => RequestStatus) public s_requests; /* requestId --> requestStatus */ - VRFCoordinatorV2Interface COORDINATOR; - - // past requests Id. - uint256[] public requestIds; - uint256 public lastRequestId; - - constructor( - address vrfCoordinator - ) VRFConsumerBaseV2(vrfCoordinator) ConfirmedOwner(msg.sender) { - COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); - } - - // Assumes the subscription is funded sufficiently. - function requestRandomWords( - uint64 subId, - uint32 callbackGasLimit, - uint16 requestConfirmations, - uint32 numWords, - bytes32 keyHash - ) external onlyOwner returns (uint256 requestId) { - // Will revert if subscription is not set and funded. - requestId = COORDINATOR.requestRandomWords(keyHash, subId, requestConfirmations, callbackGasLimit, numWords); - s_requests[requestId] = RequestStatus({randomWords: new uint256[](0), exists: true, fulfilled: false}); - requestIds.push(requestId); - lastRequestId = requestId; - emit RequestSent(requestId, numWords); - return requestId; - } - - function fulfillRandomWords( - uint256 _requestId, - uint256[] memory _randomWords - ) internal override { - require(s_requests[_requestId].exists, "request not found"); - s_requests[_requestId].fulfilled = true; - s_requests[_requestId].randomWords = _randomWords; - emit RequestFulfilled(_requestId, _randomWords); - } - - function getRequestStatus( - uint256 _requestId - ) external view returns (bool fulfilled, uint256[] memory randomWords) { - require(s_requests[_requestId].exists, "request not found"); - RequestStatus memory request = s_requests[_requestId]; - return (request.fulfilled, request.randomWords); - } -} diff --git a/gethwrappers/generation/generated-wrapper-dependency-versions-do-not-edit.txt b/gethwrappers/generation/generated-wrapper-dependency-versions-do-not-edit.txt index fa50734c68..b08fed4a9f 100644 --- a/gethwrappers/generation/generated-wrapper-dependency-versions-do-not-edit.txt +++ b/gethwrappers/generation/generated-wrapper-dependency-versions-do-not-edit.txt @@ -1,50 +1,29 @@ GETH_VERSION: 1.17.4 batch_blockhash_store: ../contracts/solc/vrf/BatchBlockhashStore/BatchBlockhashStore.sol/BatchBlockhashStore.abi.json ../contracts/solc/vrf/BatchBlockhashStore/BatchBlockhashStore.sol/BatchBlockhashStore.bin feb3b78e67451b3ea81e294e16e4be4209945a671064072f599447f134d4bbe8 -batch_vrf_coordinator_v2: ../contracts/solc/vrf/BatchVRFCoordinatorV2/BatchVRFCoordinatorV2.sol/BatchVRFCoordinatorV2.abi.json ../contracts/solc/vrf/BatchVRFCoordinatorV2/BatchVRFCoordinatorV2.sol/BatchVRFCoordinatorV2.bin 45642c82bf308a8478aaa410be2b631dcb64bcb01bd2d83590d4ab8336dd1d96 batch_vrf_coordinator_v2plus: ../contracts/solc/vrf/BatchVRFCoordinatorV2Plus/BatchVRFCoordinatorV2Plus.sol/BatchVRFCoordinatorV2Plus.abi.json ../contracts/solc/vrf/BatchVRFCoordinatorV2Plus/BatchVRFCoordinatorV2Plus.sol/BatchVRFCoordinatorV2Plus.bin 45115a5a1d8f4044647e57df82c7e48293054051ffd82dd98b95b340d4a1491e blockhash_store: ../contracts/solc/vrf/BlockhashStore/BlockhashStore.sol/BlockhashStore.abi.json ../contracts/solc/vrf/BlockhashStore/BlockhashStore.sol/BlockhashStore.bin ee7c0978f3a5f15d02496e00b541426cf156e5aaf70615c700f35cc810676f45 chain_specific_util_helper: ../contracts/solc/vrf/ChainSpecificUtilHelper/ChainSpecificUtilHelper.sol/ChainSpecificUtilHelper.abi.json ../contracts/solc/vrf/ChainSpecificUtilHelper/ChainSpecificUtilHelper.sol/ChainSpecificUtilHelper.bin b95cd35610e932cc6a104cfa661b010bb58ad34621ad3cb7a4ebb0d5c9023f2d counter: ../contracts/solc/vrf/Counter/Counter.sol/Counter.abi.json ../contracts/solc/vrf/Counter/Counter.sol/Counter.bin 7dea2e58598a5973f8280f3465654254b5fc790598e45be18455e5219f57cc13 -keepers_vrf_consumer: ../contracts/solc/vrf/KeepersVRFConsumer/KeepersVRFConsumer.sol/KeepersVRFConsumer.abi.json ../contracts/solc/vrf/KeepersVRFConsumer/KeepersVRFConsumer.sol/KeepersVRFConsumer.bin 30f65453b33ad618aa04763a19b2f11dc14900e5ac91b5b33f0d7771f047b43b solidity_vrf_consumer_interface_v08: ../contracts/solc/vrf/VRFConsumer/VRFConsumer.sol/VRFConsumer.abi.json ../contracts/solc/vrf/VRFConsumer/VRFConsumer.sol/VRFConsumer.bin 64a3ef440e9c9b50c47e7add798524903de9de2a9be02979207fcd643729cca5 solidity_vrf_request_id_v08: ../contracts/solc/vrf/VRFRequestIDBaseTestHelper/VRFRequestIDBaseTestHelper.sol/VRFRequestIDBaseTestHelper.abi.json ../contracts/solc/vrf/VRFRequestIDBaseTestHelper/VRFRequestIDBaseTestHelper.sol/VRFRequestIDBaseTestHelper.bin 8a2eed78470b1e1334d8f84c67f6b1bd9acaeec23f4373d3e6f2486b7891fd4b solidity_vrf_v08_verifier_wrapper: ../contracts/solc/vrf/VRFTestHelper/VRFTestHelper.sol/VRFTestHelper.abi.json ../contracts/solc/vrf/VRFTestHelper/VRFTestHelper.sol/VRFTestHelper.bin 3d447d0b61f87dedf157e9426c609c7e26a21dd4b9a0aa858cf7e5256a3dfba4 trusted_blockhash_store: ../contracts/solc/vrf/TrustedBlockhashStore/TrustedBlockhashStore.sol/TrustedBlockhashStore.abi.json ../contracts/solc/vrf/TrustedBlockhashStore/TrustedBlockhashStore.sol/TrustedBlockhashStore.bin e8242e42b9dea837974f72dc4426a8820a7aaf9c85eac2b7def76fd328c7a532 -vrf_consumer_v2: ../contracts/solc/vrf/VRFConsumerV2/VRFConsumerV2.sol/VRFConsumerV2.abi.json ../contracts/solc/vrf/VRFConsumerV2/VRFConsumerV2.sol/VRFConsumerV2.bin c1a4afe9e7f37e804ce8d3e2989acfaa2fc2c8a3892370f596aa1f7e8edd767f vrf_consumer_v2_plus_upgradeable_example: ../contracts/solc/vrf/VRFConsumerV2PlusUpgradeableExample/VRFConsumerV2PlusUpgradeableExample.sol/VRFConsumerV2PlusUpgradeableExample.abi.json ../contracts/solc/vrf/VRFConsumerV2PlusUpgradeableExample/VRFConsumerV2PlusUpgradeableExample.sol/VRFConsumerV2PlusUpgradeableExample.bin 2e6f918e0efff80daba41685a210b6c6fc652fc656135ca8ad1753883a7c0538 -vrf_consumer_v2_upgradeable_example: ../contracts/solc/vrf/VRFConsumerV2UpgradeableExample/VRFConsumerV2UpgradeableExample.sol/VRFConsumerV2UpgradeableExample.abi.json ../contracts/solc/vrf/VRFConsumerV2UpgradeableExample/VRFConsumerV2UpgradeableExample.sol/VRFConsumerV2UpgradeableExample.bin edf3edf653939cd1f86db5f9aa1e11a590e9aab46e4ece880a0189b12f17bfac vrf_coordinator_mock: ../contracts/solc/vrf/VRFCoordinatorMock/VRFCoordinatorMock.sol/VRFCoordinatorMock.abi.json ../contracts/solc/vrf/VRFCoordinatorMock/VRFCoordinatorMock.sol/VRFCoordinatorMock.bin 32f842707155d24aeb8247d457639e73910980eb098b743b9008a92b61f354b6 -vrf_coordinator_test_v2: ../contracts/solc/vrf/VRFCoordinatorTestV2/VRFCoordinatorTestV2.sol/VRFCoordinatorTestV2.abi.json ../contracts/solc/vrf/VRFCoordinatorTestV2/VRFCoordinatorTestV2.sol/VRFCoordinatorTestV2.bin 7ed0ae0e734ad0070d96f7a1be3d786780065bd5e1624fe0ee61f12da84f2d22 vrf_coordinator_test_v2_5: ../contracts/solc/vrf/VRFCoordinatorTestV2_5/VRFCoordinatorTestV2_5.sol/VRFCoordinatorTestV2_5.abi.json ../contracts/solc/vrf/VRFCoordinatorTestV2_5/VRFCoordinatorTestV2_5.sol/VRFCoordinatorTestV2_5.bin 3a33a3bccebd796812356e6aea56bd1a5bc2683343ead8981331ad700d81870d -vrf_coordinator_v2: ../contracts/solc/vrf/VRFCoordinatorV2/VRFCoordinatorV2.sol/VRFCoordinatorV2.abi.json ../contracts/solc/vrf/VRFCoordinatorV2/VRFCoordinatorV2.sol/VRFCoordinatorV2.bin 3e49a572c2b0930e8515a822e53336d6c8b9017152db78d5826729b5b02b19be vrf_coordinator_v2_5: ../contracts/solc/vrf/VRFCoordinatorV2_5/VRFCoordinatorV2_5.sol/VRFCoordinatorV2_5.abi.json ../contracts/solc/vrf/VRFCoordinatorV2_5/VRFCoordinatorV2_5.sol/VRFCoordinatorV2_5.bin cd7699f7f1acbb1d8f50890b80ca399d3affce267592352c638a4aa2b22c6a62 vrf_coordinator_v2_5_arbitrum: ../contracts/solc/vrf/VRFCoordinatorV2_5_Arbitrum/VRFCoordinatorV2_5_Arbitrum.sol/VRFCoordinatorV2_5_Arbitrum.abi.json ../contracts/solc/vrf/VRFCoordinatorV2_5_Arbitrum/VRFCoordinatorV2_5_Arbitrum.sol/VRFCoordinatorV2_5_Arbitrum.bin ad7565fe7e449c647f06a36db16e6dc914e19e173513e886878efe1eed936e2a vrf_coordinator_v2_5_optimism: ../contracts/solc/vrf/VRFCoordinatorV2_5_Optimism/VRFCoordinatorV2_5_Optimism.sol/VRFCoordinatorV2_5_Optimism.abi.json ../contracts/solc/vrf/VRFCoordinatorV2_5_Optimism/VRFCoordinatorV2_5_Optimism.sol/VRFCoordinatorV2_5_Optimism.bin 99d5d33e8ae720b9cc76a25b442222a09ee590ef54c15e838d3f6072ee7d4bdf vrf_coordinator_v2_plus_v2_example: ../contracts/solc/vrf/VRFCoordinatorV2Plus_V2Example/VRFCoordinatorV2Plus_V2Example.sol/VRFCoordinatorV2Plus_V2Example.abi.json ../contracts/solc/vrf/VRFCoordinatorV2Plus_V2Example/VRFCoordinatorV2Plus_V2Example.sol/VRFCoordinatorV2Plus_V2Example.bin 3ad7f53fb91ee30e184d6b5bcc05603f9ab4c5912cc5a93374b7f69a89c55d5c vrf_coordinator_v2plus_interface: ../contracts/solc/vrf/IVRFCoordinatorV2PlusInternal/IVRFCoordinatorV2PlusInternal.sol/IVRFCoordinatorV2PlusInternal.abi.json ../contracts/solc/vrf/IVRFCoordinatorV2PlusInternal/IVRFCoordinatorV2PlusInternal.sol/IVRFCoordinatorV2PlusInternal.bin 148fad1c48ad41480728773d65311ed45f4c12199c8b80da44228480ed383775 -vrf_external_sub_owner_example: ../contracts/solc/vrf/VRFExternalSubOwnerExample/VRFExternalSubOwnerExample.sol/VRFExternalSubOwnerExample.abi.json ../contracts/solc/vrf/VRFExternalSubOwnerExample/VRFExternalSubOwnerExample.sol/VRFExternalSubOwnerExample.bin 0e907db3188c6cf2e4bd0db6a8b764eaf3bd698648007d18f2fc26ff0d9d2896 -vrf_load_test_external_sub_owner: ../contracts/solc/vrf/VRFLoadTestExternalSubOwner/VRFLoadTestExternalSubOwner.sol/VRFLoadTestExternalSubOwner.abi.json ../contracts/solc/vrf/VRFLoadTestExternalSubOwner/VRFLoadTestExternalSubOwner.sol/VRFLoadTestExternalSubOwner.bin 1a17930fbf29e0513a6e0327fe1c27da43735516c86492f90c41d8aa37531d0d vrf_load_test_ownerless_consumer: ../contracts/solc/vrf/VRFLoadTestOwnerlessConsumer/VRFLoadTestOwnerlessConsumer.sol/VRFLoadTestOwnerlessConsumer.abi.json ../contracts/solc/vrf/VRFLoadTestOwnerlessConsumer/VRFLoadTestOwnerlessConsumer.sol/VRFLoadTestOwnerlessConsumer.bin faf88c5847f16217fe07ed7ea998b1cd1ff52f09c16bb32afdeba7fdd3b423f0 -vrf_load_test_with_metrics: ../contracts/solc/vrf/VRFV2LoadTestWithMetrics/VRFV2LoadTestWithMetrics.sol/VRFV2LoadTestWithMetrics.abi.json ../contracts/solc/vrf/VRFV2LoadTestWithMetrics/VRFV2LoadTestWithMetrics.sol/VRFV2LoadTestWithMetrics.bin 3fb5ca57d688b57d8bac0b67a90cc6026bc009e6159fdf2e899da89ba43e92a0 -vrf_malicious_consumer_v2: ../contracts/solc/vrf/VRFMaliciousConsumerV2/VRFMaliciousConsumerV2.sol/VRFMaliciousConsumerV2.abi.json ../contracts/solc/vrf/VRFMaliciousConsumerV2/VRFMaliciousConsumerV2.sol/VRFMaliciousConsumerV2.bin 89fd55375a7df9eea9902f9417e44d1c1be39b38f73fcdb074d78e698d697277 vrf_malicious_consumer_v2_plus: ../contracts/solc/vrf/VRFMaliciousConsumerV2Plus/VRFMaliciousConsumerV2Plus.sol/VRFMaliciousConsumerV2Plus.abi.json ../contracts/solc/vrf/VRFMaliciousConsumerV2Plus/VRFMaliciousConsumerV2Plus.sol/VRFMaliciousConsumerV2Plus.bin d0bde5ad985007485016cf5cd7daeeb895891109956e952fcbed1d9dca03cd49 vrf_mock_ethlink_aggregator: ../contracts/solc/vrf/VRFMockETHLINKAggregator/VRFMockETHLINKAggregator.sol/VRFMockETHLINKAggregator.abi.json ../contracts/solc/vrf/VRFMockETHLINKAggregator/VRFMockETHLINKAggregator.sol/VRFMockETHLINKAggregator.bin 055efe5b3fc53d35c587e4f43162123d8877b2a783329ce0861bbc12d439ec17 -vrf_owner: ../contracts/solc/vrf/VRFOwner/VRFOwner.sol/VRFOwner.abi.json ../contracts/solc/vrf/VRFOwner/VRFOwner.sol/VRFOwner.bin e9483e9e30ffed3babae6cea36f272f6859e506c0248107253ddef073763e7c7 -vrf_owner_test_consumer: ../contracts/solc/vrf/VRFV2OwnerTestConsumer/VRFV2OwnerTestConsumer.sol/VRFV2OwnerTestConsumer.abi.json ../contracts/solc/vrf/VRFV2OwnerTestConsumer/VRFV2OwnerTestConsumer.sol/VRFV2OwnerTestConsumer.bin a2feb4e1c714e4c53ba51941b5e787e211bbed8fa85788b2e012a7373a043cd7 vrf_ownerless_consumer_example: ../contracts/solc/vrf/VRFOwnerlessConsumerExample/VRFOwnerlessConsumerExample.sol/VRFOwnerlessConsumerExample.abi.json ../contracts/solc/vrf/VRFOwnerlessConsumerExample/VRFOwnerlessConsumerExample.sol/VRFOwnerlessConsumerExample.bin e739467fd1a3e6d8740a490cb90034909c5cc043d558a1160fdb6576e3eaad71 -vrf_single_consumer_example: ../contracts/solc/vrf/VRFSingleConsumerExample/VRFSingleConsumerExample.sol/VRFSingleConsumerExample.abi.json ../contracts/solc/vrf/VRFSingleConsumerExample/VRFSingleConsumerExample.sol/VRFSingleConsumerExample.bin 217702a2c6d4d555d924dabbea6a3abfff9b076ed024f06c27ae012bc4f783e8 -vrf_v2_consumer_wrapper: ../contracts/solc/vrf/VRFv2Consumer/VRFv2Consumer.sol/VRFv2Consumer.abi.json ../contracts/solc/vrf/VRFv2Consumer/VRFv2Consumer.sol/VRFv2Consumer.bin 14eae51056941cb3a457348eaf47b60c9b1b979790ea206bc9d0a740f7531f47 vrf_v2plus_load_test_with_metrics: ../contracts/solc/vrf/VRFV2PlusLoadTestWithMetrics/VRFV2PlusLoadTestWithMetrics.sol/VRFV2PlusLoadTestWithMetrics.abi.json ../contracts/solc/vrf/VRFV2PlusLoadTestWithMetrics/VRFV2PlusLoadTestWithMetrics.sol/VRFV2PlusLoadTestWithMetrics.bin 02a8db1f3d08a8f268819e6cf8f4515a8b693753ec295324255044f99c8deb81 vrf_v2plus_single_consumer: ../contracts/solc/vrf/VRFV2PlusSingleConsumerExample/VRFV2PlusSingleConsumerExample.sol/VRFV2PlusSingleConsumerExample.abi.json ../contracts/solc/vrf/VRFV2PlusSingleConsumerExample/VRFV2PlusSingleConsumerExample.sol/VRFV2PlusSingleConsumerExample.bin 978431537b18a19c24040a96370a2b16109010b8d4097f9c0a6765073bb97ad9 vrf_v2plus_sub_owner: ../contracts/solc/vrf/VRFV2PlusExternalSubOwnerExample/VRFV2PlusExternalSubOwnerExample.sol/VRFV2PlusExternalSubOwnerExample.abi.json ../contracts/solc/vrf/VRFV2PlusExternalSubOwnerExample/VRFV2PlusExternalSubOwnerExample.sol/VRFV2PlusExternalSubOwnerExample.bin 1c0cffa5f8060d65603fe675d3fe86c3c8fc8cc3fdd280c6c3440bed4a430cf9 vrf_v2plus_upgraded_version: ../contracts/solc/vrf/VRFCoordinatorV2PlusUpgradedVersion/VRFCoordinatorV2PlusUpgradedVersion.sol/VRFCoordinatorV2PlusUpgradedVersion.abi.json ../contracts/solc/vrf/VRFCoordinatorV2PlusUpgradedVersion/VRFCoordinatorV2PlusUpgradedVersion.sol/VRFCoordinatorV2PlusUpgradedVersion.bin 629d05e4182bcc22547a25415169b75a019524032aa76b971b131ec39e827864 -vrfv2_proxy_admin: ../contracts/solc/vrf/VRFV2ProxyAdmin/VRFV2ProxyAdmin.sol/VRFV2ProxyAdmin.abi.json ../contracts/solc/vrf/VRFV2ProxyAdmin/VRFV2ProxyAdmin.sol/VRFV2ProxyAdmin.bin f3e7f3f94e7567ef998db8da155c257096f226588574a32564a5ac4b9ed02ff6 -vrfv2_reverting_example: ../contracts/solc/vrf/VRFV2RevertingExample/VRFV2RevertingExample.sol/VRFV2RevertingExample.abi.json ../contracts/solc/vrf/VRFV2RevertingExample/VRFV2RevertingExample.sol/VRFV2RevertingExample.bin 7b7d15a87ecf55d62a7a41441498617d41e87112c684b55ae66c4cad91ff0bad -vrfv2_transparent_upgradeable_proxy: ../contracts/solc/vrf/VRFV2TransparentUpgradeableProxy/VRFV2TransparentUpgradeableProxy.sol/VRFV2TransparentUpgradeableProxy.abi.json ../contracts/solc/vrf/VRFV2TransparentUpgradeableProxy/VRFV2TransparentUpgradeableProxy.sol/VRFV2TransparentUpgradeableProxy.bin d378bc6fa1b15b08f4e1d674b52d05892835914296ffab03cce992b27d3042fe -vrfv2_wrapper: ../contracts/solc/vrf/VRFV2Wrapper/VRFV2Wrapper.sol/VRFV2Wrapper.abi.json ../contracts/solc/vrf/VRFV2Wrapper/VRFV2Wrapper.sol/VRFV2Wrapper.bin ce5288af714754d0f924ce8610e85e003c31b182198677052ffab85c7b30a008 -vrfv2_wrapper_consumer_example: ../contracts/solc/vrf/VRFV2WrapperConsumerExample/VRFV2WrapperConsumerExample.sol/VRFV2WrapperConsumerExample.abi.json ../contracts/solc/vrf/VRFV2WrapperConsumerExample/VRFV2WrapperConsumerExample.sol/VRFV2WrapperConsumerExample.bin 3605006ddcd3e4b8d7851c89ab69c2551b2ee2fc6be2d2808da98a01d4ec7fc3 -vrfv2_wrapper_interface: ../contracts/solc/vrf/VRFV2WrapperInterface/VRFV2WrapperInterface.sol/VRFV2WrapperInterface.abi.json ../contracts/solc/vrf/VRFV2WrapperInterface/VRFV2WrapperInterface.sol/VRFV2WrapperInterface.bin 8e3478b6c72ed2caa47ec1cdb4edb97386e2cce18e589d9613c793673a587de6 -vrfv2_wrapper_load_test_consumer: ../contracts/solc/vrf/VRFV2WrapperLoadTestConsumer/VRFV2WrapperLoadTestConsumer.sol/VRFV2WrapperLoadTestConsumer.abi.json ../contracts/solc/vrf/VRFV2WrapperLoadTestConsumer/VRFV2WrapperLoadTestConsumer.sol/VRFV2WrapperLoadTestConsumer.bin 2eb5cd0a4ec2d12ad154af536d84147ea665423d06a38407dcfb0e26188c2ce5 vrfv2plus_client: ../contracts/solc/vrf/VRFV2PlusClient/VRFV2PlusClient.sol/VRFV2PlusClient.abi.json ../contracts/solc/vrf/VRFV2PlusClient/VRFV2PlusClient.sol/VRFV2PlusClient.bin b7207a82a9a6065664aae2f46d8c48fbf27ca39f1daf427afc33e45173e9e314 vrfv2plus_consumer_example: ../contracts/solc/vrf/VRFV2PlusConsumerExample/VRFV2PlusConsumerExample.sol/VRFV2PlusConsumerExample.abi.json ../contracts/solc/vrf/VRFV2PlusConsumerExample/VRFV2PlusConsumerExample.sol/VRFV2PlusConsumerExample.bin 4e7b4da659c9a1fcf0dc7e489a5377f0705e38404c020c43c7d62ca97ec7ad91 vrfv2plus_malicious_migrator: ../contracts/solc/vrf/VRFV2PlusMaliciousMigrator/VRFV2PlusMaliciousMigrator.sol/VRFV2PlusMaliciousMigrator.abi.json ../contracts/solc/vrf/VRFV2PlusMaliciousMigrator/VRFV2PlusMaliciousMigrator.sol/VRFV2PlusMaliciousMigrator.bin 9bf08e322c84237fab631381d2c1fc9b671e58bbb62e403da7e257054bb0efb7 diff --git a/gethwrappers/go_generate_vrf.go b/gethwrappers/go_generate_vrf.go index 166f02f6da..ec51967db5 100644 --- a/gethwrappers/go_generate_vrf.go +++ b/gethwrappers/go_generate_vrf.go @@ -7,38 +7,12 @@ package gethwrappers //go:generate go run ./generation/wrap.go vrf VRFRequestIDBaseTestHelper solidity_vrf_request_id_v08 //go:generate go run ./generation/wrap.go vrf VRFOwnerlessConsumerExample vrf_ownerless_consumer_example //go:generate go run ./generation/wrap.go vrf VRFLoadTestOwnerlessConsumer vrf_load_test_ownerless_consumer -//go:generate go run ./generation/wrap.go vrf VRFLoadTestExternalSubOwner vrf_load_test_external_sub_owner -//go:generate go run ./generation/wrap.go vrf VRFV2LoadTestWithMetrics vrf_load_test_with_metrics -//go:generate go run ./generation/wrap.go vrf VRFV2OwnerTestConsumer vrf_owner_test_consumer -//go:generate go run ./generation/wrap.go vrf VRFv2Consumer vrf_v2_consumer_wrapper //go:generate go run ./generation/wrap.go vrf Counter counter -// VRF V2 -//go:generate go run ./generation/wrap.go vrf BatchVRFCoordinatorV2 batch_vrf_coordinator_v2 -//go:generate go run ./generation/wrap.go vrf VRFOwner vrf_owner -//go:generate go run ./generation/wrap.go vrf VRFCoordinatorV2 vrf_coordinator_v2 -//go:generate go run ./generation/wrap.go vrf VRFConsumerV2 vrf_consumer_v2 -//go:generate go run ./generation/wrap.go vrf VRFMaliciousConsumerV2 vrf_malicious_consumer_v2 //go:generate go run ./generation/wrap.go vrf VRFTestHelper solidity_vrf_v08_verifier_wrapper -//go:generate go run ./generation/wrap.go vrf VRFSingleConsumerExample vrf_single_consumer_example -//go:generate go run ./generation/wrap.go vrf VRFExternalSubOwnerExample vrf_external_sub_owner_example -//go:generate go run ./generation/wrap.go vrf VRFV2RevertingExample vrfv2_reverting_example -//go:generate go run ./generation/wrap.go vrf VRFConsumerV2UpgradeableExample vrf_consumer_v2_upgradeable_example -//go:generate go run ./generation/wrap.go vrf VRFV2TransparentUpgradeableProxy vrfv2_transparent_upgradeable_proxy -//go:generate go run ./generation/wrap.go vrf VRFV2ProxyAdmin vrfv2_proxy_admin //go:generate go run ./generation/wrap.go vrf ChainSpecificUtilHelper chain_specific_util_helper -//go:generate go run ./generation/wrap.go vrf VRFCoordinatorTestV2 vrf_coordinator_test_v2 //go:generate go run ./generation/wrap.go vrf VRFMockETHLINKAggregator vrf_mock_ethlink_aggregator -// VRF V2 Wrapper -//go:generate go run ./generation/wrap.go vrf VRFV2Wrapper vrfv2_wrapper -//go:generate go run ./generation/wrap.go vrf VRFV2WrapperInterface vrfv2_wrapper_interface -//go:generate go run ./generation/wrap.go vrf VRFV2WrapperConsumerExample vrfv2_wrapper_consumer_example -//go:generate go run ./generation/wrap.go vrf VRFV2WrapperLoadTestConsumer vrfv2_wrapper_load_test_consumer - -// Keepers X VRF v2 -//go:generate go run ./generation/wrap.go vrf KeepersVRFConsumer keepers_vrf_consumer - // VRF V2Plus //go:generate go run ./generation/wrap.go vrf IVRFCoordinatorV2PlusInternal vrf_coordinator_v2plus_interface //go:generate go run ./generation/wrap.go vrf BatchVRFCoordinatorV2Plus batch_vrf_coordinator_v2plus From bfcd20c618af9a0763e85d5c0ef0a03468bdd0b3 Mon Sep 17 00:00:00 2001 From: Iva Brajer Date: Wed, 28 Oct 2026 21:09:11 +0100 Subject: [PATCH 2/5] Remove stale IAuthorizedReceiver entry from compile script The contract was deleted in this branch but its compile entry was missed, causing forge to fail with 'No source files found' and the wrapper generation verification to panic. Co-Authored-By: Claude Code --- contracts/scripts/native_solc_compile_all_vrf | 3 --- 1 file changed, 3 deletions(-) diff --git a/contracts/scripts/native_solc_compile_all_vrf b/contracts/scripts/native_solc_compile_all_vrf index 86efe75ddd..ee4e55c509 100755 --- a/contracts/scripts/native_solc_compile_all_vrf +++ b/contracts/scripts/native_solc_compile_all_vrf @@ -48,9 +48,6 @@ compileContract vrf-compile testhelpers/VRFLoadTestOwnerlessConsumer compileContract vrf-compile testhelpers/VRFMockETHLINKAggregator compileContract vrf-compile testhelpers/Counter -# Helper contracts -compileContract vrf-compile interfaces/IAuthorizedReceiver - # VRF V2 Plus compileContract vrfv2plus-compile interfaces/IVRFCoordinatorV2PlusInternal compileContract vrfv2plus-compile testhelpers/VRFV2PlusConsumerExample From ef0a15c170aa005ef0b9a6e15fc78e96e2b57424 Mon Sep 17 00:00:00 2001 From: Iva Brajer Date: Wed, 28 Oct 2026 21:18:54 +0100 Subject: [PATCH 3/5] Update GETH_VERSION to 1.17.4 in CRE gobindings versions files Wrapper regeneration updates these files to match the go-ethereum version in contracts/cre/gobindings/go.mod (bumped to v1.17.4 earlier in this PR), so they must be committed for the wrapper validation to pass. Co-Authored-By: Claude Code --- .../generated-wrapper-dependency-versions-do-not-edit.txt | 2 +- .../generated-wrapper-dependency-versions-do-not-edit.txt | 2 +- .../generated-wrapper-dependency-versions-do-not-edit.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contracts/cre/gobindings/dev/generation/generated-wrapper-dependency-versions-do-not-edit.txt b/contracts/cre/gobindings/dev/generation/generated-wrapper-dependency-versions-do-not-edit.txt index 62460bc8fc..57969ccb70 100644 --- a/contracts/cre/gobindings/dev/generation/generated-wrapper-dependency-versions-do-not-edit.txt +++ b/contracts/cre/gobindings/dev/generation/generated-wrapper-dependency-versions-do-not-edit.txt @@ -1,4 +1,4 @@ -GETH_VERSION: 1.17.3 +GETH_VERSION: 1.17.4 message_emitter: ../../solc/dev/MessageEmitter/MessageEmitter.sol/MessageEmitter.abi.json ../../solc/dev/MessageEmitter/MessageEmitter.sol/MessageEmitter.bin 14234aed0e58dbad3581517107bd851cebddc75892050fc207cbfb12dcdfe695 mock_forwarder: ../../solc/dev/MockKeystoneForwarder/MockKeystoneForwarder.sol/MockKeystoneForwarder.abi.json ../../solc/dev/MockKeystoneForwarder/MockKeystoneForwarder.sol/MockKeystoneForwarder.bin c6c9a6e84780eacc6fd358daab8b5f11b3cddfe47416cc84c18b093ce6a65503 reserve_manager: ../../solc/dev/ReserveManager/ReserveManager.sol/ReserveManager.abi.json ../../solc/dev/ReserveManager/ReserveManager.sol/ReserveManager.bin 113a433c32bf094b3ab25bf8c3ae0eddf2e31e4e525b85924c0688fc48148c75 diff --git a/contracts/cre/gobindings/v1/generation/generated-wrapper-dependency-versions-do-not-edit.txt b/contracts/cre/gobindings/v1/generation/generated-wrapper-dependency-versions-do-not-edit.txt index 621067df8c..fb210736a8 100644 --- a/contracts/cre/gobindings/v1/generation/generated-wrapper-dependency-versions-do-not-edit.txt +++ b/contracts/cre/gobindings/v1/generation/generated-wrapper-dependency-versions-do-not-edit.txt @@ -1,4 +1,4 @@ -GETH_VERSION: 1.17.3 +GETH_VERSION: 1.17.4 balance_reader: ../../solc/v1/BalanceReader/BalanceReader.sol/BalanceReader.abi.json ../../solc/v1/BalanceReader/BalanceReader.sol/BalanceReader.bin a39a8b0ab5c2fbdd3d6dc7208ffa6b777f2d9e0ad0ddd00fdc299e65a782f22b capabilities_registry_wrapper: ../../solc/v1/CapabilitiesRegistry/CapabilitiesRegistry.sol/CapabilitiesRegistry.abi.json ../../solc/v1/CapabilitiesRegistry/CapabilitiesRegistry.sol/CapabilitiesRegistry.bin c5635a7f210b40b64ebcff39a4a816835f3492c029a61a47eae4b138f70dd1e8 feeds_consumer: ../../solc/v1/KeystoneFeedsConsumer/KeystoneFeedsConsumer.sol/KeystoneFeedsConsumer.abi.json ../../solc/v1/KeystoneFeedsConsumer/KeystoneFeedsConsumer.sol/KeystoneFeedsConsumer.bin d91722f385ae2babb6ad31646956e49dd7c7011a2ed7f3d7bfea3fe92794ffa0 diff --git a/contracts/cre/gobindings/v2/generation/generated-wrapper-dependency-versions-do-not-edit.txt b/contracts/cre/gobindings/v2/generation/generated-wrapper-dependency-versions-do-not-edit.txt index aee3227edd..6f1da8de24 100644 --- a/contracts/cre/gobindings/v2/generation/generated-wrapper-dependency-versions-do-not-edit.txt +++ b/contracts/cre/gobindings/v2/generation/generated-wrapper-dependency-versions-do-not-edit.txt @@ -1,3 +1,3 @@ -GETH_VERSION: 1.17.3 +GETH_VERSION: 1.17.4 capabilities_registry_wrapper: ../../solc/v2/CapabilitiesRegistry/CapabilitiesRegistry.sol/CapabilitiesRegistry.abi.json ../../solc/v2/CapabilitiesRegistry/CapabilitiesRegistry.sol/CapabilitiesRegistry.bin 4da4a10c2fa6e7fd049c6b2470d1403df9a4a77f516941cfd2d5f1f067a14d8b workflow_registry_wrapper: ../../solc/v2/WorkflowRegistry/WorkflowRegistry.sol/WorkflowRegistry.abi.json ../../solc/v2/WorkflowRegistry/WorkflowRegistry.sol/WorkflowRegistry.bin 1f970e09e9857f220ff9568d43225223380167eeda2dba0ff03d5ce8fca09681 From fbc7493597f1334215d72a9fef6b88852403ebd9 Mon Sep 17 00:00:00 2001 From: Iva Brajer Date: Wed, 28 Oct 2026 15:22:50 +0100 Subject: [PATCH 4/5] Bump go-ethereum to v1.17.4 in contracts/cre/gobindings The revert of #572 downgraded go-ethereum to v1.17.4 in the root and gethwrappers modules but missed this nested module, causing the wrapper generation to fail with an abigen version mismatch in CI. Same change as in #571. Co-Authored-By: Claude Code --- contracts/cre/gobindings/go.mod | 5 +++-- contracts/cre/gobindings/go.sum | 38 +++++++++++++++++---------------- 2 files changed, 23 insertions(+), 20 deletions(-) diff --git a/contracts/cre/gobindings/go.mod b/contracts/cre/gobindings/go.mod index 5be8d5adf4..2da5fa0d54 100644 --- a/contracts/cre/gobindings/go.mod +++ b/contracts/cre/gobindings/go.mod @@ -3,7 +3,7 @@ module github.com/smartcontractkit/chainlink-evm/contracts/cre/gobindings go 1.25.13 require ( - github.com/ethereum/go-ethereum v1.17.3 + github.com/ethereum/go-ethereum v1.17.4 github.com/smartcontractkit/chainlink-evm/gethwrappers/helpers v0.0.0-20260910153826-57b3ea930843 ) @@ -18,6 +18,7 @@ require ( github.com/deckarep/golang-set/v2 v2.6.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/ethereum/c-kzg-4844/v2 v2.1.6 // indirect + github.com/fjl/jsonw v0.1.0 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect @@ -39,5 +40,5 @@ require ( golang.org/x/exp v0.0.0-20240213143201-ec583247a57a // indirect golang.org/x/sync v0.19.0 // indirect golang.org/x/sys v0.45.0 // indirect - golang.org/x/tools v0.40.0 // indirect + golang.org/x/tools v0.41.0 // indirect ) diff --git a/contracts/cre/gobindings/go.sum b/contracts/cre/gobindings/go.sum index 3a6e161d31..fe2e763108 100644 --- a/contracts/cre/gobindings/go.sum +++ b/contracts/cre/gobindings/go.sum @@ -52,10 +52,12 @@ github.com/ethereum/c-kzg-4844/v2 v2.1.6 h1:xQymkKCT5E2Jiaoqf3v4wsNgjZLY0lRSkZn2 github.com/ethereum/c-kzg-4844/v2 v2.1.6/go.mod h1:8HMkUZ5JRv4hpw/XUrYWSQNAUzhHMg2UDb/U+5m+XNw= github.com/ethereum/go-bigmodexpfix v0.0.0-20250911101455-f9e208c548ab h1:rvv6MJhy07IMfEKuARQ9TKojGqLVNxQajaXEp/BoqSk= github.com/ethereum/go-bigmodexpfix v0.0.0-20250911101455-f9e208c548ab/go.mod h1:IuLm4IsPipXKF7CW5Lzf68PIbZ5yl7FFd74l/E0o9A8= -github.com/ethereum/go-ethereum v1.17.3 h1:Ev/sQHH+UdKZHWjuVzhu2pxhi/sXaPZl23Q+Q5LDd4Q= -github.com/ethereum/go-ethereum v1.17.3/go.mod h1:f2EhRwqewIZkGoQekywI2Y2RZAMTSavLNkD9qItFy1A= +github.com/ethereum/go-ethereum v1.17.4 h1:uA4q+qiLp7QImBsjdRbINu8iX6OEVmj4DPc5/E5Fsxc= +github.com/ethereum/go-ethereum v1.17.4/go.mod h1:qMdgwqqRAen+aT8P7KKQKi0Qt6RzG4cfejVAbCpJgqA= github.com/ferranbt/fastssz v0.1.4 h1:OCDB+dYDEQDvAgtAGnTSidK1Pe2tW3nFV40XyMkTeDY= github.com/ferranbt/fastssz v0.1.4/go.mod h1:Ea3+oeoRGGLGm5shYAeDgu6PGUlcvQhE2fILyD9+tGg= +github.com/fjl/jsonw v0.1.0 h1:V3MyR79fjLpn/+bMgvegdGUIhoJOzjmqWcKDgcOmY1I= +github.com/fjl/jsonw v0.1.0/go.mod h1:2KMLevM6FXEJnfhtk7naXu9vZdVfOma1GlnGdPRlumU= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/gballet/go-libpcsclite v0.0.0-20190607065134-2772fd86a8ff h1:tY80oXqGNY4FhTFhk+o9oFHGINQ/+vhlm8HFzi6znCI= @@ -142,16 +144,14 @@ github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsq github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= github.com/peterh/liner v1.1.1-0.20190123174540-a2c9a5303de7 h1:oYW+YCJ1pachXTQmzR3rNLYGGz4g/UgFcjb28p/viDM= github.com/peterh/liner v1.1.1-0.20190123174540-a2c9a5303de7/go.mod h1:CRroGNssyjTd/qIG2FyxByd2S8JEAZXBl4qUrZf8GS0= -github.com/pion/dtls/v2 v2.2.7 h1:cSUBsETxepsCSFSxC3mc/aDo14qQLMSL+O6IjG28yV8= -github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s= -github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY= -github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms= -github.com/pion/stun/v2 v2.0.0 h1:A5+wXKLAypxQri59+tmQKVs7+l6mMM+3d+eER9ifRU0= -github.com/pion/stun/v2 v2.0.0/go.mod h1:22qRSh08fSEttYUmJZGlriq9+03jtVmXNODgLccj8GQ= -github.com/pion/transport/v2 v2.2.1 h1:7qYnCBlpgSJNYMbLCKuSY9KbQdBFoETvPNETv0y4N7c= -github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g= -github.com/pion/transport/v3 v3.0.1 h1:gDTlPJwROfSfz6QfSi0ZmeCSkFcnWWiiR9ES0ouANiM= -github.com/pion/transport/v3 v3.0.1/go.mod h1:UY7kiITrlMv7/IKgd5eTUcaahZx5oUN3l9SzK5f5xE0= +github.com/pion/dtls/v3 v3.1.2 h1:gqEdOUXLtCGW+afsBLO0LtDD8GnuBBjEy6HRtyofZTc= +github.com/pion/dtls/v3 v3.1.2/go.mod h1:Hw/igcX4pdY69z1Hgv5x7wJFrUkdgHwAn/Q/uo7YHRo= +github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8= +github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so= +github.com/pion/stun/v3 v3.1.2 h1:86IhD8wFn6IDW4b1/0QzoQS+f5PeA8OHHRn8UZW5ErY= +github.com/pion/stun/v3 v3.1.2/go.mod h1:H7gDic7nNwlUL05pbs6T1dtaBehh/KjupxfWw3ZI7cA= +github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o= +github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= @@ -188,6 +188,8 @@ github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+F github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY= github.com/urfave/cli/v2 v2.27.5 h1:WoHEJLdsXr6dDWoJgMq/CboDmyY/8HMMH1fTECbih+w= github.com/urfave/cli/v2 v2.27.5/go.mod h1:3Sevf16NykTbInEnD0yKkjDAeZDS0A6bzhBH5hrMvTQ= +github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU= +github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA= github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4= github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= @@ -196,8 +198,8 @@ go.opentelemetry.io/otel v1.41.0 h1:YlEwVsGAlCvczDILpUXpIpPSL/VPugt7zHThEMLce1c= go.opentelemetry.io/otel v1.41.0/go.mod h1:Yt4UwgEKeT05QbLwbyHXEwhnjxNO6D8L5PQP51/46dE= go.opentelemetry.io/otel/metric v1.41.0 h1:rFnDcs4gRzBcsO9tS8LCpgR0dxg4aaxWlJxCno7JlTQ= go.opentelemetry.io/otel/metric v1.41.0/go.mod h1:xPvCwd9pU0VN8tPZYzDZV/BMj9CM9vs00GuBjeKhJps= -go.opentelemetry.io/otel/sdk v1.40.0 h1:KHW/jUzgo6wsPh9At46+h4upjtccTmuZCFAc9OJ71f8= -go.opentelemetry.io/otel/sdk v1.40.0/go.mod h1:Ph7EFdYvxq72Y8Li9q8KebuYUr2KoeyHx0DRMKrYBUE= +go.opentelemetry.io/otel/sdk v1.41.0 h1:YPIEXKmiAwkGl3Gu1huk1aYWwtpRLeskpV+wPisxBp8= +go.opentelemetry.io/otel/sdk v1.41.0/go.mod h1:ahFdU0G5y8IxglBf0QBJXgSe7agzjE4GiTJ6HT9ud90= go.opentelemetry.io/otel/trace v1.41.0 h1:Vbk2co6bhj8L59ZJ6/xFTskY+tGAbOnCtQGVVa9TIN0= go.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -219,10 +221,10 @@ golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= -golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= -golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= -golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA= -golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= +golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4= +golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc= +golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= From f5d8959eca918301b8f851fe2b8f4cb2b9af4f8f Mon Sep 17 00:00:00 2001 From: Iva Brajer Date: Thu, 29 Oct 2026 14:32:02 +0100 Subject: [PATCH 5/5] Remove stale VRF v1 entries from native_solc_compile_all_vrf The VRF v1 removal (#571) deleted these Solidity sources, but the compile script still referenced them, causing forge build to fail with "No source files found in specified build paths" in CI. Co-Authored-By: Claude Code --- contracts/scripts/native_solc_compile_all_vrf | 9 --------- 1 file changed, 9 deletions(-) diff --git a/contracts/scripts/native_solc_compile_all_vrf b/contracts/scripts/native_solc_compile_all_vrf index ee4e55c509..ca1e8908df 100755 --- a/contracts/scripts/native_solc_compile_all_vrf +++ b/contracts/scripts/native_solc_compile_all_vrf @@ -31,20 +31,11 @@ compileContract() { cp "$CONTRACTS_DIR"/solc/$PROJECT/"$contract"/"$contract".sol/"$contract".abi.json "$CONTRACTS_DIR"/abi/v0.8/"$PROJECT"/"$contract".abi.json } -# VRF -compileContract vrf-compile VRFRequestIDBase -compileContract vrf-compile VRFConsumerBase -compileContract vrf-compile testhelpers/VRFConsumer -compileContract vrf-compile testhelpers/VRFRequestIDBaseTestHelper -compileContract vrf-compile mocks/VRFCoordinatorMock - # VRF Helpers compileContract vrf-compile testhelpers/ChainSpecificUtilHelper compileContract vrf-compile testhelpers/VRFTestHelper # VRF Consumers and Mocks -compileContract vrf-compile testhelpers/VRFOwnerlessConsumerExample -compileContract vrf-compile testhelpers/VRFLoadTestOwnerlessConsumer compileContract vrf-compile testhelpers/VRFMockETHLINKAggregator compileContract vrf-compile testhelpers/Counter