zellic-audit
Initial commit
f998fcd
raw
history blame
23.9 kB
{
"language": "Solidity",
"sources": {
"contracts/Randomizer.sol": {
"content": "// SPDX-License-Identifier: MIT\n// An example of a consumer contract that also owns and manages the subscription\npragma solidity ^0.8.7;\npragma abicoder v2;\n\nimport \"@chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol\";\nimport \"@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol\";\nimport \"@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"./interfaces/IUniswapV2Router.sol\";\nimport \"./interfaces/IWETH.sol\";\n\ncontract Randomizer is VRFConsumerBaseV2 {\n VRFCoordinatorV2Interface COORDINATOR;\n LinkTokenInterface LINKTOKEN;\n\n address vrfCoordinator = 0x271682DEB8C4E0901D1a1550aD2e64D568E69909;\n address link_token_contract = 0x514910771AF9Ca656af840dff83E8264EcF986CA;\n bytes32 keyHash = 0x8af398995b04c28e9951adb9721ef74c74f93e6a478f39e7e0777be13527e7ef;\n uint32 callbackGasLimit = 2500000;\n uint16 requestConfirmations = 3;\n uint32 numWords = 100;\n\n // Storage parameters\n uint256[] private s_randomWords;\n uint256 public s_requestId;\n uint64 public s_subscriptionId;\n address s_owner;\n\n mapping(address => bool) gameContracts;\n\n uint256 wordsThreshold = 25;\n bool requestPending;\n \n address private constant UNISWAP_V2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;\n address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\n address public constant LINK = 0x514910771AF9Ca656af840dff83E8264EcF986CA;\n uint256 public swapThreshold = 10000000000000000;\n\n constructor() VRFConsumerBaseV2(vrfCoordinator) {\n COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);\n LINKTOKEN = LinkTokenInterface(link_token_contract);\n s_owner = msg.sender;\n //Create a new subscription when you deploy the contract.\n createNewSubscription();\n gameContracts[address(this)] = true;\n }\n\n receive() external payable {}\n\n modifier onlyGames() {\n require(gameContracts[msg.sender], \"only game contracts allowed\");\n _;\n }\n\n // Assumes the subscription is funded sufficiently.\n function requestRandomWords() public onlyGames {\n // Will revert if subscription is not set and funded.\n s_requestId = COORDINATOR.requestRandomWords(\n keyHash,\n s_subscriptionId,\n requestConfirmations,\n callbackGasLimit,\n numWords\n );\n }\n\n function fulfillRandomWords(\n uint256, /* requestId */\n uint256[] memory randomWords\n ) internal override {\n s_randomWords = randomWords;\n requestPending = false;\n }\n\n function getRandomWords(uint256 number) external onlyGames returns (uint256[] memory ranWords) {\n ranWords = new uint256[](number);\n for (uint i = 0; i < number; i++) {\n uint256 curIndex = s_randomWords.length-1;\n ranWords[i] = s_randomWords[curIndex];\n s_randomWords.pop();\n }\n\n uint256 remainingWords = s_randomWords.length;\n if(remainingWords < wordsThreshold && !requestPending) {\n swapAndTopLink(); \n requestRandomWords(); \n requestPending = true;\n }\n }\n\n function getRemainingWords() external view onlyGames returns (uint256) {\n return s_randomWords.length;\n }\n\n // Create a new subscription when the contract is initially deployed.\n function createNewSubscription() private onlyOwner {\n s_subscriptionId = COORDINATOR.createSubscription();\n // Add this contract as a consumer of its own subscription.\n COORDINATOR.addConsumer(s_subscriptionId, address(this));\n }\n\n function swapAndTopLink() public onlyGames {\n uint256 amountIn = address(this).balance;\n if(amountIn < swapThreshold) {\n return;\n }\n\n IWETH(WETH).deposit{value: amountIn}();\n swap(WETH, LINK, amountIn, 0, address(this));\n\n uint256 amountOut = LINKTOKEN.balanceOf(address(this));\n LINKTOKEN.transferAndCall(address(COORDINATOR), amountOut, abi.encode(s_subscriptionId));\n }\n\n function swap(address _tokenIn, address _tokenOut, uint256 _amountIn, uint256 _amountOutMin, address _to) internal {\n IERC20(WETH).approve(UNISWAP_V2_ROUTER, _amountIn);\n\n address[] memory path;\n path = new address[](2);\n path[0] = _tokenIn;\n path[1] = _tokenOut;\n\n IUniswapV2Router(UNISWAP_V2_ROUTER).swapExactTokensForTokens(_amountIn, _amountOutMin, path, _to, block.timestamp);\n }\n\n // Assumes this contract owns link.\n // 1000000000000000000 = 1 LINK\n function topUpSubscription(uint256 amount) external onlyOwner {\n LINKTOKEN.transferAndCall(address(COORDINATOR), amount, abi.encode(s_subscriptionId));\n }\n\n function addConsumer(address consumerAddress) external onlyOwner {\n // Add a consumer contract to the subscription.\n COORDINATOR.addConsumer(s_subscriptionId, consumerAddress);\n }\n\n function removeConsumer(address consumerAddress) external onlyOwner {\n // Remove a consumer contract from the subscription.\n COORDINATOR.removeConsumer(s_subscriptionId, consumerAddress);\n }\n\n function cancelSubscription(address receivingWallet) external onlyOwner {\n // Cancel the subscription and send the remaining LINK to a wallet address.\n COORDINATOR.cancelSubscription(s_subscriptionId, receivingWallet);\n s_subscriptionId = 0;\n }\n\n // Transfer this contract's funds to an address.\n // 1000000000000000000 = 1 LINK\n function withdraw(uint256 amount, address to) external onlyOwner {\n LINKTOKEN.transfer(to, amount);\n }\n\n function rescueETH() external onlyOwner {\n uint256 amount = address(this).balance;\n payable(s_owner).transfer(amount);\n }\n\n function rescueToken(address _token) external onlyOwner {\n uint256 amount = IERC20(_token).balanceOf(address(this));\n IERC20(_token).transfer(s_owner, amount);\n }\n\n function setGameContract(address _contract, bool flag)external onlyOwner {\n gameContracts[_contract] = flag;\n }\n\n function setCallbackGas(uint32 _gas) external onlyOwner {\n callbackGasLimit = _gas;\n }\n\n function setNumWords(uint32 _numWords) external onlyOwner {\n numWords = _numWords;\n }\n\n function setSwapThreshold(uint256 _threshold) external onlyOwner {\n swapThreshold = _threshold;\n }\n\n function setWordsThreshold(uint256 _threshold) external onlyOwner {\n wordsThreshold = _threshold;\n }\n\n modifier onlyOwner() {\n require(msg.sender == s_owner);\n _;\n }\n}\n\n"
},
"contracts/interfaces/IWETH.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.16;\n\ninterface IWETH {\n function deposit() external payable;\n function transfer(address to, uint value) external returns (bool);\n function withdraw(uint) external;\n}"
},
"contracts/interfaces/IUniswapV2Router.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.7;\n\ninterface IUniswapV2Router {\n function getAmountsOut(uint256 amountIn, address[] memory path)\n external\n view\n returns (uint256[] memory amounts);\n \n function swapExactTokensForTokens(\n \n //amount of tokens we are sending in\n uint256 amountIn,\n //the minimum amount of tokens we want out of the trade\n uint256 amountOutMin,\n //list of token addresses we are going to trade in. this is necessary to calculate amounts\n address[] calldata path,\n //this is the address we are going to send the output tokens to\n address to,\n //the last time that the trade is valid for\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n}\n\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
},
"@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/** ****************************************************************************\n * @notice Interface for contracts using VRF randomness\n * *****************************************************************************\n * @dev PURPOSE\n *\n * @dev Reggie the Random Oracle (not his real job) wants to provide randomness\n * @dev to Vera the verifier in such a way that Vera can be sure he's not\n * @dev making his output up to suit himself. Reggie provides Vera a public key\n * @dev to which he knows the secret key. Each time Vera provides a seed to\n * @dev Reggie, he gives back a value which is computed completely\n * @dev deterministically from the seed and the secret key.\n *\n * @dev Reggie provides a proof by which Vera can verify that the output was\n * @dev correctly computed once Reggie tells it to her, but without that proof,\n * @dev the output is indistinguishable to her from a uniform random sample\n * @dev from the output space.\n *\n * @dev The purpose of this contract is to make it easy for unrelated contracts\n * @dev to talk to Vera the verifier about the work Reggie is doing, to provide\n * @dev simple access to a verifiable source of randomness. It ensures 2 things:\n * @dev 1. The fulfillment came from the VRFCoordinator\n * @dev 2. The consumer contract implements fulfillRandomWords.\n * *****************************************************************************\n * @dev USAGE\n *\n * @dev Calling contracts must inherit from VRFConsumerBase, and can\n * @dev initialize VRFConsumerBase's attributes in their constructor as\n * @dev shown:\n *\n * @dev contract VRFConsumer {\n * @dev constructor(<other arguments>, address _vrfCoordinator, address _link)\n * @dev VRFConsumerBase(_vrfCoordinator) public {\n * @dev <initialization with other arguments goes here>\n * @dev }\n * @dev }\n *\n * @dev The oracle will have given you an ID for the VRF keypair they have\n * @dev committed to (let's call it keyHash). Create subscription, fund it\n * @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface\n * @dev subscription management functions).\n * @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,\n * @dev callbackGasLimit, numWords),\n * @dev see (VRFCoordinatorInterface for a description of the arguments).\n *\n * @dev Once the VRFCoordinator has received and validated the oracle's response\n * @dev to your request, it will call your contract's fulfillRandomWords method.\n *\n * @dev The randomness argument to fulfillRandomWords is a set of random words\n * @dev generated from your requestId and the blockHash of the request.\n *\n * @dev If your contract could have concurrent requests open, you can use the\n * @dev requestId returned from requestRandomWords to track which response is associated\n * @dev with which randomness request.\n * @dev See \"SECURITY CONSIDERATIONS\" for principles to keep in mind,\n * @dev if your contract could have multiple requests in flight simultaneously.\n *\n * @dev Colliding `requestId`s are cryptographically impossible as long as seeds\n * @dev differ.\n *\n * *****************************************************************************\n * @dev SECURITY CONSIDERATIONS\n *\n * @dev A method with the ability to call your fulfillRandomness method directly\n * @dev could spoof a VRF response with any random value, so it's critical that\n * @dev it cannot be directly called by anything other than this base contract\n * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).\n *\n * @dev For your users to trust that your contract's random behavior is free\n * @dev from malicious interference, it's best if you can write it so that all\n * @dev behaviors implied by a VRF response are executed *during* your\n * @dev fulfillRandomness method. If your contract must store the response (or\n * @dev anything derived from it) and use it later, you must ensure that any\n * @dev user-significant behavior which depends on that stored value cannot be\n * @dev manipulated by a subsequent VRF request.\n *\n * @dev Similarly, both miners and the VRF oracle itself have some influence\n * @dev over the order in which VRF responses appear on the blockchain, so if\n * @dev your contract could have multiple VRF requests in flight simultaneously,\n * @dev you must ensure that the order in which the VRF responses arrive cannot\n * @dev be used to manipulate your contract's user-significant behavior.\n *\n * @dev Since the block hash of the block which contains the requestRandomness\n * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful\n * @dev miner could, in principle, fork the blockchain to evict the block\n * @dev containing the request, forcing the request to be included in a\n * @dev different block with a different hash, and therefore a different input\n * @dev to the VRF. However, such an attack would incur a substantial economic\n * @dev cost. This cost scales with the number of blocks the VRF oracle waits\n * @dev until it calls responds to a request. It is for this reason that\n * @dev that you can signal to an oracle you'd like them to wait longer before\n * @dev responding to the request (however this is not enforced in the contract\n * @dev and so remains effective only in the case of unmodified oracle software).\n */\nabstract contract VRFConsumerBaseV2 {\n error OnlyCoordinatorCanFulfill(address have, address want);\n address private immutable vrfCoordinator;\n\n /**\n * @param _vrfCoordinator address of VRFCoordinator contract\n */\n constructor(address _vrfCoordinator) {\n vrfCoordinator = _vrfCoordinator;\n }\n\n /**\n * @notice fulfillRandomness handles the VRF response. Your contract must\n * @notice implement it. See \"SECURITY CONSIDERATIONS\" above for important\n * @notice principles to keep in mind when implementing your fulfillRandomness\n * @notice method.\n *\n * @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this\n * @dev signature, and will call it once it has verified the proof\n * @dev associated with the randomness. (It is triggered via a call to\n * @dev rawFulfillRandomness, below.)\n *\n * @param requestId The Id initially returned by requestRandomness\n * @param randomWords the VRF output expanded to the requested number of words\n */\n function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual;\n\n // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF\n // proof. rawFulfillRandomness then calls fulfillRandomness, after validating\n // the origin of the call\n function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external {\n if (msg.sender != vrfCoordinator) {\n revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator);\n }\n fulfillRandomWords(requestId, randomWords);\n }\n}\n"
},
"@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface VRFCoordinatorV2Interface {\n /**\n * @notice Get configuration relevant for making requests\n * @return minimumRequestConfirmations global min for request confirmations\n * @return maxGasLimit global max for request gas limit\n * @return s_provingKeyHashes list of registered key hashes\n */\n function getRequestConfig()\n external\n view\n returns (\n uint16,\n uint32,\n bytes32[] memory\n );\n\n /**\n * @notice Request a set of random words.\n * @param keyHash - Corresponds to a particular oracle job which uses\n * that key for generating the VRF proof. Different keyHash's have different gas price\n * ceilings, so you can select a specific one to bound your maximum per request cost.\n * @param subId - The ID of the VRF subscription. Must be funded\n * with the minimum subscription balance required for the selected keyHash.\n * @param minimumRequestConfirmations - How many blocks you'd like the\n * oracle to wait before responding to the request. See SECURITY CONSIDERATIONS\n * for why you may want to request more. The acceptable range is\n * [minimumRequestBlockConfirmations, 200].\n * @param callbackGasLimit - How much gas you'd like to receive in your\n * fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords\n * may be slightly less than this amount because of gas used calling the function\n * (argument decoding etc.), so you may need to request slightly more than you expect\n * to have inside fulfillRandomWords. The acceptable range is\n * [0, maxGasLimit]\n * @param numWords - The number of uint256 random values you'd like to receive\n * in your fulfillRandomWords callback. Note these numbers are expanded in a\n * secure way by the VRFCoordinator from a single random value supplied by the oracle.\n * @return requestId - A unique identifier of the request. Can be used to match\n * a request to a response in fulfillRandomWords.\n */\n function requestRandomWords(\n bytes32 keyHash,\n uint64 subId,\n uint16 minimumRequestConfirmations,\n uint32 callbackGasLimit,\n uint32 numWords\n ) external returns (uint256 requestId);\n\n /**\n * @notice Create a VRF subscription.\n * @return subId - A unique subscription id.\n * @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.\n * @dev Note to fund the subscription, use transferAndCall. For example\n * @dev LINKTOKEN.transferAndCall(\n * @dev address(COORDINATOR),\n * @dev amount,\n * @dev abi.encode(subId));\n */\n function createSubscription() external returns (uint64 subId);\n\n /**\n * @notice Get a VRF subscription.\n * @param subId - ID of the subscription\n * @return balance - LINK balance of the subscription in juels.\n * @return reqCount - number of requests for this subscription, determines fee tier.\n * @return owner - owner of the subscription.\n * @return consumers - list of consumer address which are able to use this subscription.\n */\n function getSubscription(uint64 subId)\n external\n view\n returns (\n uint96 balance,\n uint64 reqCount,\n address owner,\n address[] memory consumers\n );\n\n /**\n * @notice Request subscription owner transfer.\n * @param subId - ID of the subscription\n * @param newOwner - proposed new owner of the subscription\n */\n function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;\n\n /**\n * @notice Request subscription owner transfer.\n * @param subId - ID of the subscription\n * @dev will revert if original owner of subId has\n * not requested that msg.sender become the new owner.\n */\n function acceptSubscriptionOwnerTransfer(uint64 subId) external;\n\n /**\n * @notice Add a consumer to a VRF subscription.\n * @param subId - ID of the subscription\n * @param consumer - New consumer which can use the subscription\n */\n function addConsumer(uint64 subId, address consumer) external;\n\n /**\n * @notice Remove a consumer from a VRF subscription.\n * @param subId - ID of the subscription\n * @param consumer - Consumer to remove from the subscription\n */\n function removeConsumer(uint64 subId, address consumer) external;\n\n /**\n * @notice Cancel a subscription\n * @param subId - ID of the subscription\n * @param to - Where to send the remaining LINK to\n */\n function cancelSubscription(uint64 subId, address to) external;\n}\n"
},
"@chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface LinkTokenInterface {\n function allowance(address owner, address spender) external view returns (uint256 remaining);\n\n function approve(address spender, uint256 value) external returns (bool success);\n\n function balanceOf(address owner) external view returns (uint256 balance);\n\n function decimals() external view returns (uint8 decimalPlaces);\n\n function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);\n\n function increaseApproval(address spender, uint256 subtractedValue) external;\n\n function name() external view returns (string memory tokenName);\n\n function symbol() external view returns (string memory tokenSymbol);\n\n function totalSupply() external view returns (uint256 totalTokensIssued);\n\n function transfer(address to, uint256 value) external returns (bool success);\n\n function transferAndCall(\n address to,\n uint256 value,\n bytes calldata data\n ) external returns (bool success);\n\n function transferFrom(\n address from,\n address to,\n uint256 value\n ) external returns (bool success);\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 999999
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
}
}
}