file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; ///////////////////////////////////////////////////////////////////////////////////////////////////////// // // // OIIIIIIIIII77 // // IIIIIIIII???IIIII77 NI777777777777$ // // IIIII?????????????I?7III O77777777IIIIII77777777 // // 7IIIIIIIII7I?????????III7I I7777IIIIIIIIIIIIIIIII77777$ // // N8ZIIIIIIII7I??I??II7II 7777IIIIIIIIIIIIIIIIIIIIIIII7777 // // I77IIIIIIII77I 777IIIIIIIIIIIIIIIIIIIIIIIII777777D // // 7777IIII77 777IIIIIIIIII7777777777III777777777$7 // // O7III7I77I777 7I7III777 777IIIIII777777777777777777777777777$$$ // // IIIIIIIIIIIIII77IIII77I N77III77 777IIII77777$ N$77$77$7777$$D // // ?7IIII???????????????III7II77 77II77777II7777I 8$$$7$77$$N // // IIII???????????????IIIIIIIIII77777IIII7II7777 $$$$$$$ // // N7II??????????????II7III7I7777777IIIIIIIII777 7$$$$ // // $II???????????I7IIIIIIIIZO888Z7I7777IIIIIII77777777777777777777D O$$$ // // $II?????????I7IIII8 777777IIIIIIII777IIIIIIIII777777777$$7 Z$ // // 8II???????IIII? $7777777777IIIIIIIIIIIIIIIIIIIIIIIIII777777$$77$Z // // 7I?????III77 I7777777IIIIIII77777II777777IIIIIIIIIII7777777777777$$$ // // III???IIII OI7777IIIIIIIIIII777I$77I777$7777777IIIIIII77777777777777$$$7 // // 7I??IIII I7I7IIIIIIIIIIIII777Z 777II777$$$ 7$777777777777777777777777$$$8 // // IIIIII7 OII7I?IIIIIIIIIII7777 $777II777777$$D 777777777777777777777777$$7 // // IIIII 7IIIIIIIIIIIIIIII777 777IIII77$$777$$N $77$777777777777777777$$$ // // III I77IIIIIIIIIIIIII777 777IIII777$$7777$$ 8$77$7777777777777777$$7 // // I$ II7?IIIIIIIIIIII777$ 777IIIII77 $$$777$$$ $$$$777777777777777$$ // // 77IIIIIIIIIIIIII777 777IIIII777 $$$777$$$ 77$$77777777777777$$ // // 7IIIIIIIIIIIIII777 777IIIIII778 D$$7777$$$ 7$$$777777777777$$O // // II7IIIIIIIIIIII777 777IIIIIII77 $$$$$$$$$D $$$77777777777$$$ // // DI7IIIIIIIIIII7778 N77IIIIIII777 8$$$$$$$$$ N$$$7777777777$$ // // 77IIIIIIIIIII777 777IIIIIII777 $$$7I77$$$ Z$$$77777777$$N // // 77IIIIIIIIII777 877IIIIIIII77Z Z$$$$$$$$$ $$$7777777$$$ // // NI7IIIIIIIII777 777IIIIIIII77 Z$$$$$$$$$ 8$$$$777$$$$ // // 877IIIIIIII777 77IIIIIIIII77 Z$$$$$$$$$ $$$777$$$$ // // O77IIIIIII77O O77IIIIIIIII77 Z$$$$$$$$$$ $$$7$$$$$ // // D77IIIIII777 777IIIIIIIII77 $$IIIII$$Z 8Z$$7$$Z // // 77IIIII777 777IIIIIIII777 $$$$7$$$$ZZ $$$$$ // // 77IIII777 777IIIIIII7777 $Z$$$$$$$ZZ $$$$ // // 777II777 7777IIIII777$7Z ZZZ$$$$$$ZZZ $$$ // // D77II77 N777III77777777 DZZ$$$$$$$ZZ $$ // // 77I777 77III77777777$ ZZ$$$$II$ZZ // // O7777 7777777777777$ ZZ$$$$IZ$ZZZ // // 7778 77777777777$$ ZZZZZZ$ZZZZZ // // 77 Z7777777777$77 ZZZZZZZZZZZZ // // Z$ 77777777777$$ ZZZZZZZZZZZZ8 // // 7777777777$$ ZZZIII$ZZZZZZ // // 777777777$$$ ZZZZZZZZZZZZZ // // $$$77777$$ ZZZZZZZZZZZZZ // // N7$$$77$$$ ZZZZZZZZZ$ZZZ // // 7$$$$$$ ZZZZZZIIIZZZZN // // O$$$ OZZZZZZZZZZZZ8 // // OZZZZZZZZZZZOO // // OZZZZZZZZZZOOO // // OOOZZZZZZZZOOO // // OOOIIIOOZZOOOO // // OOOOOOOOOOOOOO // // OOOOOOOOOOOOOO // // OOOOOOOOOOOOOO // // NOOOOOOOIIOOOOO // // OOOOOOOOOOOOOO8 // // OOOOOOOOOOOOOOD // // OOOOOOOOOOOOOO // // OOOOOOOOOOOO8 // // D8O8D // // nft affirmations // ///////////////////////////////////////////////////////////////////////////////////////////////////////// contract Affirmations is ERC721Enumerable, Ownable, VRFConsumerBase { using SafeMath for uint256; using Strings for uint256; string public _baseTokenURI; bytes32 internal keyHash; uint256 internal fee; bool public saleStarted = false; bool public whitelistStarted = false; bool public eight88Started = false; bool public mintStartIndexDrawn = false; ERC1155 eight88contract = ERC1155(0xA4Aeee2ea28D116db404e3840a5C300436Ec3456); uint256 public mintStartIndex; uint256 private price = 77700000000000000; // 0.0777 ETH uint256 public totalAffirmations = 10000; uint256 public maxAffirmationsPerMint = 7; string public provenanceHash = ""; // example event randomStartingIndexDrawn(uint256 mintStartIndex); address vrfCoordinator = 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952; address linkToken = 0x514910771AF9Ca656af840dff83E8264EcF986CA; uint linkFee = 2 * 10 ** 18; constructor() ERC721("NFT Affirmations", "AMINT") VRFConsumerBase(vrfCoordinator, linkToken) { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = linkFee; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } function tokenURI(uint256 tokenId) override view public returns (string memory) { uint256 chosenURI = (tokenId + mintStartIndex) % totalAffirmations; return bytes(_baseTokenURI).length > 0 ? string(abi.encodePacked(_baseTokenURI, chosenURI.toString(), ".json")) : ""; } function startSale() public onlyOwner { require(mintStartIndexDrawn, "Must draw random number."); saleStarted = true; } function pauseSale() public onlyOwner { saleStarted = false; } function startWhitelist() public onlyOwner { require(mintStartIndexDrawn, "Must draw random number."); whitelistStarted = true; } function stopWhitelist() public onlyOwner { whitelistStarted = false; } function start888() public onlyOwner { require(mintStartIndexDrawn, "Must draw random number."); eight88Started = true; } function stop888() public onlyOwner { eight88Started = false; } function mintGifts(uint256[] memory numberOfMints, address[] memory _mintTo) public onlyOwner { require(mintStartIndexDrawn, "Sale hasn't started"); for (uint i = 0; i < numberOfMints.length; i++) { require(totalSupply().add(numberOfMints[i]) <= totalAffirmations, 'Not enough affirmations left'); for(uint j = 0; j < numberOfMints[i]; j++) { uint mintNum = totalSupply() + 1; if (mintNum < totalAffirmations) { _safeMint(_mintTo[i], mintNum); } } } } function manifest(uint256 numberOfMints) public payable { require(mintStartIndexDrawn, "Sale hasn't started"); uint256 newMintCount = totalSupply().add(numberOfMints); uint256 myBalance = balanceOf(msg.sender).add(numberOfMints); if (whitelistStarted) { require(newMintCount <= 1111, "Whitelist period has sold out"); require(myBalance <= 1, 'Maximum 1 affirmation during presale'); } else if (eight88Started) { require(eight88contract.balanceOf(msg.sender, 888) > 0); require(newMintCount <= (1111 + 888), "Whitelist period has sold out"); require(myBalance <= 1, 'Maximum 1 affirmation during presale'); } else require(saleStarted, "Sale hasn't started"); require(numberOfMints > 0 && numberOfMints <= maxAffirmationsPerMint, 'Can mint up to 7 affirmations at a time'); require(myBalance <= 33, 'Maximum 33 affirmations per wallet'); require(newMintCount <= totalAffirmations, 'Not enough affirmations left'); require(msg.value == price.mul(numberOfMints), 'Need 0.0777 ETH per affirmation'); for (uint i = 0; i < numberOfMints; i++) { uint mintNum = totalSupply() + 1; if (mintNum < totalAffirmations) { _safeMint(msg.sender, mintNum); } } } /** * Requests randomness from Chainlink */ function getRandomStartIndex() public onlyOwner returns (bytes32 requestId) { require(!mintStartIndexDrawn , "RNG ALREADY DRAWN"); require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK"); return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { mintStartIndex = randomness % totalAffirmations; if (mintStartIndex == 0) { mintStartIndex = 1; } emit randomStartingIndexDrawn(mintStartIndex); mintStartIndexDrawn = true; } function withdrawLink() external onlyOwner { require(LINK.transfer(msg.sender, LINK.balanceOf(address(this))), "Unable to transfer"); } function withdraw(address _to, uint amount) public onlyOwner { payable(_to).call{value:amount, gas:200000}(""); } // COMMENT THIS FUNCTION ON PRODUCTION. ONLY FOR TESTING function testStartIndex(uint256 index) public onlyOwner { mintStartIndex = index; mintStartIndexDrawn = true; } function changeMaxNumber(uint256 totalAff) public onlyOwner { totalAffirmations = totalAff; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee ) internal returns ( bytes32 requestId ) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @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. */ abstract 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() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual 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 virtual onlyOwner { _setOwner(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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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 a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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 a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting 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) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @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"); (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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 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. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); }
* Callback function used by VRF Coordinator/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { mintStartIndex = randomness % totalAffirmations; if (mintStartIndex == 0) { mintStartIndex = 1; } emit randomStartingIndexDrawn(mintStartIndex); mintStartIndexDrawn = true; }
399,567
[ 1, 2428, 445, 1399, 635, 776, 12918, 10320, 4240, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22290, 8529, 4496, 12, 3890, 1578, 14459, 16, 2254, 5034, 2744, 4496, 13, 2713, 3849, 288, 203, 3639, 312, 474, 16792, 273, 2744, 4496, 738, 2078, 13785, 3985, 1012, 31, 203, 3639, 309, 261, 81, 474, 16792, 422, 374, 13, 288, 203, 5411, 312, 474, 16792, 273, 404, 31, 203, 3639, 289, 203, 203, 3639, 3626, 2744, 11715, 1016, 6493, 82, 12, 81, 474, 16792, 1769, 203, 203, 3639, 312, 474, 16792, 6493, 82, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x41cB4a771FdD019ADBF4685bd4885fbBeedE1784/sources/contracts/EvilNoundlesVRF.sol
generic minting function :) Attempt to mint. Removed for now.
function _handleMinting(address _to, uint256 _index, uint8 _type, bool useECType) private { _safeMint(_to, _index); localTotalSupply.increment(); if (useECType && _type == 0) { companionBalance[_to]++; companionList.push(_index); noundleOffsetCount[_index] = mintCountCompanions; mintCountCompanions++; evilBalance[_to]++; evilList.push(_index); noundleOffsetCount[_index] = mintCountEvil; mintCountEvil++; lowLandBalance[_to]++; lowLandList.push(_index); noundleOffsetCount[_index] = mintCountLandLow; mintCountLandLow++; midLandBalance[_to]++; midLandList.push(_index); noundleOffsetCount[_index] = mintCountLandMid; mintCountLandMid++; highLandBalance[_to]++; highLandList.push(_index); noundleOffsetCount[_index] = mintCountLandHigh; mintCountLandHigh++; } }
3,121,462
[ 1, 13540, 312, 474, 310, 445, 294, 13, 12864, 358, 312, 474, 18, 2663, 9952, 364, 2037, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4110, 49, 474, 310, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1615, 16, 2254, 28, 389, 723, 16, 1426, 999, 7228, 559, 13, 3238, 288, 203, 203, 3639, 389, 4626, 49, 474, 24899, 869, 16, 389, 1615, 1769, 203, 203, 3639, 1191, 5269, 3088, 1283, 18, 15016, 5621, 203, 203, 3639, 309, 261, 1202, 7228, 559, 597, 389, 723, 422, 374, 13, 288, 203, 5411, 1161, 304, 285, 13937, 63, 67, 869, 3737, 15, 31, 203, 5411, 1161, 304, 285, 682, 18, 6206, 24899, 1615, 1769, 203, 5411, 290, 772, 298, 2335, 1380, 63, 67, 1615, 65, 273, 312, 474, 1380, 2945, 304, 1115, 31, 203, 5411, 312, 474, 1380, 2945, 304, 1115, 9904, 31, 203, 5411, 2113, 330, 13937, 63, 67, 869, 3737, 15, 31, 203, 5411, 2113, 330, 682, 18, 6206, 24899, 1615, 1769, 203, 5411, 290, 772, 298, 2335, 1380, 63, 67, 1615, 65, 273, 312, 474, 1380, 20861, 330, 31, 203, 5411, 312, 474, 1380, 20861, 330, 9904, 31, 203, 5411, 4587, 29398, 13937, 63, 67, 869, 3737, 15, 31, 203, 5411, 4587, 29398, 682, 18, 6206, 24899, 1615, 1769, 203, 5411, 290, 772, 298, 2335, 1380, 63, 67, 1615, 65, 273, 312, 474, 1380, 29398, 10520, 31, 203, 5411, 312, 474, 1380, 29398, 10520, 9904, 31, 203, 5411, 7501, 29398, 13937, 63, 67, 869, 3737, 15, 31, 203, 5411, 7501, 29398, 682, 18, 6206, 24899, 1615, 1769, 203, 5411, 290, 772, 298, 2335, 1380, 63, 67, 1615, 65, 273, 312, 474, 1380, 29398, 20711, 31, 2 ]
pragma solidity ^0.4.17; contract Lottery { address public manager; address[] public players; function Lottery() public { // Assign the manager to be the person who launched the contract manager = msg.sender; } function enter() public payable { // Requires ether to join the contest require(msg.value > .01 ether); // this might fail, it won't say why it failed players.push(msg.sender); } function random() private view returns (uint) { // Returns return uint(keccak256(block.difficulty, now, players)); //keccak256(); } function pickWinner () public restricted { // Picks the winner of the lottery // make sure that contract owner is able to call this function only require(msg.sender == manager); // Pick a winner through pseudonumber generator uint index = random() % players.length; players[index].transfer(this.balance); // Assign a dynamic list to the list of initial size of 0 players = new address[](0); } function getPlayers() public view returns (address[]) { // Returns all the players in the contract return players; } modifier restricted() { // modifier to restrict access to some function // this only allows the manager to run certain public functions require(msg.sender == manager); _; } }
Picks the winner of the lottery make sure that contract owner is able to call this function only Pick a winner through pseudonumber generator Assign a dynamic list to the list of initial size of 0
function pickWinner () public restricted { require(msg.sender == manager); uint index = random() % players.length; players[index].transfer(this.balance); players = new address[](0); }
5,403,440
[ 1, 17968, 87, 326, 5657, 1224, 434, 326, 17417, 387, 93, 1221, 3071, 716, 6835, 3410, 353, 7752, 358, 745, 333, 445, 1338, 23038, 279, 5657, 1224, 3059, 29606, 265, 1226, 4456, 12093, 279, 5976, 666, 358, 326, 666, 434, 2172, 963, 434, 374, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6002, 59, 7872, 1832, 1071, 15693, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3301, 1769, 203, 3639, 2254, 770, 273, 2744, 1435, 738, 18115, 18, 2469, 31, 203, 3639, 18115, 63, 1615, 8009, 13866, 12, 2211, 18, 12296, 1769, 203, 3639, 18115, 273, 394, 1758, 8526, 12, 20, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/80001/0x89A03a99Bf7cAc4c2648460B4D7653e352B8cDA3/sources/DLT.sol
This is the mainnet USDT contract address IERC20 usdt = IERC20(address(usdt)); transfers USDT that belong to your contract to the specified address
function sendUSDT(address _to, uint256 _amount) public onlyRole(SET_ENV_ROLE) { IERC20(USDT_ADDRESS).transfer(_to, _amount); }
8,823,605
[ 1, 2503, 353, 326, 2774, 2758, 11836, 9081, 6835, 1758, 467, 654, 39, 3462, 584, 7510, 273, 467, 654, 39, 3462, 12, 2867, 12, 407, 7510, 10019, 29375, 11836, 9081, 716, 10957, 358, 3433, 6835, 358, 326, 1269, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1366, 3378, 9081, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 2996, 12, 4043, 67, 11986, 67, 16256, 13, 288, 203, 540, 203, 3639, 467, 654, 39, 3462, 12, 3378, 9081, 67, 15140, 2934, 13866, 24899, 869, 16, 389, 8949, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 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 SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 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 * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 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' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _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(IERC20 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, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @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"); (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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; import "./Ownable.sol"; /** * @title Abstract manageable contract that can be inherited by other contracts * @notice Contract module based on Ownable which provides a basic access control mechanism, where * there is an owner and a manager that can be granted exclusive access to specific functions. * * By default, the owner is the deployer of the contract. * * The owner account is set through a two steps process. * 1. The current `owner` calls {transferOwnership} to set a `pendingOwner` * 2. The `pendingOwner` calls {acceptOwnership} to accept the ownership transfer * * The manager account needs to be set using {setManager}. * * This module is used through inheritance. It will make available the modifier * `onlyManager`, which can be applied to your functions to restrict their use to * the manager. */ abstract contract Manageable is Ownable { address private _manager; /** * @dev Emitted when `_manager` has been changed. * @param previousManager previous `_manager` address. * @param newManager new `_manager` address. */ event ManagerTransferred(address indexed previousManager, address indexed newManager); /* ============ External Functions ============ */ /** * @notice Gets current `_manager`. * @return Current `_manager` address. */ function manager() public view virtual returns (address) { return _manager; } /** * @notice Set or change of manager. * @dev Throws if called by any account other than the owner. * @param _newManager New _manager address. * @return Boolean to indicate if the operation was successful or not. */ function setManager(address _newManager) external onlyOwner returns (bool) { return _setManager(_newManager); } /* ============ Internal Functions ============ */ /** * @notice Set or change of manager. * @param _newManager New _manager address. * @return Boolean to indicate if the operation was successful or not. */ function _setManager(address _newManager) private returns (bool) { address _previousManager = _manager; require(_newManager != _previousManager, "Manageable/existing-manager-address"); _manager = _newManager; emit ManagerTransferred(_previousManager, _newManager); return true; } /* ============ Modifier Functions ============ */ /** * @dev Throws if called by any account other than the manager. */ modifier onlyManager() { require(manager() == msg.sender, "Manageable/caller-not-manager"); _; } /** * @dev Throws if called by any account other than the manager or the owner. */ modifier onlyManagerOrOwner() { require(manager() == msg.sender || owner() == msg.sender, "Manageable/caller-not-manager-or-owner"); _; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; /** * @title Abstract ownable contract that can be inherited by other contracts * @notice 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 is the deployer of the contract. * * The owner account is set through a two steps process. * 1. The current `owner` calls {transferOwnership} to set a `pendingOwner` * 2. The `pendingOwner` calls {acceptOwnership} to accept the ownership transfer * * The manager account needs to be set using {setManager}. * * 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. */ abstract contract Ownable { address private _owner; address private _pendingOwner; /** * @dev Emitted when `_pendingOwner` has been changed. * @param pendingOwner new `_pendingOwner` address. */ event OwnershipOffered(address indexed pendingOwner); /** * @dev Emitted when `_owner` has been changed. * @param previousOwner previous `_owner` address. * @param newOwner new `_owner` address. */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /* ============ Deploy ============ */ /** * @notice Initializes the contract setting `_initialOwner` as the initial owner. * @param _initialOwner Initial owner of the contract. */ constructor(address _initialOwner) { _setOwner(_initialOwner); } /* ============ External Functions ============ */ /** * @notice Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @notice Gets current `_pendingOwner`. * @return Current `_pendingOwner` address. */ function pendingOwner() external view virtual returns (address) { return _pendingOwner; } /** * @notice Renounce ownership of the contract. * @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() external virtual onlyOwner { _setOwner(address(0)); } /** * @notice Allows current owner to set the `_pendingOwner` address. * @param _newOwner Address to transfer ownership to. */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Ownable/pendingOwner-not-zero-address"); _pendingOwner = _newOwner; emit OwnershipOffered(_newOwner); } /** * @notice Allows the `_pendingOwner` address to finalize the transfer. * @dev This function is only callable by the `_pendingOwner`. */ function claimOwnership() external onlyPendingOwner { _setOwner(_pendingOwner); _pendingOwner = address(0); } /* ============ Internal Functions ============ */ /** * @notice Internal function to set the `_owner` of the contract. * @param _newOwner New `_owner` address. */ function _setOwner(address _newOwner) private { address _oldOwner = _owner; _owner = _newOwner; emit OwnershipTransferred(_oldOwner, _newOwner); } /* ============ Modifier Functions ============ */ /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == msg.sender, "Ownable/caller-not-owner"); _; } /** * @dev Throws if called by any account other than the `pendingOwner`. */ modifier onlyPendingOwner() { require(msg.sender == _pendingOwner, "Ownable/caller-not-pendingOwner"); _; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0; /// @title Random Number Generator Interface /// @notice Provides an interface for requesting random numbers from 3rd-party RNG services (Chainlink VRF, Starkware VDF, etc..) interface RNGInterface { /// @notice Emitted when a new request for a random number has been submitted /// @param requestId The indexed ID of the request used to get the results of the RNG service /// @param sender The indexed address of the sender of the request event RandomNumberRequested(uint32 indexed requestId, address indexed sender); /// @notice Emitted when an existing request for a random number has been completed /// @param requestId The indexed ID of the request used to get the results of the RNG service /// @param randomNumber The random number produced by the 3rd-party service event RandomNumberCompleted(uint32 indexed requestId, uint256 randomNumber); /// @notice Gets the last request id used by the RNG service /// @return requestId The last request id used in the last request function getLastRequestId() external view returns (uint32 requestId); /// @notice Gets the Fee for making a Request against an RNG service /// @return feeToken The address of the token that is used to pay fees /// @return requestFee The fee required to be paid to make a request function getRequestFee() external view returns (address feeToken, uint256 requestFee); /// @notice Sends a request for a random number to the 3rd-party service /// @dev Some services will complete the request immediately, others may have a time-delay /// @dev Some services require payment in the form of a token, such as $LINK for Chainlink VRF /// @return requestId The ID of the request used to get the results of the RNG service /// @return lockBlock The block number at which the RNG service will start generating time-delayed randomness. The calling contract /// should "lock" all activity until the result is available via the `requestId` function requestRandomNumber() external returns (uint32 requestId, uint32 lockBlock); /// @notice Checks if the request for randomness from the 3rd-party service has completed /// @dev For time-delayed requests, this function is used to check/confirm completion /// @param requestId The ID of the request used to get the results of the RNG service /// @return isCompleted True if the request has completed and a random number is available, false otherwise function isRequestComplete(uint32 requestId) external view returns (bool isCompleted); /// @notice Gets the random number produced by the 3rd-party service /// @param requestId The ID of the request used to get the results of the RNG service /// @return randomNum The random number function randomNumber(uint32 requestId) external returns (uint256 randomNum); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "@pooltogether/owner-manager-contracts/contracts/Manageable.sol"; import "./libraries/DrawRingBufferLib.sol"; import "./interfaces/IPrizeDistributionBuffer.sol"; /** * @title PoolTogether V4 PrizeDistributionBuffer * @author PoolTogether Inc Team * @notice The PrizeDistributionBuffer contract provides historical lookups of PrizeDistribution struct parameters (linked with a Draw ID) via a circular ring buffer. Historical PrizeDistribution parameters can be accessed on-chain using a drawId to calculate ring buffer storage slot. The PrizeDistribution parameters can be created by manager/owner and existing PrizeDistribution parameters can only be updated the owner. When adding a new PrizeDistribution basic sanity checks will be used to validate the incoming parameters. */ contract PrizeDistributionBuffer is IPrizeDistributionBuffer, Manageable { using DrawRingBufferLib for DrawRingBufferLib.Buffer; /// @notice The maximum cardinality of the prize distribution ring buffer. /// @dev even with daily draws, 256 will give us over 8 months of history. uint256 internal constant MAX_CARDINALITY = 256; /// @notice The ceiling for prize distributions. 1e9 = 100%. /// @dev It's fixed point 9 because 1e9 is the largest "1" that fits into 2**32 uint256 internal constant TIERS_CEILING = 1e9; /// @notice Emitted when the contract is deployed. /// @param cardinality The maximum number of records in the buffer before they begin to expire. event Deployed(uint8 cardinality); /// @notice PrizeDistribution ring buffer history. IPrizeDistributionBuffer.PrizeDistribution[MAX_CARDINALITY] internal prizeDistributionRingBuffer; /// @notice Ring buffer metadata (nextIndex, lastId, cardinality) DrawRingBufferLib.Buffer internal bufferMetadata; /* ============ Constructor ============ */ /** * @notice Constructor for PrizeDistributionBuffer * @param _owner Address of the PrizeDistributionBuffer owner * @param _cardinality Cardinality of the `bufferMetadata` */ constructor(address _owner, uint8 _cardinality) Ownable(_owner) { bufferMetadata.cardinality = _cardinality; emit Deployed(_cardinality); } /* ============ External Functions ============ */ /// @inheritdoc IPrizeDistributionBuffer function getBufferCardinality() external view override returns (uint32) { return bufferMetadata.cardinality; } /// @inheritdoc IPrizeDistributionBuffer function getPrizeDistribution(uint32 _drawId) external view override returns (IPrizeDistributionBuffer.PrizeDistribution memory) { return _getPrizeDistribution(bufferMetadata, _drawId); } /// @inheritdoc IPrizeDistributionBuffer function getPrizeDistributions(uint32[] calldata _drawIds) external view override returns (IPrizeDistributionBuffer.PrizeDistribution[] memory) { uint256 drawIdsLength = _drawIds.length; DrawRingBufferLib.Buffer memory buffer = bufferMetadata; IPrizeDistributionBuffer.PrizeDistribution[] memory _prizeDistributions = new IPrizeDistributionBuffer.PrizeDistribution[]( drawIdsLength ); for (uint256 i = 0; i < drawIdsLength; i++) { _prizeDistributions[i] = _getPrizeDistribution(buffer, _drawIds[i]); } return _prizeDistributions; } /// @inheritdoc IPrizeDistributionBuffer function getPrizeDistributionCount() external view override returns (uint32) { DrawRingBufferLib.Buffer memory buffer = bufferMetadata; if (buffer.lastDrawId == 0) { return 0; } uint32 bufferNextIndex = buffer.nextIndex; // If the buffer is full return the cardinality, else retun the nextIndex if (prizeDistributionRingBuffer[bufferNextIndex].matchCardinality != 0) { return buffer.cardinality; } else { return bufferNextIndex; } } /// @inheritdoc IPrizeDistributionBuffer function getNewestPrizeDistribution() external view override returns (IPrizeDistributionBuffer.PrizeDistribution memory prizeDistribution, uint32 drawId) { DrawRingBufferLib.Buffer memory buffer = bufferMetadata; return (prizeDistributionRingBuffer[buffer.getIndex(buffer.lastDrawId)], buffer.lastDrawId); } /// @inheritdoc IPrizeDistributionBuffer function getOldestPrizeDistribution() external view override returns (IPrizeDistributionBuffer.PrizeDistribution memory prizeDistribution, uint32 drawId) { DrawRingBufferLib.Buffer memory buffer = bufferMetadata; // if the ring buffer is full, the oldest is at the nextIndex prizeDistribution = prizeDistributionRingBuffer[buffer.nextIndex]; // The PrizeDistribution at index 0 IS by default the oldest prizeDistribution. if (buffer.lastDrawId == 0) { drawId = 0; // return 0 to indicate no prizeDistribution ring buffer history } else if (prizeDistribution.bitRangeSize == 0) { // IF the next PrizeDistribution.bitRangeSize == 0 the ring buffer HAS NOT looped around so the oldest is the first entry. prizeDistribution = prizeDistributionRingBuffer[0]; drawId = (buffer.lastDrawId + 1) - buffer.nextIndex; } else { // Calculates the drawId using the ring buffer cardinality // Sequential drawIds are gauranteed by DrawRingBufferLib.push() drawId = (buffer.lastDrawId + 1) - buffer.cardinality; } } /// @inheritdoc IPrizeDistributionBuffer function pushPrizeDistribution( uint32 _drawId, IPrizeDistributionBuffer.PrizeDistribution calldata _prizeDistribution ) external override onlyManagerOrOwner returns (bool) { return _pushPrizeDistribution(_drawId, _prizeDistribution); } /// @inheritdoc IPrizeDistributionBuffer function setPrizeDistribution( uint32 _drawId, IPrizeDistributionBuffer.PrizeDistribution calldata _prizeDistribution ) external override onlyOwner returns (uint32) { DrawRingBufferLib.Buffer memory buffer = bufferMetadata; uint32 index = buffer.getIndex(_drawId); prizeDistributionRingBuffer[index] = _prizeDistribution; emit PrizeDistributionSet(_drawId, _prizeDistribution); return _drawId; } /* ============ Internal Functions ============ */ /** * @notice Gets the PrizeDistributionBuffer for a drawId * @param _buffer DrawRingBufferLib.Buffer * @param _drawId drawId */ function _getPrizeDistribution(DrawRingBufferLib.Buffer memory _buffer, uint32 _drawId) internal view returns (IPrizeDistributionBuffer.PrizeDistribution memory) { return prizeDistributionRingBuffer[_buffer.getIndex(_drawId)]; } /** * @notice Set newest PrizeDistributionBuffer in ring buffer storage. * @param _drawId drawId * @param _prizeDistribution PrizeDistributionBuffer struct */ function _pushPrizeDistribution( uint32 _drawId, IPrizeDistributionBuffer.PrizeDistribution calldata _prizeDistribution ) internal returns (bool) { require(_drawId > 0, "DrawCalc/draw-id-gt-0"); require(_prizeDistribution.matchCardinality > 0, "DrawCalc/matchCardinality-gt-0"); require( _prizeDistribution.bitRangeSize <= 256 / _prizeDistribution.matchCardinality, "DrawCalc/bitRangeSize-too-large" ); require(_prizeDistribution.bitRangeSize > 0, "DrawCalc/bitRangeSize-gt-0"); require(_prizeDistribution.maxPicksPerUser > 0, "DrawCalc/maxPicksPerUser-gt-0"); require(_prizeDistribution.expiryDuration > 0, "DrawCalc/expiryDuration-gt-0"); // ensure that the sum of the tiers are not gt 100% uint256 sumTotalTiers = 0; uint256 tiersLength = _prizeDistribution.tiers.length; for (uint256 index = 0; index < tiersLength; index++) { uint256 tier = _prizeDistribution.tiers[index]; sumTotalTiers += tier; } // Each tier amount stored as uint32 - summed can't exceed 1e9 require(sumTotalTiers <= TIERS_CEILING, "DrawCalc/tiers-gt-100%"); DrawRingBufferLib.Buffer memory buffer = bufferMetadata; // store the PrizeDistribution in the ring buffer prizeDistributionRingBuffer[buffer.nextIndex] = _prizeDistribution; // update the ring buffer data bufferMetadata = buffer.push(_drawId); emit PrizeDistributionSet(_drawId, _prizeDistribution); return true; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@pooltogether/owner-manager-contracts/contracts/Ownable.sol"; import "./interfaces/IPrizeDistributor.sol"; import "./interfaces/IDrawCalculator.sol"; /** * @title PoolTogether V4 PrizeDistributor * @author PoolTogether Inc Team * @notice The PrizeDistributor contract holds Tickets (captured interest) and distributes tickets to users with winning draw claims. PrizeDistributor uses an external IDrawCalculator to validate a users draw claim, before awarding payouts. To prevent users from reclaiming prizes, a payout history for each draw claim is mapped to user accounts. Reclaiming a draw can occur if an "optimal" prize was not included in previous claim pick indices and the new claims updated payout is greater then the previous prize distributor claim payout. */ contract PrizeDistributor is IPrizeDistributor, Ownable { using SafeERC20 for IERC20; /* ============ Global Variables ============ */ /// @notice DrawCalculator address IDrawCalculator internal drawCalculator; /// @notice Token address IERC20 internal immutable token; /// @notice Maps users => drawId => paid out balance mapping(address => mapping(uint256 => uint256)) internal userDrawPayouts; /* ============ Initialize ============ */ /** * @notice Initialize PrizeDistributor smart contract. * @param _owner Owner address * @param _token Token address * @param _drawCalculator DrawCalculator address */ constructor( address _owner, IERC20 _token, IDrawCalculator _drawCalculator ) Ownable(_owner) { _setDrawCalculator(_drawCalculator); require(address(_token) != address(0), "PrizeDistributor/token-not-zero-address"); token = _token; emit TokenSet(_token); } /* ============ External Functions ============ */ /// @inheritdoc IPrizeDistributor function claim( address _user, uint32[] calldata _drawIds, bytes calldata _data ) external override returns (uint256) { uint256 totalPayout; (uint256[] memory drawPayouts, ) = drawCalculator.calculate(_user, _drawIds, _data); // neglect the prizeCounts since we are not interested in them here uint256 drawPayoutsLength = drawPayouts.length; for (uint256 payoutIndex = 0; payoutIndex < drawPayoutsLength; payoutIndex++) { uint32 drawId = _drawIds[payoutIndex]; uint256 payout = drawPayouts[payoutIndex]; uint256 oldPayout = _getDrawPayoutBalanceOf(_user, drawId); uint256 payoutDiff = 0; // helpfully short-circuit, in case the user screwed something up. require(payout > oldPayout, "PrizeDistributor/zero-payout"); unchecked { payoutDiff = payout - oldPayout; } _setDrawPayoutBalanceOf(_user, drawId, payout); totalPayout += payoutDiff; emit ClaimedDraw(_user, drawId, payoutDiff); } _awardPayout(_user, totalPayout); return totalPayout; } /// @inheritdoc IPrizeDistributor function withdrawERC20( IERC20 _erc20Token, address _to, uint256 _amount ) external override onlyOwner returns (bool) { require(_to != address(0), "PrizeDistributor/recipient-not-zero-address"); require(address(_erc20Token) != address(0), "PrizeDistributor/ERC20-not-zero-address"); _erc20Token.safeTransfer(_to, _amount); emit ERC20Withdrawn(_erc20Token, _to, _amount); return true; } /// @inheritdoc IPrizeDistributor function getDrawCalculator() external view override returns (IDrawCalculator) { return drawCalculator; } /// @inheritdoc IPrizeDistributor function getDrawPayoutBalanceOf(address _user, uint32 _drawId) external view override returns (uint256) { return _getDrawPayoutBalanceOf(_user, _drawId); } /// @inheritdoc IPrizeDistributor function getToken() external view override returns (IERC20) { return token; } /// @inheritdoc IPrizeDistributor function setDrawCalculator(IDrawCalculator _newCalculator) external override onlyOwner returns (IDrawCalculator) { _setDrawCalculator(_newCalculator); return _newCalculator; } /* ============ Internal Functions ============ */ function _getDrawPayoutBalanceOf(address _user, uint32 _drawId) internal view returns (uint256) { return userDrawPayouts[_user][_drawId]; } function _setDrawPayoutBalanceOf( address _user, uint32 _drawId, uint256 _payout ) internal { userDrawPayouts[_user][_drawId] = _payout; } /** * @notice Sets DrawCalculator reference for individual draw id. * @param _newCalculator DrawCalculator address */ function _setDrawCalculator(IDrawCalculator _newCalculator) internal { require(address(_newCalculator) != address(0), "PrizeDistributor/calc-not-zero"); drawCalculator = _newCalculator; emit DrawCalculatorSet(_newCalculator); } /** * @notice Transfer claimed draw(s) total payout to user. * @param _to User address * @param _amount Transfer amount */ function _awardPayout(address _to, uint256 _amount) internal { token.safeTransfer(_to, _amount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @title IControlledToken * @author PoolTogether Inc Team * @notice ERC20 Tokens with a controller for minting & burning. */ interface IControlledToken is IERC20 { /** @notice Interface to the contract responsible for controlling mint/burn */ function controller() external view returns (address); /** * @notice Allows the controller to mint tokens for a user account * @dev May be overridden to provide more granular control over minting * @param user Address of the receiver of the minted tokens * @param amount Amount of tokens to mint */ function controllerMint(address user, uint256 amount) external; /** * @notice Allows the controller to burn tokens from a user account * @dev May be overridden to provide more granular control over burning * @param user Address of the holder account to burn tokens from * @param amount Amount of tokens to burn */ function controllerBurn(address user, uint256 amount) external; /** * @notice Allows an operator via the controller to burn tokens on behalf of a user account * @dev May be overridden to provide more granular control over operator-burning * @param operator Address of the operator performing the burn action via the controller contract * @param user Address of the holder account to burn tokens from * @param amount Amount of tokens to burn */ function controllerBurnFrom( address operator, address user, uint256 amount ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "@pooltogether/pooltogether-rng-contracts/contracts/RNGInterface.sol"; import "./IDrawBuffer.sol"; /** @title IDrawBeacon * @author PoolTogether Inc Team * @notice The DrawBeacon interface. */ interface IDrawBeacon { /// @notice Draw struct created every draw /// @param winningRandomNumber The random number returned from the RNG service /// @param drawId The monotonically increasing drawId for each draw /// @param timestamp Unix timestamp of the draw. Recorded when the draw is created by the DrawBeacon. /// @param beaconPeriodStartedAt Unix timestamp of when the draw started /// @param beaconPeriodSeconds Unix timestamp of the beacon draw period for this draw. struct Draw { uint256 winningRandomNumber; uint32 drawId; uint64 timestamp; uint64 beaconPeriodStartedAt; uint32 beaconPeriodSeconds; } /** * @notice Emit when a new DrawBuffer has been set. * @param newDrawBuffer The new DrawBuffer address */ event DrawBufferUpdated(IDrawBuffer indexed newDrawBuffer); /** * @notice Emit when a draw has opened. * @param startedAt Start timestamp */ event BeaconPeriodStarted(uint64 indexed startedAt); /** * @notice Emit when a draw has started. * @param rngRequestId draw id * @param rngLockBlock Block when draw becomes invalid */ event DrawStarted(uint32 indexed rngRequestId, uint32 rngLockBlock); /** * @notice Emit when a draw has been cancelled. * @param rngRequestId draw id * @param rngLockBlock Block when draw becomes invalid */ event DrawCancelled(uint32 indexed rngRequestId, uint32 rngLockBlock); /** * @notice Emit when a draw has been completed. * @param randomNumber Random number generated from draw */ event DrawCompleted(uint256 randomNumber); /** * @notice Emit when a RNG service address is set. * @param rngService RNG service address */ event RngServiceUpdated(RNGInterface indexed rngService); /** * @notice Emit when a draw timeout param is set. * @param rngTimeout draw timeout param in seconds */ event RngTimeoutSet(uint32 rngTimeout); /** * @notice Emit when the drawPeriodSeconds is set. * @param drawPeriodSeconds Time between draw */ event BeaconPeriodSecondsUpdated(uint32 drawPeriodSeconds); /** * @notice Returns the number of seconds remaining until the beacon period can be complete. * @return The number of seconds remaining until the beacon period can be complete. */ function beaconPeriodRemainingSeconds() external view returns (uint64); /** * @notice Returns the timestamp at which the beacon period ends * @return The timestamp at which the beacon period ends. */ function beaconPeriodEndAt() external view returns (uint64); /** * @notice Returns whether a Draw can be started. * @return True if a Draw can be started, false otherwise. */ function canStartDraw() external view returns (bool); /** * @notice Returns whether a Draw can be completed. * @return True if a Draw can be completed, false otherwise. */ function canCompleteDraw() external view returns (bool); /** * @notice Calculates when the next beacon period will start. * @param time The timestamp to use as the current time * @return The timestamp at which the next beacon period would start */ function calculateNextBeaconPeriodStartTime(uint64 time) external view returns (uint64); /** * @notice Can be called by anyone to cancel the draw request if the RNG has timed out. */ function cancelDraw() external; /** * @notice Completes the Draw (RNG) request and pushes a Draw onto DrawBuffer. */ function completeDraw() external; /** * @notice Returns the block number that the current RNG request has been locked to. * @return The block number that the RNG request is locked to */ function getLastRngLockBlock() external view returns (uint32); /** * @notice Returns the current RNG Request ID. * @return The current Request ID */ function getLastRngRequestId() external view returns (uint32); /** * @notice Returns whether the beacon period is over * @return True if the beacon period is over, false otherwise */ function isBeaconPeriodOver() external view returns (bool); /** * @notice Returns whether the random number request has completed. * @return True if a random number request has completed, false otherwise. */ function isRngCompleted() external view returns (bool); /** * @notice Returns whether a random number has been requested * @return True if a random number has been requested, false otherwise. */ function isRngRequested() external view returns (bool); /** * @notice Returns whether the random number request has timed out. * @return True if a random number request has timed out, false otherwise. */ function isRngTimedOut() external view returns (bool); /** * @notice Allows the owner to set the beacon period in seconds. * @param beaconPeriodSeconds The new beacon period in seconds. Must be greater than zero. */ function setBeaconPeriodSeconds(uint32 beaconPeriodSeconds) external; /** * @notice Allows the owner to set the RNG request timeout in seconds. This is the time that must elapsed before the RNG request can be cancelled and the pool unlocked. * @param rngTimeout The RNG request timeout in seconds. */ function setRngTimeout(uint32 rngTimeout) external; /** * @notice Sets the RNG service that the Prize Strategy is connected to * @param rngService The address of the new RNG service interface */ function setRngService(RNGInterface rngService) external; /** * @notice Starts the Draw process by starting random number request. The previous beacon period must have ended. * @dev The RNG-Request-Fee is expected to be held within this contract before calling this function */ function startDraw() external; /** * @notice Set global DrawBuffer variable. * @dev All subsequent Draw requests/completions will be pushed to the new DrawBuffer. * @param newDrawBuffer DrawBuffer address * @return DrawBuffer */ function setDrawBuffer(IDrawBuffer newDrawBuffer) external returns (IDrawBuffer); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "../interfaces/IDrawBeacon.sol"; /** @title IDrawBuffer * @author PoolTogether Inc Team * @notice The DrawBuffer interface. */ interface IDrawBuffer { /** * @notice Emit when a new draw has been created. * @param drawId Draw id * @param draw The Draw struct */ event DrawSet(uint32 indexed drawId, IDrawBeacon.Draw draw); /** * @notice Read a ring buffer cardinality * @return Ring buffer cardinality */ function getBufferCardinality() external view returns (uint32); /** * @notice Read a Draw from the draws ring buffer. * @dev Read a Draw using the Draw.drawId to calculate position in the draws ring buffer. * @param drawId Draw.drawId * @return IDrawBeacon.Draw */ function getDraw(uint32 drawId) external view returns (IDrawBeacon.Draw memory); /** * @notice Read multiple Draws from the draws ring buffer. * @dev Read multiple Draws using each drawId to calculate position in the draws ring buffer. * @param drawIds Array of drawIds * @return IDrawBeacon.Draw[] */ function getDraws(uint32[] calldata drawIds) external view returns (IDrawBeacon.Draw[] memory); /** * @notice Gets the number of Draws held in the draw ring buffer. * @dev If no Draws have been pushed, it will return 0. * @dev If the ring buffer is full, it will return the cardinality. * @dev Otherwise, it will return the NewestDraw index + 1. * @return Number of Draws held in the draw ring buffer. */ function getDrawCount() external view returns (uint32); /** * @notice Read newest Draw from draws ring buffer. * @dev Uses the nextDrawIndex to calculate the most recently added Draw. * @return IDrawBeacon.Draw */ function getNewestDraw() external view returns (IDrawBeacon.Draw memory); /** * @notice Read oldest Draw from draws ring buffer. * @dev Finds the oldest Draw by comparing and/or diffing totalDraws with the cardinality. * @return IDrawBeacon.Draw */ function getOldestDraw() external view returns (IDrawBeacon.Draw memory); /** * @notice Push Draw onto draws ring buffer history. * @dev Push new draw onto draws history via authorized manager or owner. * @param draw IDrawBeacon.Draw * @return Draw.drawId */ function pushDraw(IDrawBeacon.Draw calldata draw) external returns (uint32); /** * @notice Set existing Draw in draws ring buffer with new parameters. * @dev Updating a Draw should be used sparingly and only in the event an incorrect Draw parameter has been stored. * @param newDraw IDrawBeacon.Draw * @return Draw.drawId */ function setDraw(IDrawBeacon.Draw calldata newDraw) external returns (uint32); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "./ITicket.sol"; import "./IDrawBuffer.sol"; import "../PrizeDistributionBuffer.sol"; import "../PrizeDistributor.sol"; /** * @title PoolTogether V4 IDrawCalculator * @author PoolTogether Inc Team * @notice The DrawCalculator interface. */ interface IDrawCalculator { struct PickPrize { bool won; uint8 tierIndex; } ///@notice Emitted when the contract is initialized event Deployed( ITicket indexed ticket, IDrawBuffer indexed drawBuffer, IPrizeDistributionBuffer indexed prizeDistributionBuffer ); ///@notice Emitted when the prizeDistributor is set/updated event PrizeDistributorSet(PrizeDistributor indexed prizeDistributor); /** * @notice Calculates the prize amount for a user for Multiple Draws. Typically called by a PrizeDistributor. * @param user User for which to calculate prize amount. * @param drawIds drawId array for which to calculate prize amounts for. * @param data The ABI encoded pick indices for all Draws. Expected to be winning picks. Pick indices must be less than the totalUserPicks. * @return List of awardable prize amounts ordered by drawId. */ function calculate( address user, uint32[] calldata drawIds, bytes calldata data ) external view returns (uint256[] memory, bytes memory); /** * @notice Read global DrawBuffer variable. * @return IDrawBuffer */ function getDrawBuffer() external view returns (IDrawBuffer); /** * @notice Read global DrawBuffer variable. * @return IDrawBuffer */ function getPrizeDistributionBuffer() external view returns (IPrizeDistributionBuffer); /** * @notice Returns a users balances expressed as a fraction of the total supply over time. * @param user The users address * @param drawIds The drawsId to consider * @return Array of balances */ function getNormalizedBalancesForDrawIds(address user, uint32[] calldata drawIds) external view returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; /** @title IPrizeDistributionBuffer * @author PoolTogether Inc Team * @notice The PrizeDistributionBuffer interface. */ interface IPrizeDistributionBuffer { ///@notice PrizeDistribution struct created every draw ///@param bitRangeSize Decimal representation of bitRangeSize ///@param matchCardinality The number of numbers to consider in the 256 bit random number. Must be > 1 and < 256/bitRangeSize. ///@param startTimestampOffset The starting time offset in seconds from which Ticket balances are calculated. ///@param endTimestampOffset The end time offset in seconds from which Ticket balances are calculated. ///@param maxPicksPerUser Maximum number of picks a user can make in this draw ///@param expiryDuration Length of time in seconds the PrizeDistribution is valid for. Relative to the Draw.timestamp. ///@param numberOfPicks Number of picks this draw has (may vary across networks according to how much the network has contributed to the Reserve) ///@param tiers Array of prize tiers percentages, expressed in fraction form with base 1e9. Ordering: index0: grandPrize, index1: runnerUp, etc. ///@param prize Total prize amount available in this draw calculator for this draw (may vary from across networks) struct PrizeDistribution { uint8 bitRangeSize; uint8 matchCardinality; uint32 startTimestampOffset; uint32 endTimestampOffset; uint32 maxPicksPerUser; uint32 expiryDuration; uint104 numberOfPicks; uint32[16] tiers; uint256 prize; } /** * @notice Emit when PrizeDistribution is set. * @param drawId Draw id * @param prizeDistribution IPrizeDistributionBuffer.PrizeDistribution */ event PrizeDistributionSet( uint32 indexed drawId, IPrizeDistributionBuffer.PrizeDistribution prizeDistribution ); /** * @notice Read a ring buffer cardinality * @return Ring buffer cardinality */ function getBufferCardinality() external view returns (uint32); /** * @notice Read newest PrizeDistribution from prize distributions ring buffer. * @dev Uses nextDrawIndex to calculate the most recently added PrizeDistribution. * @return prizeDistribution * @return drawId */ function getNewestPrizeDistribution() external view returns (IPrizeDistributionBuffer.PrizeDistribution memory prizeDistribution, uint32 drawId); /** * @notice Read oldest PrizeDistribution from prize distributions ring buffer. * @dev Finds the oldest Draw by buffer.nextIndex and buffer.lastDrawId * @return prizeDistribution * @return drawId */ function getOldestPrizeDistribution() external view returns (IPrizeDistributionBuffer.PrizeDistribution memory prizeDistribution, uint32 drawId); /** * @notice Gets PrizeDistribution list from array of drawIds * @param drawIds drawIds to get PrizeDistribution for * @return prizeDistributionList */ function getPrizeDistributions(uint32[] calldata drawIds) external view returns (IPrizeDistributionBuffer.PrizeDistribution[] memory); /** * @notice Gets the PrizeDistributionBuffer for a drawId * @param drawId drawId * @return prizeDistribution */ function getPrizeDistribution(uint32 drawId) external view returns (IPrizeDistributionBuffer.PrizeDistribution memory); /** * @notice Gets the number of PrizeDistributions stored in the prize distributions ring buffer. * @dev If no Draws have been pushed, it will return 0. * @dev If the ring buffer is full, it will return the cardinality. * @dev Otherwise, it will return the NewestPrizeDistribution index + 1. * @return Number of PrizeDistributions stored in the prize distributions ring buffer. */ function getPrizeDistributionCount() external view returns (uint32); /** * @notice Adds new PrizeDistribution record to ring buffer storage. * @dev Only callable by the owner or manager * @param drawId Draw ID linked to PrizeDistribution parameters * @param prizeDistribution PrizeDistribution parameters struct */ function pushPrizeDistribution( uint32 drawId, IPrizeDistributionBuffer.PrizeDistribution calldata prizeDistribution ) external returns (bool); /** * @notice Sets existing PrizeDistribution with new PrizeDistribution parameters in ring buffer storage. * @dev Retroactively updates an existing PrizeDistribution and should be thought of as a "safety" fallback. If the manager is setting invalid PrizeDistribution parameters the Owner can update the invalid parameters with correct parameters. * @return drawId */ function setPrizeDistribution(uint32 drawId, IPrizeDistributionBuffer.PrizeDistribution calldata draw) external returns (uint32); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IDrawBuffer.sol"; import "./IDrawCalculator.sol"; /** @title IPrizeDistributor * @author PoolTogether Inc Team * @notice The PrizeDistributor interface. */ interface IPrizeDistributor { /** * @notice Emit when user has claimed token from the PrizeDistributor. * @param user User address receiving draw claim payouts * @param drawId Draw id that was paid out * @param payout Payout for draw */ event ClaimedDraw(address indexed user, uint32 indexed drawId, uint256 payout); /** * @notice Emit when DrawCalculator is set. * @param calculator DrawCalculator address */ event DrawCalculatorSet(IDrawCalculator indexed calculator); /** * @notice Emit when Token is set. * @param token Token address */ event TokenSet(IERC20 indexed token); /** * @notice Emit when ERC20 tokens are withdrawn. * @param token ERC20 token transferred. * @param to Address that received funds. * @param amount Amount of tokens transferred. */ event ERC20Withdrawn(IERC20 indexed token, address indexed to, uint256 amount); /** * @notice Claim prize payout(s) by submitting valud drawId(s) and winning pick indice(s). The user address is used as the "seed" phrase to generate random numbers. * @dev The claim function is public and any wallet may execute claim on behalf of another user. Prizes are always paid out to the designated user account and not the caller (msg.sender). Claiming prizes is not limited to a single transaction. Reclaiming can be executed subsequentially if an "optimal" prize was not included in previous claim pick indices. The payout difference for the new claim is calculated during the award process and transfered to user. * @param user Address of user to claim awards for. Does NOT need to be msg.sender * @param drawIds Draw IDs from global DrawBuffer reference * @param data The data to pass to the draw calculator * @return Total claim payout. May include calcuations from multiple draws. */ function claim( address user, uint32[] calldata drawIds, bytes calldata data ) external returns (uint256); /** * @notice Read global DrawCalculator address. * @return IDrawCalculator */ function getDrawCalculator() external view returns (IDrawCalculator); /** * @notice Get the amount that a user has already been paid out for a draw * @param user User address * @param drawId Draw ID */ function getDrawPayoutBalanceOf(address user, uint32 drawId) external view returns (uint256); /** * @notice Read global Ticket address. * @return IERC20 */ function getToken() external view returns (IERC20); /** * @notice Sets DrawCalculator reference contract. * @param newCalculator DrawCalculator address * @return New DrawCalculator address */ function setDrawCalculator(IDrawCalculator newCalculator) external returns (IDrawCalculator); /** * @notice Transfer ERC20 tokens out of contract to recipient address. * @dev Only callable by contract owner. * @param token ERC20 token to transfer. * @param to Recipient of the tokens. * @param amount Amount of tokens to transfer. * @return true if operation is successful. */ function withdrawERC20( IERC20 token, address to, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "../libraries/TwabLib.sol"; import "./IControlledToken.sol"; interface ITicket is IControlledToken { /** * @notice A struct containing details for an Account. * @param balance The current balance for an Account. * @param nextTwabIndex The next available index to store a new twab. * @param cardinality The number of recorded twabs (plus one!). */ struct AccountDetails { uint224 balance; uint16 nextTwabIndex; uint16 cardinality; } /** * @notice Combines account details with their twab history. * @param details The account details. * @param twabs The history of twabs for this account. */ struct Account { AccountDetails details; ObservationLib.Observation[65535] twabs; } /** * @notice Emitted when TWAB balance has been delegated to another user. * @param delegator Address of the delegator. * @param delegate Address of the delegate. */ event Delegated(address indexed delegator, address indexed delegate); /** * @notice Emitted when ticket is initialized. * @param name Ticket name (eg: PoolTogether Dai Ticket (Compound)). * @param symbol Ticket symbol (eg: PcDAI). * @param decimals Ticket decimals. * @param controller Token controller address. */ event TicketInitialized(string name, string symbol, uint8 decimals, address indexed controller); /** * @notice Emitted when a new TWAB has been recorded. * @param delegate The recipient of the ticket power (may be the same as the user). * @param newTwab Updated TWAB of a ticket holder after a successful TWAB recording. */ event NewUserTwab( address indexed delegate, ObservationLib.Observation newTwab ); /** * @notice Emitted when a new total supply TWAB has been recorded. * @param newTotalSupplyTwab Updated TWAB of tickets total supply after a successful total supply TWAB recording. */ event NewTotalSupplyTwab(ObservationLib.Observation newTotalSupplyTwab); /** * @notice Retrieves the address of the delegate to whom `user` has delegated their tickets. * @dev Address of the delegate will be the zero address if `user` has not delegated their tickets. * @param user Address of the delegator. * @return Address of the delegate. */ function delegateOf(address user) external view returns (address); /** * @notice Delegate time-weighted average balances to an alternative address. * @dev Transfers (including mints) trigger the storage of a TWAB in delegate(s) account, instead of the targetted sender and/or recipient address(s). * @dev To reset the delegate, pass the zero address (0x000.000) as `to` parameter. * @dev Current delegate address should be different from the new delegate address `to`. * @param to Recipient of delegated TWAB. */ function delegate(address to) external; /** * @notice Allows the controller to delegate on a users behalf. * @param user The user for whom to delegate * @param delegate The new delegate */ function controllerDelegateFor(address user, address delegate) external; /** * @notice Allows a user to delegate via signature * @param user The user who is delegating * @param delegate The new delegate * @param deadline The timestamp by which this must be submitted * @param v The v portion of the ECDSA sig * @param r The r portion of the ECDSA sig * @param s The s portion of the ECDSA sig */ function delegateWithSignature( address user, address delegate, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @notice Gets a users twab context. This is a struct with their balance, next twab index, and cardinality. * @param user The user for whom to fetch the TWAB context. * @return The TWAB context, which includes { balance, nextTwabIndex, cardinality } */ function getAccountDetails(address user) external view returns (TwabLib.AccountDetails memory); /** * @notice Gets the TWAB at a specific index for a user. * @param user The user for whom to fetch the TWAB. * @param index The index of the TWAB to fetch. * @return The TWAB, which includes the twab amount and the timestamp. */ function getTwab(address user, uint16 index) external view returns (ObservationLib.Observation memory); /** * @notice Retrieves `user` TWAB balance. * @param user Address of the user whose TWAB is being fetched. * @param timestamp Timestamp at which we want to retrieve the TWAB balance. * @return The TWAB balance at the given timestamp. */ function getBalanceAt(address user, uint64 timestamp) external view returns (uint256); /** * @notice Retrieves `user` TWAB balances. * @param user Address of the user whose TWABs are being fetched. * @param timestamps Timestamps range at which we want to retrieve the TWAB balances. * @return `user` TWAB balances. */ function getBalancesAt(address user, uint64[] calldata timestamps) external view returns (uint256[] memory); /** * @notice Retrieves the average balance held by a user for a given time frame. * @param user The user whose balance is checked. * @param startTime The start time of the time frame. * @param endTime The end time of the time frame. * @return The average balance that the user held during the time frame. */ function getAverageBalanceBetween( address user, uint64 startTime, uint64 endTime ) external view returns (uint256); /** * @notice Retrieves the average balances held by a user for a given time frame. * @param user The user whose balance is checked. * @param startTimes The start time of the time frame. * @param endTimes The end time of the time frame. * @return The average balance that the user held during the time frame. */ function getAverageBalancesBetween( address user, uint64[] calldata startTimes, uint64[] calldata endTimes ) external view returns (uint256[] memory); /** * @notice Retrieves the total supply TWAB balance at the given timestamp. * @param timestamp Timestamp at which we want to retrieve the total supply TWAB balance. * @return The total supply TWAB balance at the given timestamp. */ function getTotalSupplyAt(uint64 timestamp) external view returns (uint256); /** * @notice Retrieves the total supply TWAB balance between the given timestamps range. * @param timestamps Timestamps range at which we want to retrieve the total supply TWAB balance. * @return Total supply TWAB balances. */ function getTotalSuppliesAt(uint64[] calldata timestamps) external view returns (uint256[] memory); /** * @notice Retrieves the average total supply balance for a set of given time frames. * @param startTimes Array of start times. * @param endTimes Array of end times. * @return The average total supplies held during the time frame. */ function getAverageTotalSuppliesBetween( uint64[] calldata startTimes, uint64[] calldata endTimes ) external view returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "./RingBufferLib.sol"; /// @title Library for creating and managing a draw ring buffer. library DrawRingBufferLib { /// @notice Draw buffer struct. struct Buffer { uint32 lastDrawId; uint32 nextIndex; uint32 cardinality; } /// @notice Helper function to know if the draw ring buffer has been initialized. /// @dev since draws start at 1 and are monotonically increased, we know we are uninitialized if nextIndex = 0 and lastDrawId = 0. /// @param _buffer The buffer to check. function isInitialized(Buffer memory _buffer) internal pure returns (bool) { return !(_buffer.nextIndex == 0 && _buffer.lastDrawId == 0); } /// @notice Push a draw to the buffer. /// @param _buffer The buffer to push to. /// @param _drawId The drawID to push. /// @return The new buffer. function push(Buffer memory _buffer, uint32 _drawId) internal pure returns (Buffer memory) { require(!isInitialized(_buffer) || _drawId == _buffer.lastDrawId + 1, "DRB/must-be-contig"); return Buffer({ lastDrawId: _drawId, nextIndex: uint32(RingBufferLib.nextIndex(_buffer.nextIndex, _buffer.cardinality)), cardinality: _buffer.cardinality }); } /// @notice Get draw ring buffer index pointer. /// @param _buffer The buffer to get the `nextIndex` from. /// @param _drawId The draw id to get the index for. /// @return The draw ring buffer index pointer. function getIndex(Buffer memory _buffer, uint32 _drawId) internal pure returns (uint32) { require(isInitialized(_buffer) && _drawId <= _buffer.lastDrawId, "DRB/future-draw"); uint32 indexOffset = _buffer.lastDrawId - _drawId; require(indexOffset < _buffer.cardinality, "DRB/expired-draw"); uint256 mostRecent = RingBufferLib.newestIndex(_buffer.nextIndex, _buffer.cardinality); return uint32(RingBufferLib.offset(uint32(mostRecent), indexOffset, _buffer.cardinality)); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library ExtendedSafeCastLib { /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits */ function toUint208(uint256 _value) internal pure returns (uint208) { require(_value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits"); return uint208(_value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 _value) internal pure returns (uint224) { require(_value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(_value); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "./OverflowSafeComparatorLib.sol"; import "./RingBufferLib.sol"; /** * @title Observation Library * @notice This library allows one to store an array of timestamped values and efficiently binary search them. * @dev Largely pulled from Uniswap V3 Oracle.sol: https://github.com/Uniswap/v3-core/blob/c05a0e2c8c08c460fb4d05cfdda30b3ad8deeaac/contracts/libraries/Oracle.sol * @author PoolTogether Inc. */ library ObservationLib { using OverflowSafeComparatorLib for uint32; using SafeCast for uint256; /// @notice The maximum number of observations uint24 public constant MAX_CARDINALITY = 16777215; // 2**24 /** * @notice Observation, which includes an amount and timestamp. * @param amount `amount` at `timestamp`. * @param timestamp Recorded `timestamp`. */ struct Observation { uint224 amount; uint32 timestamp; } /** * @notice Fetches Observations `beforeOrAt` and `atOrAfter` a `_target`, eg: where [`beforeOrAt`, `atOrAfter`] is satisfied. * The result may be the same Observation, or adjacent Observations. * @dev The answer must be contained in the array used when the target is located within the stored Observation. * boundaries: older than the most recent Observation and younger, or the same age as, the oldest Observation. * @dev If `_newestObservationIndex` is less than `_oldestObservationIndex`, it means that we've wrapped around the circular buffer. * So the most recent observation will be at `_oldestObservationIndex + _cardinality - 1`, at the beginning of the circular buffer. * @param _observations List of Observations to search through. * @param _newestObservationIndex Index of the newest Observation. Right side of the circular buffer. * @param _oldestObservationIndex Index of the oldest Observation. Left side of the circular buffer. * @param _target Timestamp at which we are searching the Observation. * @param _cardinality Cardinality of the circular buffer we are searching through. * @param _time Timestamp at which we perform the binary search. * @return beforeOrAt Observation recorded before, or at, the target. * @return atOrAfter Observation recorded at, or after, the target. */ function binarySearch( Observation[MAX_CARDINALITY] storage _observations, uint24 _newestObservationIndex, uint24 _oldestObservationIndex, uint32 _target, uint24 _cardinality, uint32 _time ) internal view returns (Observation memory beforeOrAt, Observation memory atOrAfter) { uint256 leftSide = _oldestObservationIndex; uint256 rightSide = _newestObservationIndex < leftSide ? leftSide + _cardinality - 1 : _newestObservationIndex; uint256 currentIndex; while (true) { // We start our search in the middle of the `leftSide` and `rightSide`. // After each iteration, we narrow down the search to the left or the right side while still starting our search in the middle. currentIndex = (leftSide + rightSide) / 2; beforeOrAt = _observations[uint24(RingBufferLib.wrap(currentIndex, _cardinality))]; uint32 beforeOrAtTimestamp = beforeOrAt.timestamp; // We've landed on an uninitialized timestamp, keep searching higher (more recently). if (beforeOrAtTimestamp == 0) { leftSide = currentIndex + 1; continue; } atOrAfter = _observations[uint24(RingBufferLib.nextIndex(currentIndex, _cardinality))]; bool targetAtOrAfter = beforeOrAtTimestamp.lte(_target, _time); // Check if we've found the corresponding Observation. if (targetAtOrAfter && _target.lte(atOrAfter.timestamp, _time)) { break; } // If `beforeOrAtTimestamp` is greater than `_target`, then we keep searching lower. To the left of the current index. if (!targetAtOrAfter) { rightSide = currentIndex - 1; } else { // Otherwise, we keep searching higher. To the left of the current index. leftSide = currentIndex + 1; } } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; /// @title OverflowSafeComparatorLib library to share comparator functions between contracts /// @dev Code taken from Uniswap V3 Oracle.sol: https://github.com/Uniswap/v3-core/blob/3e88af408132fc957e3e406f65a0ce2b1ca06c3d/contracts/libraries/Oracle.sol /// @author PoolTogether Inc. library OverflowSafeComparatorLib { /// @notice 32-bit timestamps comparator. /// @dev safe for 0 or 1 overflows, `_a` and `_b` must be chronologically before or equal to time. /// @param _a A comparison timestamp from which to determine the relative position of `_timestamp`. /// @param _b Timestamp to compare against `_a`. /// @param _timestamp A timestamp truncated to 32 bits. /// @return bool Whether `_a` is chronologically < `_b`. function lt( uint32 _a, uint32 _b, uint32 _timestamp ) internal pure returns (bool) { // No need to adjust if there hasn't been an overflow if (_a <= _timestamp && _b <= _timestamp) return _a < _b; uint256 aAdjusted = _a > _timestamp ? _a : _a + 2**32; uint256 bAdjusted = _b > _timestamp ? _b : _b + 2**32; return aAdjusted < bAdjusted; } /// @notice 32-bit timestamps comparator. /// @dev safe for 0 or 1 overflows, `_a` and `_b` must be chronologically before or equal to time. /// @param _a A comparison timestamp from which to determine the relative position of `_timestamp`. /// @param _b Timestamp to compare against `_a`. /// @param _timestamp A timestamp truncated to 32 bits. /// @return bool Whether `_a` is chronologically <= `_b`. function lte( uint32 _a, uint32 _b, uint32 _timestamp ) internal pure returns (bool) { // No need to adjust if there hasn't been an overflow if (_a <= _timestamp && _b <= _timestamp) return _a <= _b; uint256 aAdjusted = _a > _timestamp ? _a : _a + 2**32; uint256 bAdjusted = _b > _timestamp ? _b : _b + 2**32; return aAdjusted <= bAdjusted; } /// @notice 32-bit timestamp subtractor /// @dev safe for 0 or 1 overflows, where `_a` and `_b` must be chronologically before or equal to time /// @param _a The subtraction left operand /// @param _b The subtraction right operand /// @param _timestamp The current time. Expected to be chronologically after both. /// @return The difference between a and b, adjusted for overflow function checkedSub( uint32 _a, uint32 _b, uint32 _timestamp ) internal pure returns (uint32) { // No need to adjust if there hasn't been an overflow if (_a <= _timestamp && _b <= _timestamp) return _a - _b; uint256 aAdjusted = _a > _timestamp ? _a : _a + 2**32; uint256 bAdjusted = _b > _timestamp ? _b : _b + 2**32; return uint32(aAdjusted - bAdjusted); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; library RingBufferLib { /** * @notice Returns wrapped TWAB index. * @dev In order to navigate the TWAB circular buffer, we need to use the modulo operator. * @dev For example, if `_index` is equal to 32 and the TWAB circular buffer is of `_cardinality` 32, * it will return 0 and will point to the first element of the array. * @param _index Index used to navigate through the TWAB circular buffer. * @param _cardinality TWAB buffer cardinality. * @return TWAB index. */ function wrap(uint256 _index, uint256 _cardinality) internal pure returns (uint256) { return _index % _cardinality; } /** * @notice Computes the negative offset from the given index, wrapped by the cardinality. * @dev We add `_cardinality` to `_index` to be able to offset even if `_amount` is superior to `_cardinality`. * @param _index The index from which to offset * @param _amount The number of indices to offset. This is subtracted from the given index. * @param _cardinality The number of elements in the ring buffer * @return Offsetted index. */ function offset( uint256 _index, uint256 _amount, uint256 _cardinality ) internal pure returns (uint256) { return wrap(_index + _cardinality - _amount, _cardinality); } /// @notice Returns the index of the last recorded TWAB /// @param _nextIndex The next available twab index. This will be recorded to next. /// @param _cardinality The cardinality of the TWAB history. /// @return The index of the last recorded TWAB function newestIndex(uint256 _nextIndex, uint256 _cardinality) internal pure returns (uint256) { if (_cardinality == 0) { return 0; } return wrap(_nextIndex + _cardinality - 1, _cardinality); } /// @notice Computes the ring buffer index that follows the given one, wrapped by cardinality /// @param _index The index to increment /// @param _cardinality The number of elements in the Ring Buffer /// @return The next index relative to the given index. Will wrap around to 0 if the next index == cardinality function nextIndex(uint256 _index, uint256 _cardinality) internal pure returns (uint256) { return wrap(_index + 1, _cardinality); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.6; import "./ExtendedSafeCastLib.sol"; import "./OverflowSafeComparatorLib.sol"; import "./RingBufferLib.sol"; import "./ObservationLib.sol"; /** * @title PoolTogether V4 TwabLib (Library) * @author PoolTogether Inc Team * @dev Time-Weighted Average Balance Library for ERC20 tokens. * @notice This TwabLib adds on-chain historical lookups to a user(s) time-weighted average balance. Each user is mapped to an Account struct containing the TWAB history (ring bufffer) and ring buffer parameters. Every token.transfer() creates a new TWAB checkpoint. The new TWAB checkpoint is stored in the circular ring buffer, as either a new checkpoint or rewriting a previous checkpoint with new parameters. The TwabLib (using existing blocktimes 1block/15sec) guarantees minimum 7.4 years of search history. */ library TwabLib { using OverflowSafeComparatorLib for uint32; using ExtendedSafeCastLib for uint256; /** * @notice Sets max ring buffer length in the Account.twabs Observation list. As users transfer/mint/burn tickets new Observation checkpoints are recorded. The current max cardinality guarantees a six month minimum, of historical accurate lookups with current estimates of 1 new block every 15 seconds - the of course contain a transfer to trigger an observation write to storage. * @dev The user Account.AccountDetails.cardinality parameter can NOT exceed the max cardinality variable. Preventing "corrupted" ring buffer lookup pointers and new observation checkpoints. The MAX_CARDINALITY in fact guarantees at least 7.4 years of records: If 14 = block time in seconds (2**24) * 14 = 234881024 seconds of history 234881024 / (365 * 24 * 60 * 60) ~= 7.44 years */ uint24 public constant MAX_CARDINALITY = 16777215; // 2**24 /** @notice Struct ring buffer parameters for single user Account * @param balance Current balance for an Account * @param nextTwabIndex Next uninitialized or updatable ring buffer checkpoint storage slot * @param cardinality Current total "initialized" ring buffer checkpoints for single user AccountDetails. Used to set initial boundary conditions for an efficient binary search. */ struct AccountDetails { uint208 balance; uint24 nextTwabIndex; uint24 cardinality; } /// @notice Combines account details with their twab history /// @param details The account details /// @param twabs The history of twabs for this account struct Account { AccountDetails details; ObservationLib.Observation[MAX_CARDINALITY] twabs; } /// @notice Increases an account's balance and records a new twab. /// @param _account The account whose balance will be increased /// @param _amount The amount to increase the balance by /// @param _currentTime The current time /// @return accountDetails The new AccountDetails /// @return twab The user's latest TWAB /// @return isNew Whether the TWAB is new function increaseBalance( Account storage _account, uint208 _amount, uint32 _currentTime ) internal returns ( AccountDetails memory accountDetails, ObservationLib.Observation memory twab, bool isNew ) { AccountDetails memory _accountDetails = _account.details; (accountDetails, twab, isNew) = _nextTwab(_account.twabs, _accountDetails, _currentTime); accountDetails.balance = _accountDetails.balance + _amount; } /** @notice Calculates the next TWAB checkpoint for an account with a decreasing balance. * @dev With Account struct and amount decreasing calculates the next TWAB observable checkpoint. * @param _account Account whose balance will be decreased * @param _amount Amount to decrease the balance by * @param _revertMessage Revert message for insufficient balance * @return accountDetails Updated Account.details struct * @return twab TWAB observation (with decreasing average) * @return isNew Whether TWAB is new or calling twice in the same block */ function decreaseBalance( Account storage _account, uint208 _amount, string memory _revertMessage, uint32 _currentTime ) internal returns ( AccountDetails memory accountDetails, ObservationLib.Observation memory twab, bool isNew ) { AccountDetails memory _accountDetails = _account.details; require(_accountDetails.balance >= _amount, _revertMessage); (accountDetails, twab, isNew) = _nextTwab(_account.twabs, _accountDetails, _currentTime); unchecked { accountDetails.balance -= _amount; } } /** @notice Calculates the average balance held by a user for a given time frame. * @dev Finds the average balance between start and end timestamp epochs. Validates the supplied end time is within the range of elapsed time i.e. less then timestamp of now. * @param _twabs Individual user Observation recorded checkpoints passed as storage pointer * @param _accountDetails User AccountDetails struct loaded in memory * @param _startTime Start of timestamp range as an epoch * @param _endTime End of timestamp range as an epoch * @param _currentTime Block.timestamp * @return Average balance of user held between epoch timestamps start and end */ function getAverageBalanceBetween( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _startTime, uint32 _endTime, uint32 _currentTime ) internal view returns (uint256) { uint32 endTime = _endTime > _currentTime ? _currentTime : _endTime; return _getAverageBalanceBetween(_twabs, _accountDetails, _startTime, endTime, _currentTime); } /// @notice Retrieves the oldest TWAB /// @param _twabs The storage array of twabs /// @param _accountDetails The TWAB account details /// @return index The index of the oldest TWAB in the twabs array /// @return twab The oldest TWAB function oldestTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails ) internal view returns (uint24 index, ObservationLib.Observation memory twab) { index = _accountDetails.nextTwabIndex; twab = _twabs[index]; // If the TWAB is not initialized we go to the beginning of the TWAB circular buffer at index 0 if (twab.timestamp == 0) { index = 0; twab = _twabs[0]; } } /// @notice Retrieves the newest TWAB /// @param _twabs The storage array of twabs /// @param _accountDetails The TWAB account details /// @return index The index of the newest TWAB in the twabs array /// @return twab The newest TWAB function newestTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails ) internal view returns (uint24 index, ObservationLib.Observation memory twab) { index = uint24(RingBufferLib.newestIndex(_accountDetails.nextTwabIndex, MAX_CARDINALITY)); twab = _twabs[index]; } /// @notice Retrieves amount at `_targetTime` timestamp /// @param _twabs List of TWABs to search through. /// @param _accountDetails Accounts details /// @param _targetTime Timestamp at which the reserved TWAB should be for. /// @return uint256 TWAB amount at `_targetTime`. function getBalanceAt( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _targetTime, uint32 _currentTime ) internal view returns (uint256) { uint32 timeToTarget = _targetTime > _currentTime ? _currentTime : _targetTime; return _getBalanceAt(_twabs, _accountDetails, timeToTarget, _currentTime); } /// @notice Calculates the average balance held by a user for a given time frame. /// @param _startTime The start time of the time frame. /// @param _endTime The end time of the time frame. /// @return The average balance that the user held during the time frame. function _getAverageBalanceBetween( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _startTime, uint32 _endTime, uint32 _currentTime ) private view returns (uint256) { (uint24 oldestTwabIndex, ObservationLib.Observation memory oldTwab) = oldestTwab( _twabs, _accountDetails ); (uint24 newestTwabIndex, ObservationLib.Observation memory newTwab) = newestTwab( _twabs, _accountDetails ); ObservationLib.Observation memory startTwab = _calculateTwab( _twabs, _accountDetails, newTwab, oldTwab, newestTwabIndex, oldestTwabIndex, _startTime, _currentTime ); ObservationLib.Observation memory endTwab = _calculateTwab( _twabs, _accountDetails, newTwab, oldTwab, newestTwabIndex, oldestTwabIndex, _endTime, _currentTime ); // Difference in amount / time return (endTwab.amount - startTwab.amount) / OverflowSafeComparatorLib.checkedSub(endTwab.timestamp, startTwab.timestamp, _currentTime); } /** @notice Searches TWAB history and calculate the difference between amount(s)/timestamp(s) to return average balance between the Observations closes to the supplied targetTime. * @param _twabs Individual user Observation recorded checkpoints passed as storage pointer * @param _accountDetails User AccountDetails struct loaded in memory * @param _targetTime Target timestamp to filter Observations in the ring buffer binary search * @param _currentTime Block.timestamp * @return uint256 Time-weighted average amount between two closest observations. */ function _getBalanceAt( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _targetTime, uint32 _currentTime ) private view returns (uint256) { uint24 newestTwabIndex; ObservationLib.Observation memory afterOrAt; ObservationLib.Observation memory beforeOrAt; (newestTwabIndex, beforeOrAt) = newestTwab(_twabs, _accountDetails); // If `_targetTime` is chronologically after the newest TWAB, we can simply return the current balance if (beforeOrAt.timestamp.lte(_targetTime, _currentTime)) { return _accountDetails.balance; } uint24 oldestTwabIndex; // Now, set before to the oldest TWAB (oldestTwabIndex, beforeOrAt) = oldestTwab(_twabs, _accountDetails); // If `_targetTime` is chronologically before the oldest TWAB, we can early return if (_targetTime.lt(beforeOrAt.timestamp, _currentTime)) { return 0; } // Otherwise, we perform the `binarySearch` (beforeOrAt, afterOrAt) = ObservationLib.binarySearch( _twabs, newestTwabIndex, oldestTwabIndex, _targetTime, _accountDetails.cardinality, _currentTime ); // Sum the difference in amounts and divide by the difference in timestamps. // The time-weighted average balance uses time measured between two epoch timestamps as // a constaint on the measurement when calculating the time weighted average balance. return (afterOrAt.amount - beforeOrAt.amount) / OverflowSafeComparatorLib.checkedSub(afterOrAt.timestamp, beforeOrAt.timestamp, _currentTime); } /** @notice Calculates a user TWAB for a target timestamp using the historical TWAB records. The balance is linearly interpolated: amount differences / timestamp differences using the simple (after.amount - before.amount / end.timestamp - start.timestamp) formula. /** @dev Binary search in _calculateTwab fails when searching out of bounds. Thus, before searching we exclude target timestamps out of range of newest/oldest TWAB(s). IF a search is before or after the range we "extrapolate" a Observation from the expected state. * @param _twabs Individual user Observation recorded checkpoints passed as storage pointer * @param _accountDetails User AccountDetails struct loaded in memory * @param _newestTwab Newest TWAB in history (end of ring buffer) * @param _oldestTwab Olderst TWAB in history (end of ring buffer) * @param _newestTwabIndex Pointer in ring buffer to newest TWAB * @param _oldestTwabIndex Pointer in ring buffer to oldest TWAB * @param _targetTimestamp Epoch timestamp to calculate for time (T) in the TWAB * @param _time Block.timestamp * @return accountDetails Updated Account.details struct */ function _calculateTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, ObservationLib.Observation memory _newestTwab, ObservationLib.Observation memory _oldestTwab, uint24 _newestTwabIndex, uint24 _oldestTwabIndex, uint32 _targetTimestamp, uint32 _time ) private view returns (ObservationLib.Observation memory) { // If `_targetTimestamp` is chronologically after the newest TWAB, we extrapolate a new one if (_newestTwab.timestamp.lt(_targetTimestamp, _time)) { return _computeNextTwab(_newestTwab, _accountDetails.balance, _targetTimestamp); } if (_newestTwab.timestamp == _targetTimestamp) { return _newestTwab; } if (_oldestTwab.timestamp == _targetTimestamp) { return _oldestTwab; } // If `_targetTimestamp` is chronologically before the oldest TWAB, we create a zero twab if (_targetTimestamp.lt(_oldestTwab.timestamp, _time)) { return ObservationLib.Observation({ amount: 0, timestamp: _targetTimestamp }); } // Otherwise, both timestamps must be surrounded by twabs. ( ObservationLib.Observation memory beforeOrAtStart, ObservationLib.Observation memory afterOrAtStart ) = ObservationLib.binarySearch( _twabs, _newestTwabIndex, _oldestTwabIndex, _targetTimestamp, _accountDetails.cardinality, _time ); uint224 heldBalance = (afterOrAtStart.amount - beforeOrAtStart.amount) / OverflowSafeComparatorLib.checkedSub(afterOrAtStart.timestamp, beforeOrAtStart.timestamp, _time); return _computeNextTwab(beforeOrAtStart, heldBalance, _targetTimestamp); } /** * @notice Calculates the next TWAB using the newestTwab and updated balance. * @dev Storage of the TWAB obersation is managed by the calling function and not _computeNextTwab. * @param _currentTwab Newest Observation in the Account.twabs list * @param _currentBalance User balance at time of most recent (newest) checkpoint write * @param _time Current block.timestamp * @return TWAB Observation */ function _computeNextTwab( ObservationLib.Observation memory _currentTwab, uint224 _currentBalance, uint32 _time ) private pure returns (ObservationLib.Observation memory) { // New twab amount = last twab amount (or zero) + (current amount * elapsed seconds) return ObservationLib.Observation({ amount: _currentTwab.amount + _currentBalance * (_time.checkedSub(_currentTwab.timestamp, _time)), timestamp: _time }); } /// @notice Sets a new TWAB Observation at the next available index and returns the new account details. /// @dev Note that if _currentTime is before the last observation timestamp, it appears as an overflow /// @param _twabs The twabs array to insert into /// @param _accountDetails The current account details /// @param _currentTime The current time /// @return accountDetails The new account details /// @return twab The newest twab (may or may not be brand-new) /// @return isNew Whether the newest twab was created by this call function _nextTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _currentTime ) private returns ( AccountDetails memory accountDetails, ObservationLib.Observation memory twab, bool isNew ) { (, ObservationLib.Observation memory _newestTwab) = newestTwab(_twabs, _accountDetails); // if we're in the same block, return if (_newestTwab.timestamp == _currentTime) { return (_accountDetails, _newestTwab, false); } ObservationLib.Observation memory newTwab = _computeNextTwab( _newestTwab, _accountDetails.balance, _currentTime ); _twabs[_accountDetails.nextTwabIndex] = newTwab; AccountDetails memory nextAccountDetails = push(_accountDetails); return (nextAccountDetails, newTwab, true); } /// @notice "Pushes" a new element on the AccountDetails ring buffer, and returns the new AccountDetails /// @param _accountDetails The account details from which to pull the cardinality and next index /// @return The new AccountDetails function push(AccountDetails memory _accountDetails) internal pure returns (AccountDetails memory) { _accountDetails.nextTwabIndex = uint24( RingBufferLib.nextIndex(_accountDetails.nextTwabIndex, MAX_CARDINALITY) ); // Prevent the Account specific cardinality from exceeding the MAX_CARDINALITY. // The ring buffer length is limited by MAX_CARDINALITY. IF the account.cardinality // exceeds the max cardinality, new observations would be incorrectly set or the // observation would be out of "bounds" of the ring buffer. Once reached the // AccountDetails.cardinality will continue to be equal to max cardinality. if (_accountDetails.cardinality < MAX_CARDINALITY) { _accountDetails.cardinality += 1; } return _accountDetails; } }
* @notice Combines account details with their twab history. @param details The account details. @param twabs The history of twabs for this account./
struct Account { AccountDetails details; ObservationLib.Observation[65535] twabs; } address indexed delegate, ObservationLib.Observation newTwab );
623,688
[ 1, 11328, 1465, 2236, 3189, 598, 3675, 2339, 378, 4927, 18, 225, 3189, 1021, 2236, 3189, 18, 225, 2339, 5113, 1021, 4927, 434, 2339, 5113, 364, 333, 2236, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 6590, 288, 203, 3639, 6590, 3790, 3189, 31, 203, 3639, 27177, 367, 5664, 18, 26199, 367, 63, 26, 2539, 4763, 65, 2339, 5113, 31, 203, 565, 289, 203, 203, 203, 203, 3639, 1758, 8808, 7152, 16, 203, 3639, 27177, 367, 5664, 18, 26199, 367, 394, 23539, 378, 203, 565, 11272, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); } function square(uint256 a) internal pure returns (uint256) { return mul(a, a); } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); } } contract ERC20Interface { event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function allowance( address _owner, address _spender) public view returns (uint256); } /** * @title CHStock * @author M.H. Kang */ contract CHStock is ERC20Interface { using SafeMath for uint256; /* EVENT */ event RedeemShares( address indexed user, uint256 shares, uint256 dividends ); /* STORAGE */ string public name = "ChickenHuntStock"; string public symbol = "CHS"; uint8 public decimals = 18; uint256 public totalShares; uint256 public dividendsPerShare; uint256 public constant CORRECTION = 1 << 64; mapping (address => uint256) public ethereumBalance; mapping (address => uint256) internal shares; mapping (address => uint256) internal refund; mapping (address => uint256) internal deduction; mapping (address => mapping (address => uint256)) internal allowed; /* FUNCTION */ function redeemShares() public { uint256 _shares = shares[msg.sender]; uint256 _dividends = dividendsOf(msg.sender); delete shares[msg.sender]; delete refund[msg.sender]; delete deduction[msg.sender]; totalShares = totalShares.sub(_shares); ethereumBalance[msg.sender] = ethereumBalance[msg.sender].add(_dividends); emit RedeemShares(msg.sender, _shares, _dividends); } function transfer(address _to, uint256 _value) public returns (bool) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function dividendsOf(address _shareholder) public view returns (uint256) { return dividendsPerShare.mul(shares[_shareholder]).add(refund[_shareholder]).sub(deduction[_shareholder]) / CORRECTION; } function totalSupply() public view returns (uint256) { return totalShares; } function balanceOf(address _owner) public view returns (uint256) { return shares[_owner]; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /* INTERNAL FUNCTION */ function _giveShares(address _user, uint256 _ethereum) internal { if (_ethereum > 0) { totalShares = totalShares.add(_ethereum); deduction[_user] = deduction[_user].add(dividendsPerShare.mul(_ethereum)); shares[_user] = shares[_user].add(_ethereum); dividendsPerShare = dividendsPerShare.add(_ethereum.mul(CORRECTION) / totalShares); emit Transfer(address(0), _user, _ethereum); } } function _transfer(address _from, address _to, uint256 _value) internal { require(_to != address(0)); require(_value <= shares[_from]); uint256 _rawProfit = dividendsPerShare.mul(_value); uint256 _refund = refund[_from].add(_rawProfit); uint256 _min = _refund < deduction[_from] ? _refund : deduction[_from]; refund[_from] = _refund.sub(_min); deduction[_from] = deduction[_from].sub(_min); deduction[_to] = deduction[_to].add(_rawProfit); shares[_from] = shares[_from].sub(_value); shares[_to] = shares[_to].add(_value); emit Transfer(_from, _to, _value); } } /** * @title CHGameBase * @author M.H. Kang */ contract CHGameBase is CHStock { /* DATA STRUCT */ struct House { Hunter hunter; uint256 huntingPower; uint256 offensePower; uint256 defensePower; uint256 huntingMultiplier; uint256 offenseMultiplier; uint256 defenseMultiplier; uint256 depots; uint256[] pets; } struct Hunter { uint256 strength; uint256 dexterity; uint256 constitution; uint256 resistance; } struct Store { address owner; uint256 cut; uint256 cost; uint256 balance; } /* STORAGE */ Store public store; uint256 public devCut; uint256 public devFee; uint256 public altarCut; uint256 public altarFund; uint256 public dividendRate; uint256 public totalChicken; address public chickenTokenDelegator; mapping (address => uint256) public lastSaveTime; mapping (address => uint256) public savedChickenOf; mapping (address => House) internal houses; /* FUNCTION */ function saveChickenOf(address _user) public returns (uint256) { uint256 _unclaimedChicken = _unclaimedChickenOf(_user); totalChicken = totalChicken.add(_unclaimedChicken); uint256 _chicken = savedChickenOf[_user].add(_unclaimedChicken); savedChickenOf[_user] = _chicken; lastSaveTime[_user] = block.timestamp; return _chicken; } function transferChickenFrom(address _from, address _to, uint256 _value) public returns (bool) { require(msg.sender == chickenTokenDelegator); require(saveChickenOf(_from) >= _value); savedChickenOf[_from] = savedChickenOf[_from] - _value; savedChickenOf[_to] = savedChickenOf[_to].add(_value); return true; } function chickenOf(address _user) public view returns (uint256) { return savedChickenOf[_user].add(_unclaimedChickenOf(_user)); } /* INTERNAL FUNCTION */ function _payChicken(address _user, uint256 _chicken) internal { uint256 _unclaimedChicken = _unclaimedChickenOf(_user); uint256 _extraChicken; if (_chicken > _unclaimedChicken) { _extraChicken = _chicken - _unclaimedChicken; require(savedChickenOf[_user] >= _extraChicken); savedChickenOf[_user] -= _extraChicken; totalChicken -= _extraChicken; } else { _extraChicken = _unclaimedChicken - _chicken; totalChicken = totalChicken.add(_extraChicken); savedChickenOf[_user] += _extraChicken; } lastSaveTime[_user] = block.timestamp; } function _payEthereumAndDistribute(uint256 _cost) internal { require(_cost * 100 / 100 == _cost); _payEthereum(_cost); uint256 _toShareholders = _cost * dividendRate / 100; uint256 _toAltar = _cost * altarCut / 100; uint256 _toStore = _cost * store.cut / 100; devFee = devFee.add(_cost - _toShareholders - _toAltar - _toStore); _giveShares(msg.sender, _toShareholders); altarFund = altarFund.add(_toAltar); store.balance = store.balance.add(_toStore); } function _payEthereum(uint256 _cost) internal { uint256 _extra; if (_cost > msg.value) { _extra = _cost - msg.value; require(ethereumBalance[msg.sender] >= _extra); ethereumBalance[msg.sender] -= _extra; } else { _extra = msg.value - _cost; ethereumBalance[msg.sender] = ethereumBalance[msg.sender].add(_extra); } } function _unclaimedChickenOf(address _user) internal view returns (uint256) { uint256 _timestamp = lastSaveTime[_user]; if (_timestamp > 0 && _timestamp < block.timestamp) { return houses[_user].huntingPower.mul( houses[_user].huntingMultiplier ).mul(block.timestamp - _timestamp) / 100; } else { return 0; } } function _houseOf(address _user) internal view returns (House storage _house) { _house = houses[_user]; require(_house.depots > 0); } } /** * @title CHHunter * @author M.H. Kang */ contract CHHunter is CHGameBase { /* EVENT */ event UpgradeHunter( address indexed user, string attribute, uint256 to ); /* DATA STRUCT */ struct Config { uint256 chicken; uint256 ethereum; uint256 max; } /* STORAGE */ Config public typeA; Config public typeB; /* FUNCTION */ function upgradeStrength(uint256 _to) external payable { House storage _house = _houseOf(msg.sender); uint256 _from = _house.hunter.strength; require(typeA.max >= _to && _to > _from); _payForUpgrade(_from, _to, typeA); uint256 _increment = _house.hunter.dexterity.mul(2).add(8).mul(_to.square() - _from ** 2); _house.hunter.strength = _to; _house.huntingPower = _house.huntingPower.add(_increment); _house.offensePower = _house.offensePower.add(_increment); emit UpgradeHunter(msg.sender, "strength", _to); } function upgradeDexterity(uint256 _to) external payable { House storage _house = _houseOf(msg.sender); uint256 _from = _house.hunter.dexterity; require(typeB.max >= _to && _to > _from); _payForUpgrade(_from, _to, typeB); uint256 _increment = _house.hunter.strength.square().mul((_to - _from).mul(2)); _house.hunter.dexterity = _to; _house.huntingPower = _house.huntingPower.add(_increment); _house.offensePower = _house.offensePower.add(_increment); emit UpgradeHunter(msg.sender, "dexterity", _to); } function upgradeConstitution(uint256 _to) external payable { House storage _house = _houseOf(msg.sender); uint256 _from = _house.hunter.constitution; require(typeA.max >= _to && _to > _from); _payForUpgrade(_from, _to, typeA); uint256 _increment = _house.hunter.resistance.mul(2).add(8).mul(_to.square() - _from ** 2); _house.hunter.constitution = _to; _house.defensePower = _house.defensePower.add(_increment); emit UpgradeHunter(msg.sender, "constitution", _to); } function upgradeResistance(uint256 _to) external payable { House storage _house = _houseOf(msg.sender); uint256 _from = _house.hunter.resistance; require(typeB.max >= _to && _to > _from); _payForUpgrade(_from, _to, typeB); uint256 _increment = _house.hunter.constitution.square().mul((_to - _from).mul(2)); _house.hunter.resistance = _to; _house.defensePower = _house.defensePower.add(_increment); emit UpgradeHunter(msg.sender, "resistance", _to); } /* INTERNAL FUNCTION */ function _payForUpgrade(uint256 _from, uint256 _to, Config _type) internal { uint256 _chickenCost = _type.chicken.mul(_gapOfCubeSum(_from, _to)); _payChicken(msg.sender, _chickenCost); uint256 _ethereumCost = _type.ethereum.mul(_gapOfSquareSum(_from, _to)); _payEthereumAndDistribute(_ethereumCost); } function _gapOfSquareSum(uint256 _before, uint256 _after) internal pure returns (uint256) { // max value is capped to uint32 return (_after * (_after - 1) * (2 * _after - 1) - _before * (_before - 1) * (2 * _before - 1)) / 6; } function _gapOfCubeSum(uint256 _before, uint256 _after) internal pure returns (uint256) { // max value is capped to uint32 return ((_after * (_after - 1)) ** 2 - (_before * (_before - 1)) ** 2) >> 2; } } /** * @title CHHouse * @author M.H. Kang */ contract CHHouse is CHHunter { /* EVENT */ event UpgradePet( address indexed user, uint256 id, uint256 to ); event UpgradeDepot( address indexed user, uint256 to ); event BuyItem( address indexed from, address indexed to, uint256 indexed id, uint256 cost ); event BuyStore( address indexed from, address indexed to, uint256 cost ); /* DATA STRUCT */ struct Pet { uint256 huntingPower; uint256 offensePower; uint256 defensePower; uint256 chicken; uint256 ethereum; uint256 max; } struct Item { address owner; uint256 huntingMultiplier; uint256 offenseMultiplier; uint256 defenseMultiplier; uint256 cost; } struct Depot { uint256 ethereum; uint256 max; } /* STORAGE */ uint256 public constant INCREMENT_RATE = 12; // 120% for Item and Store Depot public depot; Pet[] public pets; Item[] public items; /* FUNCTION */ function buyDepots(uint256 _amount) external payable { House storage _house = _houseOf(msg.sender); _house.depots = _house.depots.add(_amount); require(_house.depots <= depot.max); _payEthereumAndDistribute(_amount.mul(depot.ethereum)); emit UpgradeDepot(msg.sender, _house.depots); } function buyPets(uint256 _id, uint256 _amount) external payable { require(_id < pets.length); Pet memory _pet = pets[_id]; uint256 _chickenCost = _amount * _pet.chicken; _payChicken(msg.sender, _chickenCost); uint256 _ethereumCost = _amount * _pet.ethereum; _payEthereumAndDistribute(_ethereumCost); House storage _house = _houseOf(msg.sender); if (_house.pets.length < _id + 1) { _house.pets.length = _id + 1; } _house.pets[_id] = _house.pets[_id].add(_amount); require(_house.pets[_id] <= _pet.max); _house.huntingPower = _house.huntingPower.add(_pet.huntingPower * _amount); _house.offensePower = _house.offensePower.add(_pet.offensePower * _amount); _house.defensePower = _house.defensePower.add(_pet.defensePower * _amount); emit UpgradePet(msg.sender, _id, _house.pets[_id]); } // This is independent of Stock and Altar. function buyItem(uint256 _id) external payable { Item storage _item = items[_id]; address _from = _item.owner; uint256 _price = _item.cost.mul(INCREMENT_RATE) / 10; _payEthereum(_price); saveChickenOf(_from); House storage _fromHouse = _houseOf(_from); _fromHouse.huntingMultiplier = _fromHouse.huntingMultiplier.sub(_item.huntingMultiplier); _fromHouse.offenseMultiplier = _fromHouse.offenseMultiplier.sub(_item.offenseMultiplier); _fromHouse.defenseMultiplier = _fromHouse.defenseMultiplier.sub(_item.defenseMultiplier); saveChickenOf(msg.sender); House storage _toHouse = _houseOf(msg.sender); _toHouse.huntingMultiplier = _toHouse.huntingMultiplier.add(_item.huntingMultiplier); _toHouse.offenseMultiplier = _toHouse.offenseMultiplier.add(_item.offenseMultiplier); _toHouse.defenseMultiplier = _toHouse.defenseMultiplier.add(_item.defenseMultiplier); uint256 _halfMargin = _price.sub(_item.cost) / 2; devFee = devFee.add(_halfMargin); ethereumBalance[_from] = ethereumBalance[_from].add(_price - _halfMargin); items[_id].cost = _price; items[_id].owner = msg.sender; emit BuyItem(_from, msg.sender, _id, _price); } // This is independent of Stock and Altar. function buyStore() external payable { address _from = store.owner; uint256 _price = store.cost.mul(INCREMENT_RATE) / 10; _payEthereum(_price); uint256 _halfMargin = (_price - store.cost) / 2; devFee = devFee.add(_halfMargin); ethereumBalance[_from] = ethereumBalance[_from].add(_price - _halfMargin).add(store.balance); store.cost = _price; store.owner = msg.sender; delete store.balance; emit BuyStore(_from, msg.sender, _price); } function withdrawStoreBalance() public { ethereumBalance[store.owner] = ethereumBalance[store.owner].add(store.balance); delete store.balance; } } /** * @title CHArena * @author M.H. Kang */ contract CHArena is CHHouse { /* EVENT */ event Attack( address indexed attacker, address indexed defender, uint256 booty ); /* STORAGE */ mapping(address => uint256) public attackCooldown; uint256 public cooldownTime; /* FUNCTION */ function attack(address _target) external { require(attackCooldown[msg.sender] < block.timestamp); House storage _attacker = houses[msg.sender]; House storage _defender = houses[_target]; if (_attacker.offensePower.mul(_attacker.offenseMultiplier) > _defender.defensePower.mul(_defender.defenseMultiplier)) { uint256 _chicken = saveChickenOf(_target); _chicken = _defender.depots > 0 ? _chicken / _defender.depots : _chicken; savedChickenOf[_target] = savedChickenOf[_target] - _chicken; savedChickenOf[msg.sender] = savedChickenOf[msg.sender].add(_chicken); attackCooldown[msg.sender] = block.timestamp + cooldownTime; emit Attack(msg.sender, _target, _chicken); } } } /** * @title CHAltar * @author M.H. Kang */ contract CHAltar is CHArena { /* EVENT */ event NewAltarRecord(uint256 id, uint256 ethereum); event ChickenToAltar(address indexed user, uint256 id, uint256 chicken); event EthereumFromAltar(address indexed user, uint256 id, uint256 ethereum); /* DATA STRUCT */ struct AltarRecord { uint256 ethereum; uint256 chicken; } struct TradeBook { uint256 altarRecordId; uint256 chicken; } /* STORAGE */ uint256 public genesis; mapping (uint256 => AltarRecord) public altarRecords; mapping (address => TradeBook) public tradeBooks; /* FUNCTION */ function chickenToAltar(uint256 _chicken) external { require(_chicken > 0); _payChicken(msg.sender, _chicken); uint256 _id = _getCurrentAltarRecordId(); AltarRecord storage _altarRecord = _getAltarRecord(_id); require(_altarRecord.ethereum * _chicken / _chicken == _altarRecord.ethereum); TradeBook storage _tradeBook = tradeBooks[msg.sender]; if (_tradeBook.altarRecordId < _id) { _resolveTradeBook(_tradeBook); _tradeBook.altarRecordId = _id; } _altarRecord.chicken = _altarRecord.chicken.add(_chicken); _tradeBook.chicken += _chicken; emit ChickenToAltar(msg.sender, _id, _chicken); } function ethereumFromAltar() external { uint256 _id = _getCurrentAltarRecordId(); TradeBook storage _tradeBook = tradeBooks[msg.sender]; require(_tradeBook.altarRecordId < _id); _resolveTradeBook(_tradeBook); } function tradeBookOf(address _user) public view returns ( uint256 _id, uint256 _ethereum, uint256 _totalChicken, uint256 _chicken, uint256 _income ) { TradeBook memory _tradeBook = tradeBooks[_user]; _id = _tradeBook.altarRecordId; _chicken = _tradeBook.chicken; AltarRecord memory _altarRecord = altarRecords[_id]; _totalChicken = _altarRecord.chicken; _ethereum = _altarRecord.ethereum; _income = _totalChicken > 0 ? _ethereum.mul(_chicken) / _totalChicken : 0; } /* INTERNAL FUNCTION */ function _resolveTradeBook(TradeBook storage _tradeBook) internal { if (_tradeBook.chicken > 0) { AltarRecord memory _oldAltarRecord = altarRecords[_tradeBook.altarRecordId]; uint256 _ethereum = _oldAltarRecord.ethereum.mul(_tradeBook.chicken) / _oldAltarRecord.chicken; delete _tradeBook.chicken; ethereumBalance[msg.sender] = ethereumBalance[msg.sender].add(_ethereum); emit EthereumFromAltar(msg.sender, _tradeBook.altarRecordId, _ethereum); } } function _getCurrentAltarRecordId() internal view returns (uint256) { return (block.timestamp - genesis) / 86400; } function _getAltarRecord(uint256 _id) internal returns (AltarRecord storage _altarRecord) { _altarRecord = altarRecords[_id]; if (_altarRecord.ethereum == 0) { uint256 _ethereum = altarFund / 10; _altarRecord.ethereum = _ethereum; altarFund -= _ethereum; emit NewAltarRecord(_id, _ethereum); } } } /** * @title CHCommittee * @author M.H. Kang */ contract CHCommittee is CHAltar { /* EVENT */ event NewPet( uint256 id, uint256 huntingPower, uint256 offensePower, uint256 defense, uint256 chicken, uint256 ethereum, uint256 max ); event ChangePet( uint256 id, uint256 chicken, uint256 ethereum, uint256 max ); event NewItem( uint256 id, uint256 huntingMultiplier, uint256 offenseMultiplier, uint256 defenseMultiplier, uint256 ethereum ); event SetDepot(uint256 ethereum, uint256 max); event SetConfiguration( uint256 chickenA, uint256 ethereumA, uint256 maxA, uint256 chickenB, uint256 ethereumB, uint256 maxB ); event SetDistribution( uint256 dividendRate, uint256 altarCut, uint256 storeCut, uint256 devCut ); event SetCooldownTime(uint256 cooldownTime); event SetNameAndSymbol(string name, string symbol); event SetDeveloper(address developer); event SetCommittee(address committee); /* STORAGE */ address public committee; address public developer; /* FUNCTION */ function callFor(address _to, uint256 _value, uint256 _gas, bytes _code) external payable onlyCommittee returns (bool) { return _to.call.value(_value).gas(_gas)(_code); } function addPet( uint256 _huntingPower, uint256 _offensePower, uint256 _defense, uint256 _chicken, uint256 _ethereum, uint256 _max ) public onlyCommittee { require(_max > 0); require(_max == uint256(uint32(_max))); uint256 _newLength = pets.push( Pet(_huntingPower, _offensePower, _defense, _chicken, _ethereum, _max) ); emit NewPet( _newLength - 1, _huntingPower, _offensePower, _defense, _chicken, _ethereum, _max ); } function changePet( uint256 _id, uint256 _chicken, uint256 _ethereum, uint256 _max ) public onlyCommittee { require(_id < pets.length); Pet storage _pet = pets[_id]; require(_max >= _pet.max && _max == uint256(uint32(_max))); _pet.chicken = _chicken; _pet.ethereum = _ethereum; _pet.max = _max; emit ChangePet(_id, _chicken, _ethereum, _max); } function addItem( uint256 _huntingMultiplier, uint256 _offenseMultiplier, uint256 _defenseMultiplier, uint256 _price ) public onlyCommittee { uint256 _cap = 1 << 16; require( _huntingMultiplier < _cap && _offenseMultiplier < _cap && _defenseMultiplier < _cap ); saveChickenOf(committee); House storage _house = _houseOf(committee); _house.huntingMultiplier = _house.huntingMultiplier.add(_huntingMultiplier); _house.offenseMultiplier = _house.offenseMultiplier.add(_offenseMultiplier); _house.defenseMultiplier = _house.defenseMultiplier.add(_defenseMultiplier); uint256 _newLength = items.push( Item( committee, _huntingMultiplier, _offenseMultiplier, _defenseMultiplier, _price ) ); emit NewItem( _newLength - 1, _huntingMultiplier, _offenseMultiplier, _defenseMultiplier, _price ); } function setDepot(uint256 _price, uint256 _max) public onlyCommittee { require(_max >= depot.max); depot.ethereum = _price; depot.max = _max; emit SetDepot(_price, _max); } function setConfiguration( uint256 _chickenA, uint256 _ethereumA, uint256 _maxA, uint256 _chickenB, uint256 _ethereumB, uint256 _maxB ) public onlyCommittee { require(_maxA >= typeA.max && (_maxA == uint256(uint32(_maxA)))); require(_maxB >= typeB.max && (_maxB == uint256(uint32(_maxB)))); typeA.chicken = _chickenA; typeA.ethereum = _ethereumA; typeA.max = _maxA; typeB.chicken = _chickenB; typeB.ethereum = _ethereumB; typeB.max = _maxB; emit SetConfiguration(_chickenA, _ethereumA, _maxA, _chickenB, _ethereumB, _maxB); } function setDistribution( uint256 _dividendRate, uint256 _altarCut, uint256 _storeCut, uint256 _devCut ) public onlyCommittee { require(_storeCut > 0); require( _dividendRate.add(_altarCut).add(_storeCut).add(_devCut) == 100 ); dividendRate = _dividendRate; altarCut = _altarCut; store.cut = _storeCut; devCut = _devCut; emit SetDistribution(_dividendRate, _altarCut, _storeCut, _devCut); } function setCooldownTime(uint256 _cooldownTime) public onlyCommittee { cooldownTime = _cooldownTime; emit SetCooldownTime(_cooldownTime); } function setNameAndSymbol(string _name, string _symbol) public onlyCommittee { name = _name; symbol = _symbol; emit SetNameAndSymbol(_name, _symbol); } function setDeveloper(address _developer) public onlyCommittee { require(_developer != address(0)); withdrawDevFee(); developer = _developer; emit SetDeveloper(_developer); } function setCommittee(address _committee) public onlyCommittee { require(_committee != address(0)); committee = _committee; emit SetCommittee(_committee); } function withdrawDevFee() public { ethereumBalance[developer] = ethereumBalance[developer].add(devFee); delete devFee; } /* MODIFIER */ modifier onlyCommittee { require(msg.sender == committee); _; } } /** * @title ChickenHunt * @author M.H. Kang */ contract ChickenHunt is CHCommittee { /* EVENT */ event Join(address user); /* CONSTRUCTOR */ constructor() public { committee = msg.sender; developer = msg.sender; } /* FUNCTION */ function init(address _chickenTokenDelegator) external onlyCommittee { require(chickenTokenDelegator == address(0)); chickenTokenDelegator = _chickenTokenDelegator; genesis = 1525791600; join(); store.owner = msg.sender; store.cost = 0.1 ether; setConfiguration(100, 0.00001 ether, 99, 100000, 0.001 ether, 9); setDistribution(20, 75, 1, 4); setCooldownTime(600); setDepot(0.05 ether, 9); addItem(5, 5, 0, 0.01 ether); addItem(0, 0, 5, 0.01 ether); addPet(1000, 0, 0, 100000, 0.01 ether, 9); addPet(0, 1000, 0, 100000, 0.01 ether, 9); addPet(0, 0, 1000, 202500, 0.01 ether, 9); } function withdraw() external { uint256 _ethereum = ethereumBalance[msg.sender]; delete ethereumBalance[msg.sender]; msg.sender.transfer(_ethereum); } function join() public { House storage _house = houses[msg.sender]; require(_house.depots == 0); _house.hunter = Hunter(1, 1, 1, 1); _house.depots = 1; _house.huntingPower = 10; _house.offensePower = 10; _house.defensePower = 110; _house.huntingMultiplier = 10; _house.offenseMultiplier = 10; _house.defenseMultiplier = 10; lastSaveTime[msg.sender] = block.timestamp; emit Join(msg.sender); } function hunterOf(address _user) public view returns ( uint256 _strength, uint256 _dexterity, uint256 _constitution, uint256 _resistance ) { Hunter memory _hunter = houses[_user].hunter; return ( _hunter.strength, _hunter.dexterity, _hunter.constitution, _hunter.resistance ); } function detailsOf(address _user) public view returns ( uint256[2] _hunting, uint256[2] _offense, uint256[2] _defense, uint256[4] _hunter, uint256[] _pets, uint256 _depots, uint256 _savedChicken, uint256 _lastSaveTime, uint256 _cooldown ) { House memory _house = houses[_user]; _hunting = [_house.huntingPower, _house.huntingMultiplier]; _offense = [_house.offensePower, _house.offenseMultiplier]; _defense = [_house.defensePower, _house.defenseMultiplier]; _hunter = [ _house.hunter.strength, _house.hunter.dexterity, _house.hunter.constitution, _house.hunter.resistance ]; _pets = _house.pets; _depots = _house.depots; _savedChicken = savedChickenOf[_user]; _lastSaveTime = lastSaveTime[_user]; _cooldown = attackCooldown[_user]; } }
120% for Item and Store
uint256 public constant INCREMENT_RATE = 12;
15,049,978
[ 1, 22343, 9, 364, 4342, 471, 4994, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 5381, 2120, 23923, 67, 24062, 273, 2593, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x11984dc4465481512eb5b777E44061C158CF2259/sources/contracts/messaging/connectors/Connector.sol
* @title Connector @author Connext Labs, Inc. @notice This contract has the messaging interface functions used by all connectors. @dev This contract stores information about mirror connectors, but can be used as a base for contracts that do not have a mirror (i.e. the connector handling messaging on mainnet). In this case, the `mirrorConnector` and `MIRROR_DOMAIN` will be empty @dev If ownership is renounced, this contract will be unable to update its `mirrorConnector` or `mirrorGas`/ ========== Custom Errors =========== ============ Events ============ ============ Public Storage ============ ============ Modifiers ============
abstract contract Connector is ProposedOwnable, IConnector { error Connector__processMessage_notUsed(); event NewConnector( uint32 indexed domain, uint32 indexed mirrorDomain, address amb, address rootManager, address mirrorConnector ); event MirrorConnectorUpdated(address previous, address current); uint32 public immutable DOMAIN; address public immutable AMB; address public immutable ROOT_MANAGER; uint32 public immutable MIRROR_DOMAIN; address public mirrorConnector; pragma solidity 0.8.17; import {ProposedOwnable} from "../../shared/ProposedOwnable.sol"; import {IConnector} from "../interfaces/IConnector.sol"; modifier onlyAMB() { require(msg.sender == AMB, "!AMB"); _; } modifier onlyRootManager() { require(msg.sender == ROOT_MANAGER, "!rootManager"); _; } uint32 _domain, uint32 _mirrorDomain, address _amb, address _rootManager, address _mirrorConnector constructor( ) ProposedOwnable() { _setOwner(msg.sender); require(_domain != 0, "empty domain"); require(_rootManager != address(0), "empty rootManager"); DOMAIN = _domain; AMB = _amb; ROOT_MANAGER = _rootManager; MIRROR_DOMAIN = _mirrorDomain; if (_mirrorConnector != address(0)) { _setMirrorConnector(_mirrorConnector); } emit NewConnector(_domain, _mirrorDomain, _amb, _rootManager, _mirrorConnector); } ) ProposedOwnable() { _setOwner(msg.sender); require(_domain != 0, "empty domain"); require(_rootManager != address(0), "empty rootManager"); DOMAIN = _domain; AMB = _amb; ROOT_MANAGER = _rootManager; MIRROR_DOMAIN = _mirrorDomain; if (_mirrorConnector != address(0)) { _setMirrorConnector(_mirrorConnector); } emit NewConnector(_domain, _mirrorDomain, _amb, _rootManager, _mirrorConnector); } receive() external payable {} function setMirrorConnector(address _mirrorConnector) public onlyOwner { _setMirrorConnector(_mirrorConnector); } function processMessage(bytes memory _data) external onlyAMB { _processMessage(_data); emit MessageProcessed(_data, msg.sender); } function verifySender(address _expected) external returns (bool) { return _verifySender(_expected); } function _sendMessage(bytes memory _data, bytes memory _encodedData) internal virtual; function _processMessage( bytes memory /* _data */ ) internal virtual { revert Connector__processMessage_notUsed(); } function _verifySender(address _expected) internal virtual returns (bool); function _setMirrorConnector(address _mirrorConnector) internal virtual { emit MirrorConnectorUpdated(mirrorConnector, _mirrorConnector); mirrorConnector = _mirrorConnector; } }
16,601,005
[ 1, 7487, 225, 735, 4285, 511, 5113, 16, 15090, 18, 225, 1220, 6835, 711, 326, 17301, 1560, 4186, 1399, 635, 777, 28473, 18, 225, 1220, 6835, 9064, 1779, 2973, 15593, 28473, 16, 1496, 848, 506, 1399, 487, 279, 1026, 364, 20092, 716, 741, 486, 1240, 279, 15593, 261, 77, 18, 73, 18, 326, 8703, 5057, 17301, 603, 2774, 2758, 2934, 657, 333, 648, 16, 326, 1375, 27197, 7487, 68, 471, 1375, 7492, 54, 2784, 67, 18192, 68, 903, 506, 1008, 225, 971, 23178, 353, 1654, 27373, 16, 333, 6835, 903, 506, 13496, 358, 1089, 2097, 1375, 27197, 7487, 68, 578, 1375, 27197, 27998, 68, 19, 422, 1432, 6082, 9372, 422, 1432, 33, 422, 1432, 631, 9043, 422, 1432, 631, 422, 1432, 631, 7224, 5235, 422, 1432, 631, 422, 1432, 631, 3431, 3383, 422, 1432, 631, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 15779, 353, 1186, 7423, 5460, 429, 16, 467, 7487, 288, 203, 203, 225, 555, 15779, 972, 2567, 1079, 67, 902, 6668, 5621, 203, 203, 203, 225, 871, 1166, 7487, 12, 203, 565, 2254, 1578, 8808, 2461, 16, 203, 565, 2254, 1578, 8808, 15593, 3748, 16, 203, 565, 1758, 13232, 16, 203, 565, 1758, 1365, 1318, 16, 203, 565, 1758, 15593, 7487, 203, 225, 11272, 203, 203, 225, 871, 490, 8299, 7487, 7381, 12, 2867, 2416, 16, 1758, 783, 1769, 203, 203, 203, 225, 2254, 1578, 1071, 11732, 27025, 31, 203, 203, 225, 1758, 1071, 11732, 432, 7969, 31, 203, 203, 225, 1758, 1071, 11732, 11011, 67, 19402, 31, 203, 203, 225, 2254, 1578, 1071, 11732, 490, 7937, 2784, 67, 18192, 31, 203, 203, 225, 1758, 1071, 15593, 7487, 31, 203, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 4033, 31, 203, 5666, 288, 626, 7423, 5460, 429, 97, 628, 315, 16644, 11574, 19, 626, 7423, 5460, 429, 18, 18281, 14432, 203, 5666, 288, 45, 7487, 97, 628, 315, 6216, 15898, 19, 45, 7487, 18, 18281, 14432, 203, 225, 9606, 1338, 2192, 38, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 432, 7969, 16, 17528, 2192, 38, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 9606, 1338, 2375, 1318, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 11011, 67, 19402, 16, 17528, 3085, 1318, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 565, 2254, 1578, 389, 4308, 16, 203, 565, 2254, 1578, 2 ]
pragma solidity ^0.4.13; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); return c; } } contract ERC20 { uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] = SafeMath.sub(allowance[_from][msg.sender], _value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * ###################### * # private function # * ###################### */ function _transfer(address _from, address _to, uint _value) internal { require(balanceOf[_from] >= _value); require(SafeMath.add(balanceOf[_to], _value) >= balanceOf[_to]); balanceOf[_from] = SafeMath.sub(balanceOf[_from], _value); balanceOf[_to] = SafeMath.add(balanceOf[_to], _value); emit Transfer(_from, _to, _value); } } contract Token is ERC20 { uint8 public constant decimals = 9; uint256 public constant initialSupply = 10 * (10 ** 8) * (10 ** uint256(decimals)); string public constant name = 'INK Coin'; string public constant symbol = 'INK'; function() public { revert(); } function Token() public { balanceOf[msg.sender] = initialSupply; totalSupply = initialSupply; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { if (approve(_spender, _value)) { if (!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); } return true; } } } interface XCInterface { /** * Set contract service status. * @param status contract service status (0:closed;1:only-closed-lock;2:only-closed-unlock;3:opened;). */ function setStatus(uint8 status) external; /** * Get contract service status. * @return contract service status. */ function getStatus() external view returns (uint8); /** * Get the current contract platform name. * @return contract platform name. */ function getPlatformName() external view returns (bytes32); /** * Set the current contract administrator. * @param account account of contract administrator. */ function setAdmin(address account) external; /** * Get the current contract administrator. * @return contract administrator. */ function getAdmin() external view returns (address); /** * Set the Token contract address. * @param account contract address. */ function setToken(address account) external; /** * Get the Token contract address. * @return contract address. */ function getToken() external view returns (address); /** * Set the XCPlugin contract address. * @param account contract address. */ function setXCPlugin(address account) external; /** * Get the XCPlugin contract address. * @return contract address. */ function getXCPlugin() external view returns (address); /** * Set the comparison symbol in the contract. * @param symbol comparison symbol ({"-=" : ">" , "+=" : ">=" }). */ function setCompare(bytes2 symbol) external; /** * Get the comparison symbol in the contract. * @return comparison symbol. */ function getCompare() external view returns (bytes2); /** * Transfer out of cross chain. * @param toPlatform name of to platform. * @param toAccount account of to platform. * @param value transfer amount. */ function lock(bytes32 toPlatform, address toAccount, uint value) external payable; /** * Transfer in of cross chain. * @param txid transaction id. * @param fromPlatform name of form platform. * @param fromAccount ame of to platform. * @param toAccount account of to platform. * @param value transfer amount. */ function unlock(string txid, bytes32 fromPlatform, address fromAccount, address toAccount, uint value) external payable; /** * Transfer the misoperation to the amount of the contract account to the specified account. * @param account the specified account. * @param value transfer amount. */ function withdraw(address account, uint value) external payable; /** * Transfer the money(qtum/eth) from the contract account. * @param account the specified account. * @param value transfer amount. */ function transfer(address account, uint value) external payable; /** * Deposit money(eth) into a contract. */ function deposit() external payable; } contract XC is XCInterface { /** * Contract Administrator * @field status Contract external service status. * @field platformName Current contract platform name. * @field account Current contract administrator. */ struct Admin { uint8 status; bytes32 platformName; bytes32 tokenSymbol; bytes2 compareSymbol; address account; } Admin private admin; uint public lockBalance; Token private token; XCPlugin private xcPlugin; event Lock(bytes32 toPlatform, address toAccount, bytes32 value, bytes32 tokenSymbol); event Unlock(string txid, bytes32 fromPlatform, address fromAccount, bytes32 value, bytes32 tokenSymbol); event Deposit(address from, bytes32 value); function XC() public payable { init(); } function init() internal { // Admin {status | platformName | tokenSymbol | compareSymbol | account} admin.status = 3; admin.platformName = "ETH"; admin.tokenSymbol = "INK"; admin.compareSymbol = "+="; admin.account = msg.sender; //totalSupply = 10 * (10 ** 8) * (10 ** 9); lockBalance = 10 * (10 ** 8) * (10 ** 9); token = Token(0xc15d8f30fa3137eee6be111c2933f1624972f45c); xcPlugin = XCPlugin(0x55c87c2e26f66fd3642645c3f25c9e81a75ec0f4); } function setStatus(uint8 status) external { require(admin.account == msg.sender); require(status == 0 || status == 1 || status == 2 || status == 3); if (admin.status != status) { admin.status = status; } } function getStatus() external view returns (uint8) { return admin.status; } function getPlatformName() external view returns (bytes32) { return admin.platformName; } function setAdmin(address account) external { require(account != address(0)); require(admin.account == msg.sender); if (admin.account != account) { admin.account = account; } } function getAdmin() external view returns (address) { return admin.account; } function setToken(address account) external { require(admin.account == msg.sender); if (token != account) { token = Token(account); } } function getToken() external view returns (address) { return token; } function setXCPlugin(address account) external { require(admin.account == msg.sender); if (xcPlugin != account) { xcPlugin = XCPlugin(account); } } function getXCPlugin() external view returns (address) { return xcPlugin; } function setCompare(bytes2 symbol) external { require(admin.account == msg.sender); require(symbol == "+=" || symbol == "-="); if (admin.compareSymbol != symbol) { admin.compareSymbol = symbol; } } function getCompare() external view returns (bytes2){ require(admin.account == msg.sender); return admin.compareSymbol; } function lock(bytes32 toPlatform, address toAccount, uint value) external payable { require(admin.status == 2 || admin.status == 3); require(xcPlugin.getStatus()); require(xcPlugin.existPlatform(toPlatform)); require(toAccount != address(0)); // require(token.totalSupply >= value && value > 0); require(value > 0); //get user approve the contract quota uint allowance = token.allowance(msg.sender, this); require(toCompare(allowance, value)); //do transferFrom bool success = token.transferFrom(msg.sender, this, value); require(success); //record the amount of local platform turn out lockBalance = SafeMath.add(lockBalance, value); // require(token.totalSupply >= lockBalance); //trigger Lock emit Lock(toPlatform, toAccount, bytes32(value), admin.tokenSymbol); } function unlock(string txid, bytes32 fromPlatform, address fromAccount, address toAccount, uint value) external payable { require(admin.status == 1 || admin.status == 3); require(xcPlugin.getStatus()); require(xcPlugin.existPlatform(fromPlatform)); require(toAccount != address(0)); // require(token.totalSupply >= value && value > 0); require(value > 0); //verify args by function xcPlugin.verify bool complete; bool verify; (complete, verify) = xcPlugin.verifyProposal(fromPlatform, fromAccount, toAccount, value, admin.tokenSymbol, txid); require(verify && !complete); //get contracts balance uint balance = token.balanceOf(this); //validate the balance of contract were less than amount require(toCompare(balance, value)); require(token.transfer(toAccount, value)); require(xcPlugin.commitProposal(fromPlatform, txid)); lockBalance = SafeMath.sub(lockBalance, value); emit Unlock(txid, fromPlatform, fromAccount, bytes32(value), admin.tokenSymbol); } function withdraw(address account, uint value) external payable { require(admin.account == msg.sender); require(account != address(0)); // require(token.totalSupply >= value && value > 0); require(value > 0); uint balance = token.balanceOf(this); require(toCompare(SafeMath.sub(balance, lockBalance), value)); bool success = token.transfer(account, value); require(success); } function transfer(address account, uint value) external payable { require(admin.account == msg.sender); require(account != address(0)); require(value > 0 && value >= address(this).balance); this.transfer(account, value); } function deposit() external payable { emit Deposit(msg.sender, bytes32(msg.value)); } /** * ###################### * # private function # * ###################### */ function toCompare(uint f, uint s) internal view returns (bool) { if (admin.compareSymbol == "-=") { return f > s; } else if (admin.compareSymbol == "+=") { return f >= s; } else { return false; } } } interface XCPluginInterface { /** * Open the contract service status. */ function start() external; /** * Close the contract service status. */ function stop() external; /** * Get contract service status. * @return contract service status. */ function getStatus() external view returns (bool); /** * Get the current contract platform name. * @return contract platform name. */ function getPlatformName() external view returns (bytes32); /** * Set the current contract administrator. * @param account account of contract administrator. */ function setAdmin(address account) external; /** * Get the current contract administrator. * @return contract administrator. */ function getAdmin() external view returns (address); /** * Add a contract trust caller. * @param caller account of caller. */ function addCaller(address caller) external; /** * Delete a contract trust caller. * @param caller account of caller. */ function deleteCaller(address caller) external; /** * Whether the trust caller exists. * @param caller account of caller. * @return whether exists. */ function existCaller(address caller) external view returns (bool); /** * Get all contract trusted callers. * @return al lcallers. */ function getCallers() external view returns (address[]); /** * Add a trusted platform name. * @param name a platform name. */ function addPlatform(bytes32 name) external; /** * Delete a trusted platform name. * @param name a platform name. */ function deletePlatform(bytes32 name) external; /** * Whether the trusted platform information exists. * @param name a platform name. * @return whether exists. */ function existPlatform(bytes32 name) external view returns (bool); /** * Add the trusted platform public key information. * @param platformName a platform name. * @param publicKey a public key. */ function addPublicKey(bytes32 platformName, address publicKey) external; /** * Delete the trusted platform public key information. * @param platformName a platform name. * @param publicKey a public key. */ function deletePublicKey(bytes32 platformName, address publicKey) external; /** * Whether the trusted platform public key information exists. * @param platformName a platform name. * @param publicKey a public key. */ function existPublicKey(bytes32 platformName, address publicKey) external view returns (bool); /** * Get the count of public key for the trusted platform. * @param platformName a platform name. * @return count of public key. */ function countOfPublicKey(bytes32 platformName) external view returns (uint); /** * Get the list of public key for the trusted platform. * @param platformName a platform name. * @return list of public key. */ function publicKeys(bytes32 platformName) external view returns (address[]); /** * Set the weight of a trusted platform. * @param platformName a platform name. * @param weight weight of platform. */ function setWeight(bytes32 platformName, uint weight) external; /** * Get the weight of a trusted platform. * @param platformName a platform name. * @return weight of platform. */ function getWeight(bytes32 platformName) external view returns (uint); /** * Initiate and vote on the transaction proposal. * @param fromPlatform name of form platform. * @param fromAccount name of to platform. * @param toAccount account of to platform. * @param value transfer amount. * @param tokenSymbol token Symbol. * @param txid transaction id. * @param sig transaction signature. */ function voteProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid, bytes sig) external; /** * Verify that the transaction proposal is valid. * @param fromPlatform name of form platform. * @param fromAccount name of to platform. * @param toAccount account of to platform. * @param value transfer amount. * @param tokenSymbol token Symbol. * @param txid transaction id. */ function verifyProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid) external view returns (bool, bool); /** * Commit the transaction proposal. * @param platformName a platform name. * @param txid transaction id. */ function commitProposal(bytes32 platformName, string txid) external returns (bool); /** * Get the transaction proposal information. * @param platformName a platform name. * @param txid transaction id. * @return status completion status of proposal. * @return fromAccount account of to platform. * @return toAccount account of to platform. * @return value transfer amount. * @return voters notarial voters. * @return weight The weight value of the completed time. */ function getProposal(bytes32 platformName, string txid) external view returns (bool status, address fromAccount, address toAccount, uint value, address[] voters, uint weight); /** * Delete the transaction proposal information. * @param platformName a platform name. * @param txid transaction id. */ function deleteProposal(bytes32 platformName, string txid) external; /** * Transfer the money(qtum/eth) from the contract account. * @param account the specified account. * @param value transfer amount. */ function transfer(address account, uint value) external payable; } contract XCPlugin is XCPluginInterface { /** * Contract Administrator * @field status Contract external service status. * @field platformName Current contract platform name. * @field tokenSymbol token Symbol. * @field account Current contract administrator. */ struct Admin { bool status; bytes32 platformName; bytes32 tokenSymbol; address account; } /** * Transaction Proposal * @field status Transaction proposal status(false:pending,true:complete). * @field fromAccount Account of form platform. * @field toAccount Account of to platform. * @field value Transfer amount. * @field tokenSymbol token Symbol. * @field voters Proposers. * @field weight The weight value of the completed time. */ struct Proposal { bool status; address fromAccount; address toAccount; uint value; bytes32 tokenSymbol; address[] voters; uint weight; } /** * Trusted Platform * @field status Trusted platform state(false:no trusted,true:trusted). * @field weight weight of platform. * @field publicKeys list of public key. * @field proposals list of proposal. */ struct Platform { bool status; uint weight; address[] publicKeys; mapping(string => Proposal) proposals; } Admin private admin; address[] private callers; mapping(bytes32 => Platform) private platforms; function XCPlugin() public { init(); } function init() internal { // Admin { status | platformName | tokenSymbol | account} admin.status = true; admin.platformName = "ETH"; admin.tokenSymbol = "INK"; admin.account = msg.sender; bytes32 platformName = "INK"; platforms[platformName].status = true; platforms[platformName].weight = 1; platforms[platformName].publicKeys.push(0x4230a12f5b0693dd88bb35c79d7e56a68614b199); platforms[platformName].publicKeys.push(0x07caf88941eafcaaa3370657fccc261acb75dfba); } function start() external { require(admin.account == msg.sender); if (!admin.status) { admin.status = true; } } function stop() external { require(admin.account == msg.sender); if (admin.status) { admin.status = false; } } function getStatus() external view returns (bool) { return admin.status; } function getPlatformName() external view returns (bytes32) { return admin.platformName; } function setAdmin(address account) external { require(account != address(0)); require(admin.account == msg.sender); if (admin.account != account) { admin.account = account; } } function getAdmin() external view returns (address) { return admin.account; } function addCaller(address caller) external { require(admin.account == msg.sender); if (!_existCaller(caller)) { callers.push(caller); } } function deleteCaller(address caller) external { require(admin.account == msg.sender); if (_existCaller(caller)) { bool exist; for (uint i = 0; i <= callers.length; i++) { if (exist) { if (i == callers.length) { delete callers[i - 1]; callers.length--; } else { callers[i - 1] = callers[i]; } } else if (callers[i] == caller) { exist = true; } } } } function existCaller(address caller) external view returns (bool) { return _existCaller(caller); } function getCallers() external view returns (address[]) { require(admin.account == msg.sender); return callers; } function addPlatform(bytes32 name) external { require(admin.account == msg.sender); require(name != ""); require(name != admin.platformName); if (!_existPlatform(name)) { platforms[name].status = true; if (platforms[name].weight == 0) { platforms[name].weight = 1; } } } function deletePlatform(bytes32 name) external { require(admin.account == msg.sender); require(name != admin.platformName); if (_existPlatform(name)) { platforms[name].status = false; } } function existPlatform(bytes32 name) external view returns (bool){ return _existPlatform(name); } function setWeight(bytes32 platformName, uint weight) external { require(admin.account == msg.sender); require(_existPlatform(platformName)); require(weight > 0); if (platforms[platformName].weight != weight) { platforms[platformName].weight = weight; } } function getWeight(bytes32 platformName) external view returns (uint) { require(admin.account == msg.sender); require(_existPlatform(platformName)); return platforms[platformName].weight; } function addPublicKey(bytes32 platformName, address publicKey) external { require(admin.account == msg.sender); require(_existPlatform(platformName)); require(publicKey != address(0)); address[] storage listOfPublicKey = platforms[platformName].publicKeys; for (uint i; i < listOfPublicKey.length; i++) { if (publicKey == listOfPublicKey[i]) { return; } } listOfPublicKey.push(publicKey); } function deletePublicKey(bytes32 platformName, address publickey) external { require(admin.account == msg.sender); require(_existPlatform(platformName)); address[] storage listOfPublicKey = platforms[platformName].publicKeys; bool exist; for (uint i = 0; i <= listOfPublicKey.length; i++) { if (exist) { if (i == listOfPublicKey.length) { delete listOfPublicKey[i - 1]; listOfPublicKey.length--; } else { listOfPublicKey[i - 1] = listOfPublicKey[i]; } } else if (listOfPublicKey[i] == publickey) { exist = true; } } } function existPublicKey(bytes32 platformName, address publicKey) external view returns (bool) { require(admin.account == msg.sender); return _existPublicKey(platformName, publicKey); } function countOfPublicKey(bytes32 platformName) external view returns (uint){ require(admin.account == msg.sender); require(_existPlatform(platformName)); return platforms[platformName].publicKeys.length; } function publicKeys(bytes32 platformName) external view returns (address[]){ require(admin.account == msg.sender); require(_existPlatform(platformName)); return platforms[platformName].publicKeys; } function voteProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid, bytes sig) external { require(admin.status); require(_existPlatform(fromPlatform)); bytes32 msgHash = hashMsg(fromPlatform, fromAccount, admin.platformName, toAccount, value, tokenSymbol, txid); // address publicKey = ecrecover(msgHash, v, r, s); address publicKey = recover(msgHash, sig); require(_existPublicKey(fromPlatform, publicKey)); Proposal storage proposal = platforms[fromPlatform].proposals[txid]; if (proposal.value == 0) { proposal.fromAccount = fromAccount; proposal.toAccount = toAccount; proposal.value = value; proposal.tokenSymbol = tokenSymbol; } else { require(proposal.fromAccount == fromAccount && proposal.toAccount == toAccount && proposal.value == value && proposal.tokenSymbol == tokenSymbol); } changeVoters(fromPlatform, publicKey, txid); } function verifyProposal(bytes32 fromPlatform, address fromAccount, address toAccount, uint value, bytes32 tokenSymbol, string txid) external view returns (bool, bool) { require(admin.status); require(_existPlatform(fromPlatform)); Proposal storage proposal = platforms[fromPlatform].proposals[txid]; if (proposal.status) { return (true, (proposal.voters.length >= proposal.weight)); } if (proposal.value == 0) { return (false, false); } require(proposal.fromAccount == fromAccount && proposal.toAccount == toAccount && proposal.value == value && proposal.tokenSymbol == tokenSymbol); return (false, (proposal.voters.length >= platforms[fromPlatform].weight)); } function commitProposal(bytes32 platformName, string txid) external returns (bool) { require(admin.status); require(_existCaller(msg.sender) || msg.sender == admin.account); require(_existPlatform(platformName)); require(!platforms[platformName].proposals[txid].status); platforms[platformName].proposals[txid].status = true; platforms[platformName].proposals[txid].weight = platforms[platformName].proposals[txid].voters.length; return true; } function getProposal(bytes32 platformName, string txid) external view returns (bool status, address fromAccount, address toAccount, uint value, address[] voters, uint weight){ require(admin.status); require(_existPlatform(platformName)); fromAccount = platforms[platformName].proposals[txid].fromAccount; toAccount = platforms[platformName].proposals[txid].toAccount; value = platforms[platformName].proposals[txid].value; voters = platforms[platformName].proposals[txid].voters; status = platforms[platformName].proposals[txid].status; weight = platforms[platformName].proposals[txid].weight; return; } function deleteProposal(bytes32 platformName, string txid) external { require(msg.sender == admin.account); require(_existPlatform(platformName)); delete platforms[platformName].proposals[txid]; } function transfer(address account, uint value) external payable { require(admin.account == msg.sender); require(account != address(0)); require(value > 0 && value >= address(this).balance); this.transfer(account, value); } /** * ###################### * # private function # * ###################### */ function hashMsg(bytes32 fromPlatform, address fromAccount, bytes32 toPlatform, address toAccount, uint value, bytes32 tokenSymbol, string txid) internal pure returns (bytes32) { return sha256(bytes32ToStr(fromPlatform), ":0x", uintToStr(uint160(fromAccount), 16), ":", bytes32ToStr(toPlatform), ":0x", uintToStr(uint160(toAccount), 16), ":", uintToStr(value, 10), ":", bytes32ToStr(tokenSymbol), ":", txid); } function changeVoters(bytes32 platformName, address publicKey, string txid) internal { address[] storage voters = platforms[platformName].proposals[txid].voters; bool change = true; for (uint i = 0; i < voters.length; i++) { if (voters[i] == publicKey) { change = false; } } if (change) { voters.push(publicKey); } } function bytes32ToStr(bytes32 b) internal pure returns (string) { uint length = b.length; for (uint i = 0; i < b.length; i++) { if (b[b.length - 1 - i] == "") { length -= 1; } else { break; } } bytes memory bs = new bytes(length); for (uint j = 0; j < length; j++) { bs[j] = b[j]; } return string(bs); } function uintToStr(uint value, uint base) internal pure returns (string) { uint _value = value; uint length = 0; bytes16 tenStr = "0123456789abcdef"; while (true) { if (_value > 0) { length ++; _value = _value / base; } else { break; } } if (base == 16) { length = 40; } bytes memory bs = new bytes(length); for (uint i = 0; i < length; i++) { bs[length - 1 - i] = tenStr[value % base]; value = value / base; } return string(bs); } function _existCaller(address caller) internal view returns (bool) { for (uint i = 0; i < callers.length; i++) { if (callers[i] == caller) { return true; } } return false; } function _existPlatform(bytes32 name) internal view returns (bool){ return platforms[name].status; } function _existPublicKey(bytes32 platformName, address publicKey) internal view returns (bool) { address[] memory listOfPublicKey = platforms[platformName].publicKeys; for (uint i = 0; i < listOfPublicKey.length; i++) { if (listOfPublicKey[i] == publicKey) { return true; } } return false; } function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) { v += 27; } return ecrecover(hash, v, r, s); } }
* Contract Administrator @field status Contract external service status. @field platformName Current contract platform name. @field tokenSymbol token Symbol. @field account Current contract administrator./
struct Admin { bool status; bytes32 platformName; bytes32 tokenSymbol; address account; }
14,619,503
[ 1, 8924, 7807, 14207, 632, 1518, 1267, 13456, 3903, 1156, 1267, 18, 632, 1518, 4072, 461, 6562, 6835, 4072, 508, 18, 632, 1518, 1147, 5335, 1147, 8565, 18, 632, 1518, 2236, 6562, 6835, 22330, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 7807, 288, 203, 203, 3639, 1426, 1267, 31, 203, 203, 3639, 1731, 1578, 4072, 461, 31, 203, 203, 3639, 1731, 1578, 1147, 5335, 31, 203, 203, 3639, 1758, 2236, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2018 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental "ABIEncoderV2"; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { ERC20Wrapper } from "../../lib/ERC20Wrapper.sol"; import { ExchangeWrapperLibrary } from "../lib/ExchangeWrapperLibrary.sol"; import { ICore } from "../interfaces/ICore.sol"; import { KyberNetworkProxyInterface } from "../../external/KyberNetwork/KyberNetworkProxyInterface.sol"; import { LibBytes } from "../../external/0x/LibBytes.sol"; /** * @title KyberNetworkWrapper * @author Set Protocol * * The KyberNetworkWrapper contract wrapper to interface with KyberNetwork for reserve liquidity */ contract KyberNetworkWrapper { using LibBytes for bytes; using SafeMath for uint256; /* ============ State Variables ============ */ address public core; address public kyberNetworkProxy; address public setTransferProxy; uint256 public KYBER_TRADE_LENGTH = 160; // ============ Structs ============ struct KyberTrade { address destinationToken; address sourceToken; uint256 sourceTokenQuantity; uint256 minimumConversionRate; uint256 maxDestinationQuantity; } /* ============ Constructor ============ */ /** * Initialize exchange wrapper with required addresses to facilitate Kyber trades * * @param _core Deployed Core contract * @param _kyberNetworkProxy KyberNetwork contract for filling orders * @param _setTransferProxy Set Protocol transfer proxy contract */ constructor( address _core, address _kyberNetworkProxy, address _setTransferProxy ) public { core = _core; kyberNetworkProxy = _kyberNetworkProxy; setTransferProxy = _setTransferProxy; } /* ============ Public Functions ============ */ /** * Returns the conversion rate between the issuance order maker token and the set component token * in 18 decimals, regardless of component token's decimals * * @param _sourceTokens Address of source token used in exchange orders * @param _destinationTokens Address of destination token to trade for * @param _quantities Amount of maker token to exchange for component token * @return uint256[] Conversion rate in wei * @return uint256[] Slippage in wei */ function conversionRate( address[] calldata _sourceTokens, address[] calldata _destinationTokens, uint256[] calldata _quantities ) external view returns (uint256[] memory, uint256[] memory) { uint256 rateCount = _sourceTokens.length; uint256[] memory expectedRates = new uint256[](rateCount); uint256[] memory slippageRates = new uint256[](rateCount); for (uint256 i = 0; i < rateCount; i++) { (expectedRates[i], slippageRates[i]) = KyberNetworkProxyInterface(kyberNetworkProxy).getExpectedRate( _sourceTokens[i], _destinationTokens[i], _quantities[i] ); } return ( expectedRates, slippageRates ); } /** * IExchangeWrapper interface delegate method. * * Parses and executes Kyber trades. Depending on conversion rate, Kyber trades may result in change. * We currently pass change back to the issuance order maker, exploring how it can safely be passed to the taker. * * * @param _exchangeData Standard exchange wrapper interface object containing exchange metadata * @param _tradesData Arbitrary bytes data for any information to pass to the exchange * @return ExchangeWrapperLibrary.ExchangeResults Struct containing component acquisition results */ function exchange( ExchangeWrapperLibrary.ExchangeData memory _exchangeData, bytes memory _tradesData ) public returns (ExchangeWrapperLibrary.ExchangeResults memory) { require( ICore(core).validModules(msg.sender), "KyberNetworkWrapper.exchange: Sender must be approved module" ); uint256 tradesCount = _exchangeData.orderCount; address[] memory sendTokens = new address[](tradesCount); address[] memory receiveTokens = new address[](tradesCount); uint256[] memory receiveTokensAmounts = new uint256[](tradesCount); // Parse and execute the trade at the current offset via the KyberNetworkProxy, each kyber trade is 160 bytes for (uint256 i = 0; i < tradesCount; i++) { // Parse Kyber trade at the current offset KyberTrade memory trade = parseKyberTrade( _tradesData, i.mul(KYBER_TRADE_LENGTH) ); // Ensure the caller's source token is allowed to be transferred by // KyberNetworkProxy as the source token ERC20Wrapper.ensureAllowance( trade.sourceToken, address(this), kyberNetworkProxy, trade.sourceTokenQuantity ); // Track the send tokens to ensure any leftovers are returned to the user sendTokens[i] = trade.sourceToken; // Execute Kyber trade (receiveTokens[i], receiveTokensAmounts[i]) = tradeOnKyberReserve(trade); } // Return leftover send tokens to the original caller ExchangeWrapperLibrary.returnLeftoverSendTokens( sendTokens, _exchangeData.caller ); return ExchangeWrapperLibrary.ExchangeResults({ receiveTokens: receiveTokens, receiveTokenAmounts: receiveTokensAmounts }); } /* ============ Private ============ */ /** * Parses and executes Kyber trade * * @return address Address of set component to trade for * @return uint256 Amount of set component received in trade */ function tradeOnKyberReserve( KyberTrade memory _trade ) private returns (address, uint256) { // Execute Kyber trade via deployed KyberNetworkProxy contract uint256 destinationTokenQuantity = KyberNetworkProxyInterface(kyberNetworkProxy).trade( _trade.sourceToken, _trade.sourceTokenQuantity, _trade.destinationToken, address(this), _trade.maxDestinationQuantity, _trade.minimumConversionRate, address(0) ); // Ensure the destination token is allowed to be transferred by Set TransferProxy ERC20Wrapper.ensureAllowance( _trade.destinationToken, address(this), setTransferProxy, destinationTokenQuantity ); return ( _trade.destinationToken, destinationTokenQuantity ); } /* * Parses the bytes array for a Kyber trade * * | Data | Location | * |----------------------------|-------------------------------| * | destinationToken | 0 | * | sourceTokenQuantity | 32 | * | sourceTokenQuantity | 64 | * | minimumConversionRate | 96 | * | maxDestinationQuantity | 128 | * * @param _tradesData Byte array of (multiple) Kyber trades * @param _offset Offset to start scanning for Kyber trade body * @return KyberTrade KyberTrade struct */ function parseKyberTrade( bytes memory _tradesData, uint256 _offset ) private pure returns (KyberTrade memory) { KyberTrade memory trade; uint256 tradeDataStart = _tradesData.contentAddress().add(_offset); assembly { mstore(trade, mload(tradeDataStart)) // destinationToken mstore(add(trade, 32), mload(add(tradeDataStart, 32))) // sourceToken mstore(add(trade, 64), mload(add(tradeDataStart, 64))) // sourceTokenQuantity mstore(add(trade, 96), mload(add(tradeDataStart, 96))) // minimumConversionRate mstore(add(trade, 128), mload(add(tradeDataStart, 128))) // maxDestinationQuantity } return trade; } }
Parses the bytes array for a Kyber trade | Data | Location | |----------------------------|-------------------------------| | destinationToken | 0 | | sourceTokenQuantity | 32 | | sourceTokenQuantity | 64 | | minimumConversionRate | 96 | | maxDestinationQuantity | 128 | @param _tradesData Byte array of (multiple) Kyber trades @param _offset Offset to start scanning for Kyber trade body @return KyberTrade KyberTrade struct/
function parseKyberTrade( bytes memory _tradesData, uint256 _offset ) private pure returns (KyberTrade memory) { KyberTrade memory trade; uint256 tradeDataStart = _tradesData.contentAddress().add(_offset); assembly { } return trade; }
12,998,621
[ 1, 6656, 326, 1731, 526, 364, 279, 1475, 93, 744, 18542, 571, 1910, 15604, 571, 7050, 8227, 571, 571, 1271, 7620, 96, 1271, 18753, 96, 571, 2929, 1345, 6647, 571, 374, 11794, 571, 571, 1084, 1345, 12035, 3639, 571, 3847, 18701, 571, 571, 1084, 1345, 12035, 3639, 571, 5178, 18701, 571, 571, 5224, 6814, 4727, 1377, 571, 19332, 18701, 571, 571, 943, 5683, 12035, 377, 571, 8038, 21821, 571, 282, 389, 313, 16601, 751, 565, 3506, 526, 434, 261, 9622, 13, 1475, 93, 744, 1284, 5489, 282, 389, 3348, 3639, 9874, 358, 787, 21138, 364, 1475, 93, 744, 18542, 1417, 327, 1475, 93, 744, 22583, 377, 1475, 93, 744, 22583, 1958, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1109, 47, 93, 744, 22583, 12, 203, 3639, 1731, 3778, 389, 313, 16601, 751, 16, 203, 3639, 2254, 5034, 389, 3348, 203, 565, 262, 203, 3639, 3238, 203, 3639, 16618, 203, 3639, 1135, 261, 47, 93, 744, 22583, 3778, 13, 203, 565, 288, 203, 3639, 1475, 93, 744, 22583, 3778, 18542, 31, 203, 203, 3639, 2254, 5034, 18542, 751, 1685, 273, 389, 313, 16601, 751, 18, 1745, 1887, 7675, 1289, 24899, 3348, 1769, 203, 203, 3639, 19931, 288, 203, 3639, 289, 203, 203, 3639, 327, 18542, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x2A391abb0E042566A7C24249ECDb2533EaB5D76F/sources/https_/raw.githubusercontent.com/0xcert/ethereum-erc721/master/src/contracts/tokens/nf-token-enumerable.sol
* @dev Returns the count of all existing NFTokens. @return Total supply of NFTs./
function totalSupply() external override view returns (uint256) { return tokens.length; }
726,821
[ 1, 1356, 326, 1056, 434, 777, 2062, 423, 4464, 3573, 18, 327, 10710, 14467, 434, 423, 4464, 87, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2078, 3088, 1283, 1435, 203, 565, 3903, 203, 565, 3849, 203, 565, 1476, 203, 565, 1135, 261, 11890, 5034, 13, 203, 225, 288, 203, 565, 327, 2430, 18, 2469, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x549a5Cf3557D92a8B0fAD549499Eba4d41836c10/sources/contracts/Treasure.sol
* @dev Lock funds for farming pool @param lockAmount amount of locked wsd @param farmingStart date when farming pool is start @param _lockDuration duration of locked funds @param epochDuration duration of farming pool @param fee percent how many will charged @param farmingPool address of farming poll related @param account address if initiator deploy/
function lock( uint256 lockAmount, uint256 farmingStart, uint256 _lockDuration, uint256 epochDuration, uint8 fee, address farmingPool, address account ) external override { require(msg.sender == farmingRewardFactory, 'Allowed only for factory'); require(epochDuration > 0, 'Can not be zero duration'); require(fee <= MAX_COMMISSION, 'Too high fee'); require(!isAlreadyLockedContract[farmingPool], 'Already locked'); require(farmingStart >= block.timestamp, 'Can not be in past'); uint256 endDate; uint256 lockDurationModifier; if (epochDuration >= ONE_YEAR) { endDate = farmingStart + epochDuration; lockDurationModifier = epochDuration; endDate = farmingStart + ONE_YEAR; lockDurationModifier = ONE_YEAR; } require(_lockDuration == lockDurationModifier, 'Invalid duration'); contributions[account][farmingPool] = lockAmount; lockFee[account][farmingPool] = fee; startFarmingPool[account][farmingPool] = farmingStart; totalLocked = totalLocked + lockAmount; lockDuration[account][farmingPool] = _lockDuration; isDistributedLockedFunds[account][farmingPool] = false; isAlreadyLockedContract[farmingPool] = true; finishFarmingPool[account][farmingPool] = endDate; IERC20(wsd).safeTransferFrom(account, address(this), lockAmount); emit FundsLocked(account, lockAmount); }
4,923,629
[ 1, 2531, 284, 19156, 364, 284, 4610, 310, 2845, 225, 2176, 6275, 3844, 434, 8586, 4945, 72, 225, 284, 4610, 310, 1685, 1509, 1347, 284, 4610, 310, 2845, 353, 787, 225, 389, 739, 5326, 3734, 434, 8586, 284, 19156, 225, 7632, 5326, 3734, 434, 284, 4610, 310, 2845, 225, 14036, 5551, 3661, 4906, 903, 1149, 2423, 225, 284, 4610, 310, 2864, 1758, 434, 284, 4610, 310, 7672, 3746, 225, 2236, 1758, 309, 26030, 7286, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2176, 12, 203, 3639, 2254, 5034, 2176, 6275, 16, 203, 3639, 2254, 5034, 284, 4610, 310, 1685, 16, 203, 3639, 2254, 5034, 389, 739, 5326, 16, 203, 3639, 2254, 5034, 7632, 5326, 16, 203, 3639, 2254, 28, 14036, 16, 203, 3639, 1758, 284, 4610, 310, 2864, 16, 203, 3639, 1758, 2236, 203, 565, 262, 3903, 3849, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 284, 4610, 310, 17631, 1060, 1733, 16, 296, 5042, 1338, 364, 3272, 8284, 203, 3639, 2583, 12, 12015, 5326, 405, 374, 16, 296, 2568, 486, 506, 3634, 3734, 8284, 203, 3639, 2583, 12, 21386, 1648, 4552, 67, 4208, 15566, 16, 296, 10703, 3551, 14036, 8284, 203, 3639, 2583, 12, 5, 291, 9430, 8966, 8924, 63, 74, 4610, 310, 2864, 6487, 296, 9430, 8586, 8284, 203, 3639, 2583, 12, 74, 4610, 310, 1685, 1545, 1203, 18, 5508, 16, 296, 2568, 486, 506, 316, 8854, 8284, 203, 3639, 2254, 5034, 13202, 31, 203, 3639, 2254, 5034, 2176, 5326, 9829, 31, 203, 203, 3639, 309, 261, 12015, 5326, 1545, 15623, 67, 15137, 13, 288, 203, 5411, 13202, 273, 284, 4610, 310, 1685, 397, 7632, 5326, 31, 203, 5411, 2176, 5326, 9829, 273, 7632, 5326, 31, 203, 5411, 13202, 273, 284, 4610, 310, 1685, 397, 15623, 67, 15137, 31, 203, 5411, 2176, 5326, 9829, 273, 15623, 67, 15137, 31, 203, 3639, 289, 203, 3639, 2583, 24899, 739, 5326, 422, 2176, 5326, 9829, 16, 296, 1941, 3734, 8284, 203, 203, 3639, 13608, 6170, 63, 4631, 6362, 74, 4610, 310, 2864, 65, 273, 2 ]
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/lifecycle/Destructible.sol"; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "./StowHub.sol"; import "./StowUsers.sol"; import "./interfaces/IrisScoreProviderI.sol"; contract StowRecords is Ownable, Pausable, Destructible { using SafeMath for uint; // Struct of a stow record // A stow record is identified by its data hash, which is // keccak256(data + optional nonce) struct Record { // owner of the record address owner; // hash of the plaintext metadata bytes32 metadataHash; // attester signatures mapping (address => bool) sigs; // count of attester sigs uint sigCount; // calculated iris score uint irisScore; // ipfs path of the encrypted data string dataUri; // timestamp of the block when the record is added uint timestamp; // non zero score returned from the specific IRIS provider oracles mapping (address => uint256) irisProvidersReports; } event StowUpdateRecordsIris( bytes32 indexed dataHash, address indexed irisProvidersAddress, uint256 val, address indexed sender) ; event StowRecordAdded( bytes32 indexed dataHash, address indexed owner, string metadata ); event StowRecordSigAdded( bytes32 indexed dataHash, address indexed attester, uint irisScore ); event StowReward(bytes32 indexed dataHash, address indexed owner, uint256 value, address tokenContract); StowHub public hub; // all stow records // dataHash => record mapping mapping(bytes32 => Record) public records; /* Modifiers */ modifier onlyUser() { require(hub.usersContract().isUser(msg.sender) == true); _; } modifier hasProvenance(address user) { require(hub.usersContract().provenanceOf(user) > 0); _; } /* Constructor */ constructor(StowHub _hub) public { hub = _hub; } /* Fallback function */ function () public { } /* External functions */ function addRecordByAdmin( bytes32 dataHash, address owner, address attester, string metadata, string dataUri) onlyOwner whenNotPaused external returns (bool) { require(_addRecord(dataHash, owner, metadata, dataUri) == true); if (attester != address(0)) { require(_addSig(dataHash, attester)); } return true; } /// @param dataHash the datahash of the record to be scored /// @param irisProvidersAddress address of the oracle contract function updateIris(bytes32 dataHash, address irisProvidersAddress) external onlyOwner whenNotPaused returns (uint256) { require(irisProvidersAddress != address(0)); require(dataHash != 0); Record storage record = records[dataHash]; require(records[dataHash].timestamp != 0); // make sure the irisProviders is only called once require(record.irisProvidersReports[irisProvidersAddress] == 0); IrisScoreProviderI currOracle = IrisScoreProviderI(irisProvidersAddress); uint256 val = currOracle.report(dataHash); // zero and less values are reverted require(val > 0); record.irisScore = record.irisScore.add(val); // keep a record of iris score breakdown record.irisProvidersReports[irisProvidersAddress] = val; emit StowUpdateRecordsIris(dataHash, irisProvidersAddress, val, msg.sender); return val; } function getIrisProvidersReport(bytes32 dataHash, address irisProvider) external view returns (uint256) { return records[dataHash].irisProvidersReports[irisProvider]; } /* Public functions */ /// Add a record by user without any provider's signatures. /// @param dataHash the hash of the data /// @param metadata plaintext metadata for the record /// @param dataUri the ipfs path of the encrypted data function addRecord( bytes32 dataHash, string metadata, string dataUri) onlyUser whenNotPaused public returns (bool) { require( _addRecord(dataHash, msg.sender, metadata, dataUri) == true ); return true; } /// Add a record by user without any provider's signatures and get a reward. /// /// @param dataHash the hash of the data /// @param metadata plaintext metadata for the record /// @param dataUri the data uri path of the encrypted data /// @param token the ERC20 token address for the rewarding token function addRecordwithReward ( bytes32 dataHash, string metadata, string dataUri, address token) onlyUser whenNotPaused public returns (bool) { // the amount of tokens to be transferred uint256 reward = 1 finney; require (token != address (0)); require (token != address (this)); ERC20 tokenInstance = ERC20 (token); require ( _addRecord (dataHash, msg.sender, metadata, dataUri) == true ); // tokens are provided by the contracts balance require(tokenInstance.transfer (msg.sender, reward)); emit StowReward (dataHash, msg.sender, reward, token); return true; } /// Add a record by a data provider. /// @param dataHash the hash of the data /// @param owner owner of the record /// @param metadata plaintext metadata for the record /// @param dataUri the ipfs path of the encrypted data function addRecordByProvider( bytes32 dataHash, address owner, string metadata, string dataUri) onlyUser hasProvenance(msg.sender) whenNotPaused public returns (bool) { // add the file first require(_addRecord(dataHash, owner, metadata, dataUri) == true); // add provider's sig to the file require(_addSig(dataHash, msg.sender)); return true; } /// Add a provider's signature to a stow record, /// i.e. adding an attestation /// This function is only callable by a provider /// @param dataHash the data hash of the stow record function addSigByProvider(bytes32 dataHash) hasProvenance(msg.sender) whenNotPaused public returns (bool) { require(_addSig(dataHash, msg.sender)); return true; } /// Add a provider's signature to a stow record /// i.e. adding an attestation /// This function can be called by anyone. As long as the signatures are /// indeed from a provider, the sig will be added to the record. /// The signature should cover the root hash, which is /// hash(hash(data), hash(metadata)) /// @param dataHash the data hash of a stow record /// @param r signature: R /// @param s signature: S /// @param v signature: V function addSig(bytes32 dataHash, bytes32 r, bytes32 s, uint8 v) public whenNotPaused returns (bool) { // find the root hash of the record bytes32 rootHash = rootHashOf(dataHash); // recover the provider's address from signature address provider = recover(rootHash, r, s, v); // add sig require(_addSig(dataHash, provider)); return true; } function recover(bytes32 message, bytes32 r, bytes32 s, uint8 v) public pure returns (address) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, message)); return ecrecover(prefixedHash, v, r, s); } function recordOwnerOf(bytes32 dataHash) public view returns (address) { return records[dataHash].owner; } function rootHashOf(bytes32 dataHash) public view returns (bytes32) { return keccak256(abi.encodePacked(dataHash, records[dataHash].metadataHash)); } function sigExists(bytes32 dataHash, address provider) public view returns (bool) { return records[dataHash].sigs[provider]; } /* Internal functions */ function _addRecord( bytes32 dataHash, address owner, string metadata, string dataUri) internal returns (bool) { // validate input require(dataHash != 0); require(bytes(dataUri).length != 0); bytes32 metadataHash = keccak256(abi.encodePacked(metadata)); // the file must be new require(records[dataHash].timestamp == 0); // verify owner require(hub.usersContract().isUser(owner) == true); // add record records[dataHash] = Record({ owner: owner, metadataHash: metadataHash, sigCount: 0, irisScore: 0, dataUri: dataUri, // solium-disable-next-line security/no-block-members timestamp: block.timestamp }); // emit event emit StowRecordAdded(dataHash, owner, metadata); return true; } function _addSig(bytes32 dataHash, address provider) hasProvenance(provider) internal returns (bool) { Record storage record = records[dataHash]; // the file must exist require(record.timestamp != 0); // the provider must not have signed the file already require(!record.sigs[provider]); uint provenanceScore = hub.usersContract().provenanceOf(provider); // add signature record.sigCount = record.sigCount.add(1); record.sigs[provider] = true; // update iris score record.irisScore = record.irisScore.add(provenanceScore); // emit event emit StowRecordSigAdded(dataHash, provider, record.irisScore); return true; } }
validate input the file must be new verify owner add record solium-disable-next-line security/no-block-members
function _addRecord( bytes32 dataHash, address owner, string metadata, string dataUri) internal returns (bool) { require(dataHash != 0); require(bytes(dataUri).length != 0); bytes32 metadataHash = keccak256(abi.encodePacked(metadata)); require(records[dataHash].timestamp == 0); require(hub.usersContract().isUser(owner) == true); records[dataHash] = Record({ owner: owner, metadataHash: metadataHash, sigCount: 0, irisScore: 0, dataUri: dataUri, timestamp: block.timestamp }); return true; }
983,488
[ 1, 5662, 810, 326, 585, 1297, 506, 394, 3929, 3410, 527, 1409, 3704, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 2629, 17, 7640, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1289, 2115, 12, 203, 3639, 1731, 1578, 501, 2310, 16, 1758, 3410, 16, 533, 1982, 16, 533, 501, 3006, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 892, 2310, 480, 374, 1769, 203, 3639, 2583, 12, 3890, 12, 892, 3006, 2934, 2469, 480, 374, 1769, 203, 3639, 1731, 1578, 1982, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 4165, 10019, 203, 203, 3639, 2583, 12, 7094, 63, 892, 2310, 8009, 5508, 422, 374, 1769, 203, 3639, 2583, 12, 14986, 18, 5577, 8924, 7675, 291, 1299, 12, 8443, 13, 422, 638, 1769, 203, 3639, 3853, 63, 892, 2310, 65, 273, 5059, 12590, 203, 5411, 3410, 30, 3410, 16, 203, 5411, 1982, 2310, 30, 1982, 2310, 16, 203, 5411, 3553, 1380, 30, 374, 16, 203, 5411, 9482, 291, 7295, 30, 374, 16, 203, 5411, 501, 3006, 30, 501, 3006, 16, 203, 5411, 2858, 30, 1203, 18, 5508, 203, 5411, 15549, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xa980d4c0C2E48d305b582AA439a3575e3de06f0E/sources/contracts/lybra/pools/base/LybraEUSDVaultBase.sol
* @notice When stETH balance increases through LSD or other reasons, the excess income is sold for eUSD, allocated to eUSD holders through rebase mechanism. Emits a `LSDistribution` event. Requirements: - stETH balance in the contract cannot be less than totalDepositedAsset after exchange. @dev Income is used to cover accumulated Service Fee first./* @notice Choose a Redemption Provider, Rigid Redeem `eusdAmount` of eUSD and get 1:1 value of collateral Emits a `RigidRedemption` event. Requirements: - `provider` must be a Redemption Provider - `provider`debt must equal to or above`eusdAmount` @dev Service Fee for rigidRedemption `redemptionFee` is set to 0.5% by default, can be revised by DAO./
function excessIncomeDistribution(uint256 payAmount) external virtual; function rigidRedemption(address provider, uint256 eusdAmount, uint256 minReceiveAmount) external virtual { require(provider != msg.sender, "CBS"); require(configurator.isRedemptionProvider(provider), "provider is not a RedemptionProvider"); require(borrowed[provider] >= eusdAmount, "eusdAmount cannot surpass providers debt"); uint256 assetPrice = getAssetPrice(); uint256 providerCollateralRatio = (depositedAsset[provider] * assetPrice * 100) / borrowed[provider]; require(providerCollateralRatio >= 100 * 1e18, "The provider's collateral ratio should be not less than 100%."); _repay(msg.sender, provider, eusdAmount); uint256 collateralAmount = eusdAmount * 1e18 * (10_000 - configurator.redemptionFee()) / assetPrice / 10_000; uint256 sendAmount = checkWithdrawal(provider, collateralAmount); require(sendAmount >= minReceiveAmount, "EL"); depositedAsset[provider] -= collateralAmount; totalDepositedAsset -= collateralAmount; collateralAsset.safeTransfer(msg.sender, sendAmount); emit RigidRedemption(msg.sender, provider, eusdAmount, sendAmount, block.timestamp); }
15,493,966
[ 1, 9434, 384, 1584, 44, 11013, 7033, 3304, 3059, 511, 9903, 578, 1308, 14000, 16, 326, 23183, 316, 5624, 353, 272, 1673, 364, 425, 3378, 40, 16, 11977, 358, 425, 3378, 40, 366, 4665, 3059, 283, 1969, 12860, 18, 7377, 1282, 279, 1375, 3045, 9003, 68, 871, 18, 29076, 30, 300, 384, 1584, 44, 11013, 316, 326, 6835, 2780, 506, 5242, 2353, 2078, 758, 1724, 329, 6672, 1839, 7829, 18, 225, 657, 5624, 353, 1399, 358, 5590, 24893, 1956, 30174, 1122, 18, 19, 225, 25593, 279, 868, 19117, 375, 7561, 16, 534, 28542, 868, 24903, 1375, 10315, 72, 6275, 68, 434, 425, 3378, 40, 471, 336, 404, 30, 21, 460, 434, 4508, 2045, 287, 7377, 1282, 279, 1375, 54, 28542, 426, 19117, 375, 68, 871, 18, 29076, 30, 300, 1375, 6778, 68, 1297, 506, 279, 868, 19117, 375, 7561, 300, 1375, 6778, 68, 323, 23602, 1297, 3959, 358, 578, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 23183, 382, 5624, 9003, 12, 11890, 5034, 8843, 6275, 13, 3903, 5024, 31, 203, 203, 565, 445, 436, 28542, 426, 19117, 375, 12, 2867, 2893, 16, 2254, 5034, 425, 407, 72, 6275, 16, 2254, 5034, 1131, 11323, 6275, 13, 3903, 5024, 288, 203, 3639, 2583, 12, 6778, 480, 1234, 18, 15330, 16, 315, 8876, 55, 8863, 203, 3639, 2583, 12, 1425, 10662, 18, 291, 426, 19117, 375, 2249, 12, 6778, 3631, 315, 6778, 353, 486, 279, 868, 19117, 375, 2249, 8863, 203, 3639, 2583, 12, 70, 15318, 329, 63, 6778, 65, 1545, 425, 407, 72, 6275, 16, 315, 10315, 72, 6275, 2780, 5056, 5466, 9165, 18202, 88, 8863, 203, 3639, 2254, 5034, 3310, 5147, 273, 24689, 5147, 5621, 203, 3639, 2254, 5034, 2893, 13535, 2045, 287, 8541, 273, 261, 323, 1724, 329, 6672, 63, 6778, 65, 380, 3310, 5147, 380, 2130, 13, 342, 29759, 329, 63, 6778, 15533, 203, 3639, 2583, 12, 6778, 13535, 2045, 287, 8541, 1545, 2130, 380, 404, 73, 2643, 16, 315, 1986, 2893, 1807, 4508, 2045, 287, 7169, 1410, 506, 486, 5242, 2353, 2130, 9, 1199, 1769, 203, 3639, 389, 266, 10239, 12, 3576, 18, 15330, 16, 2893, 16, 425, 407, 72, 6275, 1769, 203, 3639, 2254, 5034, 4508, 2045, 287, 6275, 273, 425, 407, 72, 6275, 380, 404, 73, 2643, 380, 261, 2163, 67, 3784, 300, 18700, 18, 266, 19117, 375, 14667, 10756, 342, 3310, 5147, 342, 1728, 67, 3784, 31, 203, 3639, 2254, 5034, 1366, 6275, 273, 866, 1190, 9446, 287, 12, 6778, 16, 4508, 2045, 2 ]
./full_match/5/0x58e0D16Cd95d5Ef71b62Ec26deD873D25edfC782/sources/contractcode/SketchySquirrel.sol
INITIATE THE ROBES MAP WITH ALL AVAILABLE ROBES
constructor() ERC721("Sketchy Squirrels", "SS") { ROBES ["No Robe"] = "00"; ROBES ["Divine Robe"] = "01"; ROBES ["Divine Robe of Giants"] = "02"; ROBES ["Divine Robe of Perfection"] = "03"; ROBES ["Divine Robe of Rage"] = "04"; ROBES ["Divine Robe of Protection"] = "05"; ROBES ["Divine Robe of the Twins"] = "06"; ROBES ["Divine Robe of Anger"] = "07"; ROBES ["Divine Robe of Brilliance"] = "08"; ROBES ["Divine Robe of Fury"] = "09"; ROBES ["Divine Robe of Detection"] = "10"; ROBES ["Divine Robe of Titans"] = "11"; ROBES ["Divine Robe of Power"] = "12"; ROBES ["Divine Robe of Skill"] = "13"; ROBES ["Divine Robe of Elightenment"] = "14"; ROBES ["Divine Robe of the Fox"] = "15"; ROBES ["Divine Robe of Vitriol"] = "16"; }
1,960,446
[ 1, 12919, 45, 1777, 12786, 534, 5704, 3991, 12815, 13601, 8061, 15068, 20027, 534, 5704, 3991, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 27, 5340, 2932, 22900, 93, 348, 372, 481, 2878, 87, 3113, 315, 1260, 7923, 288, 7010, 3639, 534, 5704, 3991, 8247, 2279, 19686, 73, 11929, 273, 315, 713, 14432, 203, 3639, 534, 5704, 3991, 8247, 7244, 558, 19686, 73, 11929, 273, 315, 1611, 14432, 203, 3639, 534, 5704, 3991, 8247, 7244, 558, 19686, 73, 434, 611, 77, 4388, 11929, 273, 315, 3103, 14432, 203, 3639, 534, 5704, 3991, 8247, 7244, 558, 19686, 73, 434, 5722, 74, 794, 11929, 273, 315, 4630, 14432, 203, 3639, 534, 5704, 3991, 8247, 7244, 558, 19686, 73, 434, 534, 410, 11929, 273, 315, 3028, 14432, 203, 3639, 534, 5704, 3991, 8247, 7244, 558, 19686, 73, 434, 1186, 9694, 11929, 273, 315, 6260, 14432, 203, 3639, 534, 5704, 3991, 8247, 7244, 558, 19686, 73, 434, 326, 12694, 2679, 11929, 273, 315, 7677, 14432, 203, 3639, 534, 5704, 3991, 8247, 7244, 558, 19686, 73, 434, 1922, 693, 11929, 273, 315, 8642, 14432, 203, 3639, 534, 5704, 3991, 8247, 7244, 558, 19686, 73, 434, 605, 86, 16607, 1359, 11929, 273, 315, 6840, 14432, 203, 3639, 534, 5704, 3991, 8247, 7244, 558, 19686, 73, 434, 478, 22498, 11929, 273, 315, 5908, 14432, 203, 3639, 534, 5704, 3991, 8247, 7244, 558, 19686, 73, 434, 8083, 794, 11929, 273, 315, 2163, 14432, 203, 3639, 534, 5704, 3991, 8247, 7244, 558, 19686, 73, 434, 399, 305, 634, 11929, 273, 315, 2499, 14432, 203, 3639, 534, 5704, 3991, 8247, 7244, 558, 19686, 73, 434, 23783, 11929, 273, 315, 2138, 14432, 203, 3639, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-07-20 */ /* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: BinaryOptionMarket.sol * * Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/BinaryOptionMarket.sol * Docs: https://docs.synthetix.io/contracts/BinaryOptionMarket * * Contract Dependencies: * - IAddressResolver * - IBinaryOption * - IBinaryOptionMarket * - IBinaryOptionMarketManager * - IERC20 * - MixinResolver * - Owned * - Pausable * - SelfDestructible * Libraries: * - AddressListLib * - SafeDecimalMath * - SafeMath * * MIT License * =========== * * Copyright (c) 2020 Synthetix * * 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 */ /* =============================================== * Flattened with Solidifier by Coinage * * https://solidifier.coina.ge * =============================================== */ pragma solidity ^0.5.16; // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } interface IIssuer { // Views function anySynthOrSNXRateIsStale() external view returns (bool anyRateStale); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function canBurnSynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesStale(address _issuer) external view returns (uint cratio, bool anyRateIsStale); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function lastIssueEvent(address account) external view returns (uint); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint); function transferableSynthetixAndAnyRateIsStale(address account, uint balance) external view returns (uint transferable, bool anyRateIsStale); // Restricted: used internally to Synthetix function issueSynths(address from, uint amount) external; function issueSynthsOnBehalf( address issueFor, address from, uint amount ) external; function issueMaxSynths(address from) external; function issueMaxSynthsOnBehalf(address issueFor, address from) external; function burnSynths(address from, uint amount) external; function burnSynthsOnBehalf( address burnForAddress, address from, uint amount ) external; function burnSynthsToTarget(address from) external; function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external; function liquidateDelinquentAccount(address account, uint susdAmount, address liquidator) external returns (uint totalRedeemed, uint amountToLiquidate); } // Inheritance // https://docs.synthetix.io/contracts/AddressResolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== MUTATIVE FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { repository[names[i]] = destinations[i]; } } /* ========== VIEWS ========== */ function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getSynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.synths(key)); } } // Inheritance // Internal references // https://docs.synthetix.io/contracts/MixinResolver contract MixinResolver is Owned { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; bytes32[] public resolverAddressesRequired; uint public constant MAX_ADDRESSES_FROM_RESOLVER = 24; constructor(address _resolver, bytes32[MAX_ADDRESSES_FROM_RESOLVER] memory _addressesToCache) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); for (uint i = 0; i < _addressesToCache.length; i++) { if (_addressesToCache[i] != bytes32(0)) { resolverAddressesRequired.push(_addressesToCache[i]); } else { // End early once an empty item is found - assumes there are no empty slots in // _addressesToCache break; } } resolver = AddressResolver(_resolver); // Do not sync the cache as addresses may not be in the resolver yet } /* ========== SETTERS ========== */ function setResolverAndSyncCache(AddressResolver _resolver) external onlyOwner { resolver = _resolver; for (uint i = 0; i < resolverAddressesRequired.length; i++) { bytes32 name = resolverAddressesRequired[i]; // Note: can only be invoked once the resolver has all the targets needed added addressCache[name] = resolver.requireAndGetAddress(name, "Resolver missing target"); } } /* ========== VIEWS ========== */ function requireAndGetAddress(bytes32 name, string memory reason) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), reason); return _foundAddress; } // Note: this could be made external in a utility contract if addressCache was made public // (used for deployment) function isResolverCached(AddressResolver _resolver) external view returns (bool) { if (resolver != _resolver) { return false; } // otherwise, check everything for (uint i = 0; i < resolverAddressesRequired.length; i++) { bytes32 name = resolverAddressesRequired[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } // Note: can be made external into a utility contract (used for deployment) function getResolverAddressesRequired() external view returns (bytes32[MAX_ADDRESSES_FROM_RESOLVER] memory addressesRequired) { for (uint i = 0; i < resolverAddressesRequired.length; i++) { addressesRequired[i] = resolverAddressesRequired[i]; } } /* ========== INTERNAL FUNCTIONS ========== */ function appendToAddressCache(bytes32 name) internal { resolverAddressesRequired.push(name); require(resolverAddressesRequired.length < MAX_ADDRESSES_FROM_RESOLVER, "Max resolver cache size met"); // Because this is designed to be called internally in constructors, we don't // check the address exists already in the resolver addressCache[name] = resolver.getAddress(name); } } interface IBinaryOptionMarketManager { /* ========== VIEWS / VARIABLES ========== */ function fees() external view returns (uint poolFee, uint creatorFee, uint refundFee); function durations() external view returns (uint maxOraclePriceAge, uint expiryDuration, uint maxTimeToMaturity); function creatorLimits() external view returns (uint capitalRequirement, uint skewLimit); function marketCreationEnabled() external view returns (bool); function totalDeposited() external view returns (uint); function numActiveMarkets() external view returns (uint); function activeMarkets(uint index, uint pageSize) external view returns (address[] memory); function numMaturedMarkets() external view returns (uint); function maturedMarkets(uint index, uint pageSize) external view returns (address[] memory); /* ========== MUTATIVE FUNCTIONS ========== */ function createMarket( bytes32 oracleKey, uint strikePrice, bool refundsEnabled, uint[2] calldata times, // [biddingEnd, maturity] uint[2] calldata bids // [longBid, shortBid] ) external returns (IBinaryOptionMarket); function resolveMarket(address market) external; function cancelMarket(address market) external; function expireMarkets(address[] calldata market) external; } interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IBinaryOption { /* ========== VIEWS / VARIABLES ========== */ function market() external view returns (IBinaryOptionMarket); function bidOf(address account) external view returns (uint); function totalBids() external view returns (uint); function balanceOf(address account) external view returns (uint); function totalSupply() external view returns (uint); function claimableBalanceOf(address account) external view returns (uint); function totalClaimableSupply() external view returns (uint); } interface IBinaryOptionMarket { /* ========== TYPES ========== */ enum Phase { Bidding, Trading, Maturity, Expiry } enum Side { Long, Short } /* ========== VIEWS / VARIABLES ========== */ function options() external view returns (IBinaryOption long, IBinaryOption short); function prices() external view returns (uint long, uint short); function times() external view returns (uint biddingEnd, uint maturity, uint destructino); function oracleDetails() external view returns (bytes32 key, uint strikePrice, uint finalPrice); function fees() external view returns (uint poolFee, uint creatorFee, uint refundFee); function creatorLimits() external view returns (uint capitalRequirement, uint skewLimit); function deposited() external view returns (uint); function creator() external view returns (address); function resolved() external view returns (bool); function refundsEnabled() external view returns (bool); function phase() external view returns (Phase); function oraclePriceAndTimestamp() external view returns (uint price, uint updatedAt); function canResolve() external view returns (bool); function result() external view returns (Side); function pricesAfterBidOrRefund(Side side, uint value, bool refund) external view returns (uint long, uint short); function bidOrRefundForPrice(Side bidSide, Side priceSide, uint price, bool refund) external view returns (uint); function bidsOf(address account) external view returns (uint long, uint short); function totalBids() external view returns (uint long, uint short); function claimableBalancesOf(address account) external view returns (uint long, uint short); function totalClaimableSupplies() external view returns (uint long, uint short); function balancesOf(address account) external view returns (uint long, uint short); function totalSupplies() external view returns (uint long, uint short); function exercisableDeposits() external view returns (uint); /* ========== MUTATIVE FUNCTIONS ========== */ function bid(Side side, uint value) external; function refund(Side side, uint value) external returns (uint refundMinusFee); function claimOptions() external returns (uint longClaimed, uint shortClaimed); function exerciseOptions() external returns (uint); } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Libraries // https://docs.synthetix.io/contracts/SafeDecimalMath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } // Inheritance // https://docs.synthetix.io/contracts/Pausable contract Pausable is Owned { uint public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } } // Inheritance // https://docs.synthetix.io/contracts/SelfDestructible contract SelfDestructible is Owned { uint public constant SELFDESTRUCT_DELAY = 4 weeks; uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); selfDestructBeneficiary = owner; emit SelfDestructBeneficiaryUpdated(owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address payable _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be zero"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self Destruct not yet initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay not met"); emit SelfDestructed(selfDestructBeneficiary); selfdestruct(address(uint160(selfDestructBeneficiary))); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } library AddressListLib { struct AddressList { address[] elements; mapping(address => uint) indices; } function contains(AddressList storage list, address candidate) internal view returns (bool) { if (list.elements.length == 0) { return false; } uint index = list.indices[candidate]; return index != 0 || list.elements[0] == candidate; } function getPage( AddressList storage list, uint index, uint pageSize ) internal view returns (address[] memory) { // NOTE: This implementation should be converted to slice operators if the compiler is updated to v0.6.0+ uint endIndex = index + pageSize; // The check below that endIndex <= index handles overflow. // If the page extends past the end of the list, truncate it. if (endIndex > list.elements.length) { endIndex = list.elements.length; } if (endIndex <= index) { return new address[](0); } uint n = endIndex - index; // We already checked for negative overflow. address[] memory page = new address[](n); for (uint i; i < n; i++) { page[i] = list.elements[i + index]; } return page; } function push(AddressList storage list, address element) internal { list.indices[element] = list.elements.length; list.elements.push(element); } function remove(AddressList storage list, address element) internal { require(contains(list, element), "Element not in list."); // Replace the removed element with the last element of the list. uint index = list.indices[element]; uint lastIndex = list.elements.length - 1; // We required that element is in the list, so it is not empty. if (index != lastIndex) { // No need to shift the last element if it is the one we want to delete. address shiftedElement = list.elements[lastIndex]; list.elements[index] = shiftedElement; list.indices[shiftedElement] = index; } list.elements.pop(); delete list.indices[element]; } } // Inheritance // Internal references contract BinaryOptionMarketFactory is Owned, SelfDestructible, MixinResolver { /* ========== STATE VARIABLES ========== */ /* ---------- Address Resolver Configuration ---------- */ bytes32 internal constant CONTRACT_BINARYOPTIONMARKETMANAGER = "BinaryOptionMarketManager"; bytes32[24] internal addressesToCache = [CONTRACT_BINARYOPTIONMARKETMANAGER]; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, address _resolver) public Owned(_owner) SelfDestructible() MixinResolver(_resolver, addressesToCache) {} /* ========== VIEWS ========== */ /* ---------- Related Contracts ---------- */ function _manager() internal view returns (address) { return requireAndGetAddress(CONTRACT_BINARYOPTIONMARKETMANAGER, "Missing BinaryOptionMarketManager address"); } /* ========== MUTATIVE FUNCTIONS ========== */ function createMarket( address creator, uint[2] calldata creatorLimits, bytes32 oracleKey, uint strikePrice, bool refundsEnabled, uint[3] calldata times, // [biddingEnd, maturity, expiry] uint[2] calldata bids, // [longBid, shortBid] uint[3] calldata fees // [poolFee, creatorFee, refundFee] ) external returns (BinaryOptionMarket) { address manager = _manager(); require(address(manager) == msg.sender, "Only permitted by the manager."); return new BinaryOptionMarket(manager, creator, creatorLimits, oracleKey, strikePrice, refundsEnabled, times, bids, fees); } } // https://docs.synthetix.io/contracts/source/interfaces/IExchangeRates interface IExchangeRates { // Views function aggregators(bytes32 currencyKey) external view returns (address); function anyRateIsStale(bytes32[] calldata currencyKeys) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozen ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndStaleForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory, bool); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); } interface ISystemStatus { // Views function requireSystemActive() external view; function requireIssuanceActive() external view; function requireExchangeActive() external view; function requireSynthActive(bytes32 currencyKey) external view; function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; } // Inheritance // Libraries // Internal references contract BinaryOptionMarketManager is Owned, Pausable, SelfDestructible, MixinResolver, IBinaryOptionMarketManager { /* ========== LIBRARIES ========== */ using SafeMath for uint; using AddressListLib for AddressListLib.AddressList; /* ========== TYPES ========== */ struct Fees { uint poolFee; uint creatorFee; uint refundFee; } struct Durations { uint maxOraclePriceAge; uint expiryDuration; uint maxTimeToMaturity; } struct CreatorLimits { uint capitalRequirement; uint skewLimit; } /* ========== STATE VARIABLES ========== */ Fees public fees; Durations public durations; CreatorLimits public creatorLimits; bool public marketCreationEnabled = true; uint public totalDeposited; AddressListLib.AddressList internal _activeMarkets; AddressListLib.AddressList internal _maturedMarkets; BinaryOptionMarketManager internal _migratingManager; /* ---------- Address Resolver Configuration ---------- */ bytes32 internal constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 internal constant CONTRACT_SYNTHSUSD = "SynthsUSD"; bytes32 internal constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 internal constant CONTRACT_BINARYOPTIONMARKETFACTORY = "BinaryOptionMarketFactory"; bytes32[24] internal addressesToCache = [ CONTRACT_SYSTEMSTATUS, CONTRACT_SYNTHSUSD, CONTRACT_EXRATES, CONTRACT_BINARYOPTIONMARKETFACTORY ]; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _resolver, uint _maxOraclePriceAge, uint _expiryDuration, uint _maxTimeToMaturity, uint _creatorCapitalRequirement, uint _creatorSkewLimit, uint _poolFee, uint _creatorFee, uint _refundFee ) public Owned(_owner) Pausable() SelfDestructible() MixinResolver(_resolver, addressesToCache) { // Temporarily change the owner so that the setters don't revert. owner = msg.sender; setExpiryDuration(_expiryDuration); setMaxOraclePriceAge(_maxOraclePriceAge); setMaxTimeToMaturity(_maxTimeToMaturity); setCreatorCapitalRequirement(_creatorCapitalRequirement); setCreatorSkewLimit(_creatorSkewLimit); setPoolFee(_poolFee); setCreatorFee(_creatorFee); setRefundFee(_refundFee); owner = _owner; } /* ========== VIEWS ========== */ /* ---------- Related Contracts ---------- */ function _systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS, "Missing SystemStatus address")); } function _sUSD() internal view returns (IERC20) { return IERC20(requireAndGetAddress(CONTRACT_SYNTHSUSD, "Missing SynthsUSD address")); } function _exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES, "Missing ExchangeRates")); } function _factory() internal view returns (BinaryOptionMarketFactory) { return BinaryOptionMarketFactory( requireAndGetAddress(CONTRACT_BINARYOPTIONMARKETFACTORY, "Missing BinaryOptionMarketFactory address") ); } /* ---------- Market Information ---------- */ function _isKnownMarket(address candidate) internal view returns (bool) { return _activeMarkets.contains(candidate) || _maturedMarkets.contains(candidate); } function numActiveMarkets() external view returns (uint) { return _activeMarkets.elements.length; } function activeMarkets(uint index, uint pageSize) external view returns (address[] memory) { return _activeMarkets.getPage(index, pageSize); } function numMaturedMarkets() external view returns (uint) { return _maturedMarkets.elements.length; } function maturedMarkets(uint index, uint pageSize) external view returns (address[] memory) { return _maturedMarkets.getPage(index, pageSize); } function _isValidKey(bytes32 oracleKey) internal view returns (bool) { IExchangeRates exchangeRates = _exchangeRates(); // If it has a rate, then it's possibly a valid key if (exchangeRates.rateForCurrency(oracleKey) != 0) { // But not sUSD if (oracleKey == "sUSD") { return false; } // and not inverse rates (uint entryPoint, , , ) = exchangeRates.inversePricing(oracleKey); if (entryPoint != 0) { return false; } return true; } return false; } /* ========== MUTATIVE FUNCTIONS ========== */ /* ---------- Setters ---------- */ function setMaxOraclePriceAge(uint _maxOraclePriceAge) public onlyOwner { durations.maxOraclePriceAge = _maxOraclePriceAge; emit MaxOraclePriceAgeUpdated(_maxOraclePriceAge); } function setExpiryDuration(uint _expiryDuration) public onlyOwner { durations.expiryDuration = _expiryDuration; emit ExpiryDurationUpdated(_expiryDuration); } function setMaxTimeToMaturity(uint _maxTimeToMaturity) public onlyOwner { durations.maxTimeToMaturity = _maxTimeToMaturity; emit MaxTimeToMaturityUpdated(_maxTimeToMaturity); } function setPoolFee(uint _poolFee) public onlyOwner { uint totalFee = _poolFee + fees.creatorFee; require(totalFee < SafeDecimalMath.unit(), "Total fee must be less than 100%."); require(0 < totalFee, "Total fee must be nonzero."); fees.poolFee = _poolFee; emit PoolFeeUpdated(_poolFee); } function setCreatorFee(uint _creatorFee) public onlyOwner { uint totalFee = _creatorFee + fees.poolFee; require(totalFee < SafeDecimalMath.unit(), "Total fee must be less than 100%."); require(0 < totalFee, "Total fee must be nonzero."); fees.creatorFee = _creatorFee; emit CreatorFeeUpdated(_creatorFee); } function setRefundFee(uint _refundFee) public onlyOwner { require(_refundFee <= SafeDecimalMath.unit(), "Refund fee must be no greater than 100%."); fees.refundFee = _refundFee; emit RefundFeeUpdated(_refundFee); } function setCreatorCapitalRequirement(uint _creatorCapitalRequirement) public onlyOwner { creatorLimits.capitalRequirement = _creatorCapitalRequirement; emit CreatorCapitalRequirementUpdated(_creatorCapitalRequirement); } function setCreatorSkewLimit(uint _creatorSkewLimit) public onlyOwner { require(_creatorSkewLimit <= SafeDecimalMath.unit(), "Creator skew limit must be no greater than 1."); creatorLimits.skewLimit = _creatorSkewLimit; emit CreatorSkewLimitUpdated(_creatorSkewLimit); } /* ---------- Deposit Management ---------- */ function incrementTotalDeposited(uint delta) external onlyActiveMarkets notPaused { _systemStatus().requireSystemActive(); totalDeposited = totalDeposited.add(delta); } function decrementTotalDeposited(uint delta) external onlyKnownMarkets notPaused { _systemStatus().requireSystemActive(); // NOTE: As individual market debt is not tracked here, the underlying markets // need to be careful never to subtract more debt than they added. // This can't be enforced without additional state/communication overhead. totalDeposited = totalDeposited.sub(delta); } /* ---------- Market Lifecycle ---------- */ function createMarket( bytes32 oracleKey, uint strikePrice, bool refundsEnabled, uint[2] calldata times, // [biddingEnd, maturity] uint[2] calldata bids // [longBid, shortBid] ) external notPaused returns ( IBinaryOptionMarket // no support for returning BinaryOptionMarket polymorphically given the interface ) { _systemStatus().requireSystemActive(); require(marketCreationEnabled, "Market creation is disabled"); require(_isValidKey(oracleKey), "Invalid key"); (uint biddingEnd, uint maturity) = (times[0], times[1]); require(maturity <= now + durations.maxTimeToMaturity, "Maturity too far in the future"); uint expiry = maturity.add(durations.expiryDuration); uint initialDeposit = bids[0].add(bids[1]); require(now < biddingEnd, "End of bidding has passed"); require(biddingEnd < maturity, "Maturity predates end of bidding"); // We also require maturity < expiry. But there is no need to check this. // Fees being in range are checked in the setters. // The market itself validates the capital and skew requirements. BinaryOptionMarket market = _factory().createMarket( msg.sender, [creatorLimits.capitalRequirement, creatorLimits.skewLimit], oracleKey, strikePrice, refundsEnabled, [biddingEnd, maturity, expiry], bids, [fees.poolFee, fees.creatorFee, fees.refundFee] ); market.setResolverAndSyncCache(resolver); _activeMarkets.push(address(market)); // The debt can't be incremented in the new market's constructor because until construction is complete, // the manager doesn't know its address in order to grant it permission. totalDeposited = totalDeposited.add(initialDeposit); _sUSD().transferFrom(msg.sender, address(market), initialDeposit); emit MarketCreated(address(market), msg.sender, oracleKey, strikePrice, biddingEnd, maturity, expiry); return market; } function resolveMarket(address market) external { require(_activeMarkets.contains(market), "Not an active market"); BinaryOptionMarket(market).resolve(); _activeMarkets.remove(market); _maturedMarkets.push(market); } function cancelMarket(address market) external notPaused { require(_activeMarkets.contains(market), "Not an active market"); address creator = BinaryOptionMarket(market).creator(); require(msg.sender == creator, "Sender not market creator"); BinaryOptionMarket(market).cancel(msg.sender); _activeMarkets.remove(market); emit MarketCancelled(market); } function expireMarkets(address[] calldata markets) external notPaused { for (uint i = 0; i < markets.length; i++) { address market = markets[i]; // The market itself handles decrementing the total deposits. BinaryOptionMarket(market).expire(msg.sender); // Note that we required that the market is known, which guarantees // its index is defined and that the list of markets is not empty. _maturedMarkets.remove(market); emit MarketExpired(market); } } /* ---------- Upgrade and Administration ---------- */ function setResolverAndSyncCacheOnMarkets(AddressResolver _resolver, BinaryOptionMarket[] calldata marketsToSync) external onlyOwner { for (uint i = 0; i < marketsToSync.length; i++) { marketsToSync[i].setResolverAndSyncCache(_resolver); } } function setMarketCreationEnabled(bool enabled) public onlyOwner { if (enabled != marketCreationEnabled) { marketCreationEnabled = enabled; emit MarketCreationEnabledUpdated(enabled); } } function setMigratingManager(BinaryOptionMarketManager manager) public onlyOwner { _migratingManager = manager; } function migrateMarkets( BinaryOptionMarketManager receivingManager, bool active, BinaryOptionMarket[] calldata marketsToMigrate ) external onlyOwner { uint _numMarkets = marketsToMigrate.length; if (_numMarkets == 0) { return; } AddressListLib.AddressList storage markets = active ? _activeMarkets : _maturedMarkets; uint runningDepositTotal; for (uint i; i < _numMarkets; i++) { BinaryOptionMarket market = marketsToMigrate[i]; require(_isKnownMarket(address(market)), "Market unknown."); // Remove it from our list and deposit total. markets.remove(address(market)); runningDepositTotal = runningDepositTotal.add(market.deposited()); // Prepare to transfer ownership to the new manager. market.nominateNewOwner(address(receivingManager)); } // Deduct the total deposits of the migrated markets. totalDeposited = totalDeposited.sub(runningDepositTotal); emit MarketsMigrated(receivingManager, marketsToMigrate); // Now actually transfer the markets over to the new manager. receivingManager.receiveMarkets(active, marketsToMigrate); } function receiveMarkets(bool active, BinaryOptionMarket[] calldata marketsToReceive) external { require(msg.sender == address(_migratingManager), "Only permitted for migrating manager."); uint _numMarkets = marketsToReceive.length; if (_numMarkets == 0) { return; } AddressListLib.AddressList storage markets = active ? _activeMarkets : _maturedMarkets; uint runningDepositTotal; for (uint i; i < _numMarkets; i++) { BinaryOptionMarket market = marketsToReceive[i]; require(!_isKnownMarket(address(market)), "Market already known."); market.acceptOwnership(); markets.push(address(market)); // Update the market with the new manager address, runningDepositTotal = runningDepositTotal.add(market.deposited()); } totalDeposited = totalDeposited.add(runningDepositTotal); emit MarketsReceived(_migratingManager, marketsToReceive); } /* ========== MODIFIERS ========== */ modifier onlyActiveMarkets() { require(_activeMarkets.contains(msg.sender), "Permitted only for active markets."); _; } modifier onlyKnownMarkets() { require(_isKnownMarket(msg.sender), "Permitted only for known markets."); _; } /* ========== EVENTS ========== */ event MarketCreated( address market, address indexed creator, bytes32 indexed oracleKey, uint strikePrice, uint biddingEndDate, uint maturityDate, uint expiryDate ); event MarketExpired(address market); event MarketCancelled(address market); event MarketsMigrated(BinaryOptionMarketManager receivingManager, BinaryOptionMarket[] markets); event MarketsReceived(BinaryOptionMarketManager migratingManager, BinaryOptionMarket[] markets); event MarketCreationEnabledUpdated(bool enabled); event MaxOraclePriceAgeUpdated(uint duration); event ExerciseDurationUpdated(uint duration); event ExpiryDurationUpdated(uint duration); event MaxTimeToMaturityUpdated(uint duration); event CreatorCapitalRequirementUpdated(uint value); event CreatorSkewLimitUpdated(uint value); event PoolFeeUpdated(uint fee); event CreatorFeeUpdated(uint fee); event RefundFeeUpdated(uint fee); } // Inheritance // Libraries // Internal references contract BinaryOption is IERC20, IBinaryOption { /* ========== LIBRARIES ========== */ using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ string public constant name = "SNX Binary Option"; string public constant symbol = "sOPT"; uint8 public constant decimals = 18; BinaryOptionMarket public market; mapping(address => uint) public bidOf; uint public totalBids; mapping(address => uint) public balanceOf; uint public totalSupply; // The argument order is allowance[owner][spender] mapping(address => mapping(address => uint)) public allowance; // Enforce a 1 cent minimum bid balance uint internal constant _MINIMUM_BID = 1e16; /* ========== CONSTRUCTOR ========== */ constructor(address initialBidder, uint initialBid) public { market = BinaryOptionMarket(msg.sender); bidOf[initialBidder] = initialBid; totalBids = initialBid; } /* ========== VIEWS ========== */ function _claimableBalanceOf( uint _bid, uint price, uint exercisableDeposits ) internal view returns (uint) { uint owed = _bid.divideDecimal(price); uint supply = _totalClaimableSupply(exercisableDeposits); /* The last claimant might be owed slightly more or less than the actual remaining deposit based on rounding errors with the price. Therefore if the user's bid is the entire rest of the pot, just give them everything that's left. If there is no supply, then this option lost, and we'll return 0. */ if ((_bid == totalBids && _bid != 0) || supply == 0) { return supply; } /* Note that option supply on the losing side and deposits can become decoupled, but losing options are not claimable, therefore we only need to worry about the situation where supply < owed on the winning side. If somehow a user who is not the last bidder is owed more than what's available, subsequent bidders will be disadvantaged. Given that the minimum bid is 10^16 wei, this should never occur in reality. */ require(owed <= supply, "supply < claimable"); return owed; } function claimableBalanceOf(address account) external view returns (uint) { (uint price, uint exercisableDeposits) = market.senderPriceAndExercisableDeposits(); return _claimableBalanceOf(bidOf[account], price, exercisableDeposits); } function _totalClaimableSupply(uint exercisableDeposits) internal view returns (uint) { uint _totalSupply = totalSupply; // We'll avoid throwing an exception here to avoid breaking any dapps, but this case // should never occur given the minimum bid size. if (exercisableDeposits <= _totalSupply) { return 0; } return exercisableDeposits.sub(_totalSupply); } function totalClaimableSupply() external view returns (uint) { (, uint exercisableDeposits) = market.senderPriceAndExercisableDeposits(); return _totalClaimableSupply(exercisableDeposits); } /* ========== MUTATIVE FUNCTIONS ========== */ function _requireMinimumBid(uint bid) internal pure returns (uint) { require(bid >= _MINIMUM_BID || bid == 0, "Balance < $0.01"); return bid; } // This must only be invoked during bidding. function bid(address bidder, uint newBid) external onlyMarket { bidOf[bidder] = _requireMinimumBid(bidOf[bidder].add(newBid)); totalBids = totalBids.add(newBid); } // This must only be invoked during bidding. function refund(address bidder, uint newRefund) external onlyMarket { // The safe subtraction will catch refunds that are too large. bidOf[bidder] = _requireMinimumBid(bidOf[bidder].sub(newRefund)); totalBids = totalBids.sub(newRefund); } // This must only be invoked after bidding. function claim( address claimant, uint price, uint depositsRemaining ) external onlyMarket returns (uint optionsClaimed) { uint _bid = bidOf[claimant]; uint claimable = _claimableBalanceOf(_bid, price, depositsRemaining); // No options to claim? Nothing happens. if (claimable == 0) { return 0; } totalBids = totalBids.sub(_bid); bidOf[claimant] = 0; totalSupply = totalSupply.add(claimable); balanceOf[claimant] = balanceOf[claimant].add(claimable); // Increment rather than assigning since a transfer may have occurred. emit Transfer(address(0), claimant, claimable); emit Issued(claimant, claimable); return claimable; } // This must only be invoked after maturity. function exercise(address claimant) external onlyMarket { uint balance = balanceOf[claimant]; if (balance == 0) { return; } balanceOf[claimant] = 0; totalSupply = totalSupply.sub(balance); emit Transfer(claimant, address(0), balance); emit Burned(claimant, balance); } // This must only be invoked after the exercise window is complete. // Note that any options which have not been exercised will linger. function expire(address payable beneficiary) external onlyMarket { selfdestruct(beneficiary); } /* ---------- ERC20 Functions ---------- */ // This should only operate after bidding; // Since options can't be claimed until after bidding, all balances are zero until that time. // So we don't need to explicitly check the timestamp to prevent transfers. function _transfer( address _from, address _to, uint _value ) internal returns (bool success) { market.requireActiveAndUnpaused(); require(_to != address(0) && _to != address(this), "Invalid address"); uint fromBalance = balanceOf[_from]; require(_value <= fromBalance, "Insufficient balance"); balanceOf[_from] = fromBalance.sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function transfer(address _to, uint _value) external returns (bool success) { return _transfer(msg.sender, _to, _value); } function transferFrom( address _from, address _to, uint _value ) external returns (bool success) { uint fromAllowance = allowance[_from][msg.sender]; require(_value <= fromAllowance, "Insufficient allowance"); allowance[_from][msg.sender] = fromAllowance.sub(_value); return _transfer(_from, _to, _value); } function approve(address _spender, uint _value) external returns (bool success) { require(_spender != address(0)); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /* ========== MODIFIERS ========== */ modifier onlyMarket() { require(msg.sender == address(market), "Only market allowed"); _; } /* ========== EVENTS ========== */ event Issued(address indexed account, uint value); event Burned(address indexed account, uint value); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IFeePool { // Views function getExchangeFeeRateForSynth(bytes32 synthKey) external view returns (uint); // solhint-disable-next-line func-name-mixedcase function FEE_ADDRESS() external view returns (address); function feesAvailable(address account) external view returns (uint, uint); function isFeesClaimable(address account) external view returns (bool); function totalFeesAvailable() external view returns (uint); function totalRewardsAvailable() external view returns (uint); // Mutative Functions function claimFees() external returns (bool); function claimOnBehalf(address claimingForAddress) external returns (bool); function closeCurrentFeePeriod() external; // Restricted: used internally to Synthetix function appendAccountIssuanceRecord( address account, uint lockedAmount, uint debtEntryIndex ) external; function recordFeePaid(uint sUSDAmount) external; function setRewardsToDistribute(uint amount) external; } // Inheritance // Libraries // Internal references contract BinaryOptionMarket is Owned, MixinResolver, IBinaryOptionMarket { /* ========== LIBRARIES ========== */ using SafeMath for uint; using SafeDecimalMath for uint; /* ========== TYPES ========== */ struct Options { BinaryOption long; BinaryOption short; } struct Prices { uint long; uint short; } struct Times { uint biddingEnd; uint maturity; uint expiry; } struct OracleDetails { bytes32 key; uint strikePrice; uint finalPrice; } /* ========== STATE VARIABLES ========== */ Options public options; Prices public prices; Times public times; OracleDetails public oracleDetails; BinaryOptionMarketManager.Fees public fees; BinaryOptionMarketManager.CreatorLimits public creatorLimits; // `deposited` tracks the sum of open bids on short and long, plus withheld refund fees. // This must explicitly be kept, in case tokens are transferred to the contract directly. uint public deposited; address public creator; bool public resolved; bool public refundsEnabled; uint internal _feeMultiplier; /* ---------- Address Resolver Configuration ---------- */ bytes32 internal constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 internal constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 internal constant CONTRACT_SYNTHSUSD = "SynthsUSD"; bytes32 internal constant CONTRACT_FEEPOOL = "FeePool"; bytes32[24] internal addressesToCache = [CONTRACT_SYSTEMSTATUS, CONTRACT_EXRATES, CONTRACT_SYNTHSUSD, CONTRACT_FEEPOOL]; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _creator, uint[2] memory _creatorLimits, // [capitalRequirement, skewLimit] bytes32 _oracleKey, uint _strikePrice, bool _refundsEnabled, uint[3] memory _times, // [biddingEnd, maturity, expiry] uint[2] memory _bids, // [longBid, shortBid] uint[3] memory _fees // [poolFee, creatorFee, refundFee] ) public Owned(_owner) MixinResolver(_owner, addressesToCache) // The resolver is initially set to the owner, but it will be set correctly when the cache is synchronised { creator = _creator; creatorLimits = BinaryOptionMarketManager.CreatorLimits(_creatorLimits[0], _creatorLimits[1]); oracleDetails = OracleDetails(_oracleKey, _strikePrice, 0); times = Times(_times[0], _times[1], _times[2]); refundsEnabled = _refundsEnabled; (uint longBid, uint shortBid) = (_bids[0], _bids[1]); _checkCreatorLimits(longBid, shortBid); emit Bid(Side.Long, _creator, longBid); emit Bid(Side.Short, _creator, shortBid); // Note that the initial deposit of synths must be made by the manager, otherwise the contract's assumed // deposits will fall out of sync with its actual balance. Similarly the total system deposits must be updated in the manager. // A balance check isn't performed here since the manager doesn't know the address of the new contract until after it is created. uint initialDeposit = longBid.add(shortBid); deposited = initialDeposit; (uint poolFee, uint creatorFee) = (_fees[0], _fees[1]); fees = BinaryOptionMarketManager.Fees(poolFee, creatorFee, _fees[2]); _feeMultiplier = SafeDecimalMath.unit().sub(poolFee.add(creatorFee)); // Compute the prices now that the fees and deposits have been set. _updatePrices(longBid, shortBid, initialDeposit); // Instantiate the options themselves options.long = new BinaryOption(_creator, longBid); options.short = new BinaryOption(_creator, shortBid); } /* ========== VIEWS ========== */ /* ---------- External Contracts ---------- */ function _systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS, "Missing SystemStatus")); } function _exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES, "Missing ExchangeRates")); } function _sUSD() internal view returns (IERC20) { return IERC20(requireAndGetAddress(CONTRACT_SYNTHSUSD, "Missing SynthsUSD")); } function _feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL, "Missing FeePool")); } function _manager() internal view returns (BinaryOptionMarketManager) { return BinaryOptionMarketManager(owner); } /* ---------- Phases ---------- */ function _biddingEnded() internal view returns (bool) { return times.biddingEnd < now; } function _matured() internal view returns (bool) { return times.maturity < now; } function _expired() internal view returns (bool) { return resolved && (times.expiry < now || deposited == 0); } function phase() external view returns (Phase) { if (!_biddingEnded()) { return Phase.Bidding; } if (!_matured()) { return Phase.Trading; } if (!_expired()) { return Phase.Maturity; } return Phase.Expiry; } /* ---------- Market Resolution ---------- */ function _oraclePriceAndTimestamp() internal view returns (uint price, uint updatedAt) { return _exchangeRates().rateAndUpdatedTime(oracleDetails.key); } function oraclePriceAndTimestamp() external view returns (uint price, uint updatedAt) { return _oraclePriceAndTimestamp(); } function _isFreshPriceUpdateTime(uint timestamp) internal view returns (bool) { (uint maxOraclePriceAge, , ) = _manager().durations(); return (times.maturity.sub(maxOraclePriceAge)) <= timestamp; } function canResolve() external view returns (bool) { (, uint updatedAt) = _oraclePriceAndTimestamp(); return !resolved && _matured() && _isFreshPriceUpdateTime(updatedAt); } function _result() internal view returns (Side) { uint price; if (resolved) { price = oracleDetails.finalPrice; } else { (price, ) = _oraclePriceAndTimestamp(); } return oracleDetails.strikePrice <= price ? Side.Long : Side.Short; } function result() external view returns (Side) { return _result(); } /* ---------- Option Prices ---------- */ function _computePrices( uint longBids, uint shortBids, uint _deposited ) internal view returns (uint long, uint short) { require(longBids != 0 && shortBids != 0, "Bids must be nonzero"); uint optionsPerSide = _exercisableDeposits(_deposited); // The math library rounds up on an exact half-increment -- the price on one side may be an increment too high, // but this only implies a tiny extra quantity will go to fees. return (longBids.divideDecimalRound(optionsPerSide), shortBids.divideDecimalRound(optionsPerSide)); } function senderPriceAndExercisableDeposits() external view returns (uint price, uint exercisable) { // When the market is not yet resolved, both sides might be able to exercise all the options. // On the other hand, if the market has resolved, then only the winning side may exercise. exercisable = 0; if (!resolved || address(_option(_result())) == msg.sender) { exercisable = _exercisableDeposits(deposited); } // Send the correct price for each side of the market. if (msg.sender == address(options.long)) { price = prices.long; } else if (msg.sender == address(options.short)) { price = prices.short; } else { revert("Sender is not an option"); } } function pricesAfterBidOrRefund( Side side, uint value, bool refund ) external view returns (uint long, uint short) { (uint longTotalBids, uint shortTotalBids) = _totalBids(); // prettier-ignore function(uint, uint) pure returns (uint) operation = refund ? SafeMath.sub : SafeMath.add; assembly { mstore(operation, add(mload(operation), callvalue)) } //inject SPECIFY FUNC VAR AS ANY TYPE if (side == Side.Long) { longTotalBids = operation(longTotalBids, value); } else { shortTotalBids = operation(shortTotalBids, value); } if (refund) { value = value.multiplyDecimalRound(SafeDecimalMath.unit().sub(fees.refundFee)); } return _computePrices(longTotalBids, shortTotalBids, operation(deposited, value)); } // Returns zero if the result would be negative. See the docs for the formulae this implements. function bidOrRefundForPrice( Side bidSide, Side priceSide, uint price, bool refund ) external view returns (uint) { uint adjustedPrice = price.multiplyDecimalRound(_feeMultiplier); uint bids = _option(priceSide).totalBids(); uint _deposited = deposited; uint unit = SafeDecimalMath.unit(); uint refundFeeMultiplier = unit.sub(fees.refundFee); if (bidSide == priceSide) { uint depositedByPrice = _deposited.multiplyDecimalRound(adjustedPrice); // For refunds, the numerator is the negative of the bid case and, // in the denominator the adjusted price has an extra factor of (1 - the refundFee). if (refund) { (depositedByPrice, bids) = (bids, depositedByPrice); adjustedPrice = adjustedPrice.multiplyDecimalRound(refundFeeMultiplier); } // The adjusted price is guaranteed to be less than 1: all its factors are also less than 1. return _subToZero(depositedByPrice, bids).divideDecimalRound(unit.sub(adjustedPrice)); } else { uint bidsPerPrice = bids.divideDecimalRound(adjustedPrice); // For refunds, the numerator is the negative of the bid case. if (refund) { (bidsPerPrice, _deposited) = (_deposited, bidsPerPrice); } uint value = _subToZero(bidsPerPrice, _deposited); return refund ? value.divideDecimalRound(refundFeeMultiplier) : value; } } /* ---------- Option Balances and Bids ---------- */ function _bidsOf(address account) internal view returns (uint long, uint short) { return (options.long.bidOf(account), options.short.bidOf(account)); } function bidsOf(address account) external view returns (uint long, uint short) { return _bidsOf(account); } function _totalBids() internal view returns (uint long, uint short) { return (options.long.totalBids(), options.short.totalBids()); } function totalBids() external view returns (uint long, uint short) { return _totalBids(); } function _claimableBalancesOf(address account) internal view returns (uint long, uint short) { return (options.long.claimableBalanceOf(account), options.short.claimableBalanceOf(account)); } function claimableBalancesOf(address account) external view returns (uint long, uint short) { return _claimableBalancesOf(account); } function totalClaimableSupplies() external view returns (uint long, uint short) { return (options.long.totalClaimableSupply(), options.short.totalClaimableSupply()); } function _balancesOf(address account) internal view returns (uint long, uint short) { return (options.long.balanceOf(account), options.short.balanceOf(account)); } function balancesOf(address account) external view returns (uint long, uint short) { return _balancesOf(account); } function totalSupplies() external view returns (uint long, uint short) { return (options.long.totalSupply(), options.short.totalSupply()); } function _exercisableDeposits(uint _deposited) internal view returns (uint) { // Fees are deducted at resolution, so remove them if we're still bidding or trading. return resolved ? _deposited : _deposited.multiplyDecimalRound(_feeMultiplier); } function exercisableDeposits() external view returns (uint) { return _exercisableDeposits(deposited); } /* ---------- Utilities ---------- */ function _chooseSide( Side side, uint longValue, uint shortValue ) internal pure returns (uint) { if (side == Side.Long) { return longValue; } return shortValue; } function _option(Side side) internal view returns (BinaryOption) { if (side == Side.Long) { return options.long; } return options.short; } // Returns zero if the result would be negative. function _subToZero(uint a, uint b) internal pure returns (uint) { return a < b ? 0 : a.sub(b); } function _checkCreatorLimits(uint longBid, uint shortBid) internal view { uint totalBid = longBid.add(shortBid); require(creatorLimits.capitalRequirement <= totalBid, "Insufficient capital"); uint skewLimit = creatorLimits.skewLimit; require( skewLimit <= longBid.divideDecimal(totalBid) && skewLimit <= shortBid.divideDecimal(totalBid), "Bids too skewed" ); } function _incrementDeposited(uint value) internal returns (uint _deposited) { _deposited = deposited.add(value); deposited = _deposited; _manager().incrementTotalDeposited(value); } function _decrementDeposited(uint value) internal returns (uint _deposited) { _deposited = deposited.sub(value); deposited = _deposited; _manager().decrementTotalDeposited(value); } function _requireManagerNotPaused() internal view { require(!_manager().paused(), "This action cannot be performed while the contract is paused"); } function requireActiveAndUnpaused() external view { _systemStatus().requireSystemActive(); _requireManagerNotPaused(); } /* ========== MUTATIVE FUNCTIONS ========== */ /* ---------- Bidding and Refunding ---------- */ function _updatePrices( uint longBids, uint shortBids, uint _deposited ) internal { (uint256 longPrice, uint256 shortPrice) = _computePrices(longBids, shortBids, _deposited); prices = Prices(longPrice, shortPrice); emit PricesUpdated(longPrice, shortPrice); } function bid(Side side, uint value) external duringBidding { if (value == 0) { return; } _option(side).bid(msg.sender, value); emit Bid(side, msg.sender, value); uint _deposited = _incrementDeposited(value); _sUSD().transferFrom(msg.sender, address(this), value); (uint longTotalBids, uint shortTotalBids) = _totalBids(); _updatePrices(longTotalBids, shortTotalBids, _deposited); } function refund(Side side, uint value) external duringBidding returns (uint refundMinusFee) { require(refundsEnabled, "Refunds disabled"); if (value == 0) { return 0; } // Require the market creator to leave sufficient capital in the market. if (msg.sender == creator) { (uint thisBid, uint thatBid) = _bidsOf(msg.sender); if (side == Side.Short) { (thisBid, thatBid) = (thatBid, thisBid); } _checkCreatorLimits(thisBid.sub(value), thatBid); } // Safe subtraction here and in related contracts will fail if either the // total supply, deposits, or wallet balance are too small to support the refund. refundMinusFee = value.multiplyDecimalRound(SafeDecimalMath.unit().sub(fees.refundFee)); _option(side).refund(msg.sender, value); emit Refund(side, msg.sender, refundMinusFee, value.sub(refundMinusFee)); uint _deposited = _decrementDeposited(refundMinusFee); _sUSD().transfer(msg.sender, refundMinusFee); (uint longTotalBids, uint shortTotalBids) = _totalBids(); _updatePrices(longTotalBids, shortTotalBids, _deposited); } /* ---------- Market Resolution ---------- */ function resolve() external onlyOwner afterMaturity systemActive managerNotPaused { require(!resolved, "Market already resolved"); // We don't need to perform stale price checks, so long as the price was // last updated recently enough before the maturity date. (uint price, uint updatedAt) = _oraclePriceAndTimestamp(); require(_isFreshPriceUpdateTime(updatedAt), "Price is stale"); oracleDetails.finalPrice = price; resolved = true; // Now remit any collected fees. // Since the constructor enforces that creatorFee + poolFee < 1, the balance // in the contract will be sufficient to cover these transfers. IERC20 sUSD = _sUSD(); uint _deposited = deposited; uint poolFees = _deposited.multiplyDecimalRound(fees.poolFee); uint creatorFees = _deposited.multiplyDecimalRound(fees.creatorFee); _decrementDeposited(creatorFees.add(poolFees)); sUSD.transfer(_feePool().FEE_ADDRESS(), poolFees); sUSD.transfer(creator, creatorFees); emit MarketResolved(_result(), price, updatedAt, deposited, poolFees, creatorFees); } /* ---------- Claiming and Exercising Options ---------- */ function _claimOptions() internal systemActive managerNotPaused afterBidding returns (uint longClaimed, uint shortClaimed) { uint exercisable = _exercisableDeposits(deposited); Side outcome = _result(); bool _resolved = resolved; // Only claim options if we aren't resolved, and only claim the winning side. uint longOptions; uint shortOptions; if (!_resolved || outcome == Side.Long) { longOptions = options.long.claim(msg.sender, prices.long, exercisable); } if (!_resolved || outcome == Side.Short) { shortOptions = options.short.claim(msg.sender, prices.short, exercisable); } require(longOptions != 0 || shortOptions != 0, "Nothing to claim"); emit OptionsClaimed(msg.sender, longOptions, shortOptions); return (longOptions, shortOptions); } function claimOptions() external returns (uint longClaimed, uint shortClaimed) { return _claimOptions(); } function exerciseOptions() external returns (uint) { // The market must be resolved if it has not been. if (!resolved) { _manager().resolveMarket(address(this)); } // If there are options to be claimed, claim them and proceed. (uint claimableLong, uint claimableShort) = _claimableBalancesOf(msg.sender); if (claimableLong != 0 || claimableShort != 0) { _claimOptions(); } // If the account holds no options, revert. (uint longBalance, uint shortBalance) = _balancesOf(msg.sender); require(longBalance != 0 || shortBalance != 0, "Nothing to exercise"); // Each option only needs to be exercised if the account holds any of it. if (longBalance != 0) { options.long.exercise(msg.sender); } if (shortBalance != 0) { options.short.exercise(msg.sender); } // Only pay out the side that won. uint payout = _chooseSide(_result(), longBalance, shortBalance); emit OptionsExercised(msg.sender, payout); if (payout != 0) { _decrementDeposited(payout); _sUSD().transfer(msg.sender, payout); } return payout; } /* ---------- Market Expiry ---------- */ function _selfDestruct(address payable beneficiary) internal { uint _deposited = deposited; if (_deposited != 0) { _decrementDeposited(_deposited); } // Transfer the balance rather than the deposit value in case there are any synths left over // from direct transfers. IERC20 sUSD = _sUSD(); uint balance = sUSD.balanceOf(address(this)); if (balance != 0) { sUSD.transfer(beneficiary, balance); } // Destroy the option tokens before destroying the market itself. options.long.expire(beneficiary); options.short.expire(beneficiary); selfdestruct(beneficiary); } function cancel(address payable beneficiary) external onlyOwner duringBidding { (uint longTotalBids, uint shortTotalBids) = _totalBids(); (uint creatorLongBids, uint creatorShortBids) = _bidsOf(creator); bool cancellable = longTotalBids == creatorLongBids && shortTotalBids == creatorShortBids; require(cancellable, "Not cancellable"); _selfDestruct(beneficiary); } function expire(address payable beneficiary) external onlyOwner { require(_expired(), "Unexpired options remaining"); _selfDestruct(beneficiary); } /* ========== MODIFIERS ========== */ modifier duringBidding() { require(!_biddingEnded(), "Bidding inactive"); _; } modifier afterBidding() { require(_biddingEnded(), "Bidding incomplete"); _; } modifier afterMaturity() { require(_matured(), "Not yet mature"); _; } modifier systemActive() { _systemStatus().requireSystemActive(); _; } modifier managerNotPaused() { _requireManagerNotPaused(); _; } /* ========== EVENTS ========== */ event Bid(Side side, address indexed account, uint value); event Refund(Side side, address indexed account, uint value, uint fee); event PricesUpdated(uint longPrice, uint shortPrice); event MarketResolved( Side result, uint oraclePrice, uint oracleTimestamp, uint deposited, uint poolFees, uint creatorFees ); event OptionsClaimed(address indexed account, uint longOptions, uint shortOptions); event OptionsExercised(address indexed account, uint value); }
The argument order is allowance[owner][spender] Enforce a 1 cent minimum bid balance
contract BinaryOption is IERC20, IBinaryOption { using SafeMath for uint; using SafeDecimalMath for uint; string public constant name = "SNX Binary Option"; string public constant symbol = "sOPT"; uint8 public constant decimals = 18; BinaryOptionMarket public market; mapping(address => uint) public bidOf; uint public totalBids; mapping(address => uint) public balanceOf; uint public totalSupply; mapping(address => mapping(address => uint)) public allowance; uint internal constant _MINIMUM_BID = 1e16; constructor(address initialBidder, uint initialBid) public { market = BinaryOptionMarket(msg.sender); bidOf[initialBidder] = initialBid; totalBids = initialBid; } function _claimableBalanceOf( uint _bid, uint price, uint exercisableDeposits ) internal view returns (uint) { uint owed = _bid.divideDecimal(price); uint supply = _totalClaimableSupply(exercisableDeposits); based on rounding errors with the price. Therefore if the user's bid is the entire rest of the pot, just give them everything that's left. If there is no supply, then this option lost, and we'll return 0. if ((_bid == totalBids && _bid != 0) || supply == 0) { return supply; } the situation where supply < owed on the winning side. If somehow a user who is not the last bidder is owed more than what's available, subsequent bidders will be disadvantaged. Given that the minimum bid is 10^16 wei, this should never occur in reality. */ require(owed <= supply, "supply < claimable"); return owed; } function _claimableBalanceOf( uint _bid, uint price, uint exercisableDeposits ) internal view returns (uint) { uint owed = _bid.divideDecimal(price); uint supply = _totalClaimableSupply(exercisableDeposits); based on rounding errors with the price. Therefore if the user's bid is the entire rest of the pot, just give them everything that's left. If there is no supply, then this option lost, and we'll return 0. if ((_bid == totalBids && _bid != 0) || supply == 0) { return supply; } the situation where supply < owed on the winning side. If somehow a user who is not the last bidder is owed more than what's available, subsequent bidders will be disadvantaged. Given that the minimum bid is 10^16 wei, this should never occur in reality. */ require(owed <= supply, "supply < claimable"); return owed; } but losing options are not claimable, therefore we only need to worry about function claimableBalanceOf(address account) external view returns (uint) { (uint price, uint exercisableDeposits) = market.senderPriceAndExercisableDeposits(); return _claimableBalanceOf(bidOf[account], price, exercisableDeposits); } function _totalClaimableSupply(uint exercisableDeposits) internal view returns (uint) { uint _totalSupply = totalSupply; if (exercisableDeposits <= _totalSupply) { return 0; } return exercisableDeposits.sub(_totalSupply); } function _totalClaimableSupply(uint exercisableDeposits) internal view returns (uint) { uint _totalSupply = totalSupply; if (exercisableDeposits <= _totalSupply) { return 0; } return exercisableDeposits.sub(_totalSupply); } function totalClaimableSupply() external view returns (uint) { (, uint exercisableDeposits) = market.senderPriceAndExercisableDeposits(); return _totalClaimableSupply(exercisableDeposits); } function _requireMinimumBid(uint bid) internal pure returns (uint) { require(bid >= _MINIMUM_BID || bid == 0, "Balance < $0.01"); return bid; } function bid(address bidder, uint newBid) external onlyMarket { bidOf[bidder] = _requireMinimumBid(bidOf[bidder].add(newBid)); totalBids = totalBids.add(newBid); } function refund(address bidder, uint newRefund) external onlyMarket { bidOf[bidder] = _requireMinimumBid(bidOf[bidder].sub(newRefund)); totalBids = totalBids.sub(newRefund); } function claim( address claimant, uint price, uint depositsRemaining ) external onlyMarket returns (uint optionsClaimed) { uint _bid = bidOf[claimant]; uint claimable = _claimableBalanceOf(_bid, price, depositsRemaining); if (claimable == 0) { return 0; } totalBids = totalBids.sub(_bid); bidOf[claimant] = 0; totalSupply = totalSupply.add(claimable); emit Transfer(address(0), claimant, claimable); emit Issued(claimant, claimable); return claimable; } function claim( address claimant, uint price, uint depositsRemaining ) external onlyMarket returns (uint optionsClaimed) { uint _bid = bidOf[claimant]; uint claimable = _claimableBalanceOf(_bid, price, depositsRemaining); if (claimable == 0) { return 0; } totalBids = totalBids.sub(_bid); bidOf[claimant] = 0; totalSupply = totalSupply.add(claimable); emit Transfer(address(0), claimant, claimable); emit Issued(claimant, claimable); return claimable; } function exercise(address claimant) external onlyMarket { uint balance = balanceOf[claimant]; if (balance == 0) { return; } balanceOf[claimant] = 0; totalSupply = totalSupply.sub(balance); emit Transfer(claimant, address(0), balance); emit Burned(claimant, balance); } function exercise(address claimant) external onlyMarket { uint balance = balanceOf[claimant]; if (balance == 0) { return; } balanceOf[claimant] = 0; totalSupply = totalSupply.sub(balance); emit Transfer(claimant, address(0), balance); emit Burned(claimant, balance); } function expire(address payable beneficiary) external onlyMarket { selfdestruct(beneficiary); } function _transfer( address _from, address _to, uint _value ) internal returns (bool success) { market.requireActiveAndUnpaused(); require(_to != address(0) && _to != address(this), "Invalid address"); uint fromBalance = balanceOf[_from]; require(_value <= fromBalance, "Insufficient balance"); balanceOf[_from] = fromBalance.sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function transfer(address _to, uint _value) external returns (bool success) { return _transfer(msg.sender, _to, _value); } function transferFrom( address _from, address _to, uint _value ) external returns (bool success) { uint fromAllowance = allowance[_from][msg.sender]; require(_value <= fromAllowance, "Insufficient allowance"); allowance[_from][msg.sender] = fromAllowance.sub(_value); return _transfer(_from, _to, _value); } function approve(address _spender, uint _value) external returns (bool success) { require(_spender != address(0)); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } modifier onlyMarket() { require(msg.sender == address(market), "Only market allowed"); _; } event Issued(address indexed account, uint value); event Burned(address indexed account, uint value); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); }
883,553
[ 1, 1986, 1237, 1353, 353, 1699, 1359, 63, 8443, 6362, 87, 1302, 264, 65, 31716, 279, 404, 8301, 5224, 9949, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7896, 1895, 353, 467, 654, 39, 3462, 16, 467, 5905, 1895, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 565, 1450, 14060, 5749, 10477, 364, 2254, 31, 203, 203, 203, 565, 533, 1071, 5381, 508, 273, 315, 13653, 60, 7896, 2698, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 87, 15620, 14432, 203, 565, 2254, 28, 1071, 5381, 15105, 273, 6549, 31, 203, 203, 565, 7896, 1895, 3882, 278, 1071, 13667, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 1071, 9949, 951, 31, 203, 565, 2254, 1071, 2078, 38, 2232, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 1071, 11013, 951, 31, 203, 565, 2254, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 1071, 1699, 1359, 31, 203, 203, 565, 2254, 2713, 5381, 389, 6236, 18605, 67, 38, 734, 273, 404, 73, 2313, 31, 203, 203, 203, 203, 203, 203, 565, 3885, 12, 2867, 2172, 17763, 765, 16, 2254, 2172, 17763, 13, 1071, 288, 203, 3639, 13667, 273, 7896, 1895, 3882, 278, 12, 3576, 18, 15330, 1769, 203, 3639, 9949, 951, 63, 6769, 17763, 765, 65, 273, 2172, 17763, 31, 203, 3639, 2078, 38, 2232, 273, 2172, 17763, 31, 203, 565, 289, 203, 203, 203, 565, 445, 389, 14784, 429, 13937, 951, 12, 203, 3639, 2254, 389, 19773, 16, 203, 3639, 2254, 6205, 16, 203, 3639, 2254, 431, 12610, 291, 429, 758, 917, 1282, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 13, 288, 203, 2 ]
pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT import "./DaoConstants.sol"; import "../helpers/FlagHelper.sol"; import "../guards/AdapterGuard.sol"; import "../utils/IERC20.sol"; import "../utils/SafeMath.sol"; /** MIT License Copyright (c) 2020 Openlaw 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. */ contract DaoRegistry is DaoConstants, AdapterGuard { bool public initialized = false; // internally tracks deployment under eip-1167 proxy pattern /* * LIBRARIES */ using FlagHelper for uint256; using SafeMath for uint256; enum DaoState {CREATION, READY} /* * EVENTS */ /// @dev - Events for Proposals event SubmittedProposal(uint64 proposalId, uint256 flags); event SponsoredProposal(uint64 proposalId, uint256 flags); event ProcessedProposal(uint64 proposalId, uint256 flags); event AdapterAdded( bytes32 adapterId, address adapterAddress, uint256 flags ); event AdapterRemoved(bytes32 adapterId); /// @dev - Events for Members event UpdateDelegateKey(address memberAddress, address newDelegateKey); /// @dev - Events for Bank event MemberJailed(address memberAddr); event MemberUnjailed(address memberAddr); event NewBalance(address member, address tokenAddr, uint256 amount); /* * STRUCTURES */ struct Proposal { // the structure to track all the proposals in the DAO address adapterAddress; // the adapter address that called the functions to change the DAO state uint256 flags; // flags to track the state of the proposal: exist, sponsored, processed, canceled, etc. } struct Member { // the structure to track all the members in the DAO uint256 flags; // flags to track the state of the member: exist, jailed, etc } struct Checkpoint { // A checkpoint for marking number of votes from a given block uint96 fromBlock; uint160 amount; } struct DelegateCheckpoint { // A checkpoint for marking number of votes from a given block uint96 fromBlock; address delegateKey; } struct Bank { address[] tokens; address[] internalTokens; // tokenAddress => availability mapping(address => bool) availableTokens; mapping(address => bool) availableInternalTokens; // tokenAddress => memberAddress => checkpointNum => Checkpoint mapping(address => mapping(address => mapping(uint32 => Checkpoint))) checkpoints; // tokenAddress => memberAddress => numCheckpoints mapping(address => mapping(address => uint32)) numCheckpoints; } struct AdapterDetails { bytes32 id; uint256 acl; } /* * PUBLIC VARIABLES */ mapping(address => Member) public members; // the map to track all members of the DAO // delegate key => member address mapping mapping(address => address) public memberAddressesByDelegatedKey; Bank private _bank; // the state of the DAO Bank // memberAddress => checkpointNum => DelegateCheckpoint mapping(address => mapping(uint32 => DelegateCheckpoint)) checkpoints; // memberAddress => numDelegateCheckpoints mapping(address => uint32) numCheckpoints; DaoState public state; /// @notice The number of proposals submitted to the DAO uint64 public proposalCount; /// @notice The map that keeps track of all proposasls submitted to the DAO mapping(uint64 => Proposal) public proposals; /// @notice The map that keeps track of all adapters registered in the DAO mapping(bytes32 => address) public registry; /// @notice The inverse map to get the adapter id based on its address mapping(address => AdapterDetails) public inverseRegistry; /// @notice The map that keeps track of configuration parameters for the DAO and adapters mapping(bytes32 => uint256) public configuration; /// @notice Clonable contract must have an empty constructor // constructor() { // } //TODO: we may need to add some ACL to ensure only the factory is allowed to clone it, otherwise //any will able to deploy it, and the first one to call this function is added to the DAO as a member. /** * @notice Initialises the DAO * @dev Involves initialising available tokens, checkpoints, and membership of creator * @dev Can only be called once * @param creator The DAO's creator, who will be the first member */ function initialize(address creator) external { require(!initialized, "dao already initialized"); address memberAddr = creator; Member storage member = members[memberAddr]; member.flags = member.flags.setFlag(FlagHelper.Flag.EXISTS, true); memberAddressesByDelegatedKey[memberAddr] = memberAddr; _bank.availableInternalTokens[SHARES] = true; _bank.internalTokens.push(SHARES); _createNewAmountCheckpoint(memberAddr, SHARES, 1); _createNewAmountCheckpoint(TOTAL, SHARES, 1); initialized = true; } receive() external payable { revert("you cannot send money back directly"); } /** * @dev Sets the state of the dao to READY */ function finalizeDao() external { state = DaoState.READY; } /** * @notice Sets a configuration value * @dev Changes the value of a key in the configuration mapping * @param key The configuration key for which the value will be set * @param value The value to set the key */ function setConfiguration(bytes32 key, uint256 value) external hasAccess(this, FlagHelper.Flag.SET_CONFIGURATION) { configuration[key] = value; } /** * @return The configuration value of a particular key * @param key The key to look up in the configuration mapping */ function getConfiguration(bytes32 key) external view returns (uint256) { return configuration[key]; } /** * @notice Adds a new adapter to the registry * @param adapterId The unique identifier of the new adapter * @param adapterAddress The address of the adapter * @param acl The access control list of the adapter */ function addAdapter( bytes32 adapterId, address adapterAddress, uint256 acl ) external hasAccess(this, FlagHelper.Flag.ADD_ADAPTER) { require(adapterId != bytes32(0), "adapterId must not be empty"); require( adapterAddress != address(0x0), "adapterAddress must not be empty" ); require( registry[adapterId] == address(0x0), "adapterId already in use" ); registry[adapterId] = adapterAddress; inverseRegistry[adapterAddress].id = adapterId; inverseRegistry[adapterAddress].acl = acl; emit AdapterAdded(adapterId, adapterAddress, acl); } /** * @notice Removes an adapter from the registry * @param adapterId The unique identifier of the adapter */ function removeAdapter(bytes32 adapterId) external hasAccess(this, FlagHelper.Flag.REMOVE_ADAPTER) { require(adapterId != bytes32(0), "adapterId must not be empty"); require( registry[adapterId] != address(0x0), "adapterId not registered" ); delete inverseRegistry[registry[adapterId]]; delete registry[adapterId]; emit AdapterRemoved(adapterId); } /** * @notice Looks up if there is an adapter of a given address * @return Whether or not the address is an adapter * @param adapterAddress The address to look up */ function isAdapter(address adapterAddress) public view returns (bool) { return inverseRegistry[adapterAddress].id != bytes32(0); } /** * @notice Checks if an adapter has a given ACL flag * @return Whether or not the given adapter has the given flag set * @param adapterAddress The address to look up * @param flag The ACL flag to check against the given address */ function hasAdapterAccess(address adapterAddress, FlagHelper.Flag flag) public view returns (bool) { return inverseRegistry[adapterAddress].id != bytes32(0) && inverseRegistry[adapterAddress].acl.getFlag(flag); } /** * @return The address of a given adapter ID * @param adapterId The ID to look up */ function getAdapterAddress(bytes32 adapterId) external view returns (address) { return registry[adapterId]; } /** * @notice Jails a member * @dev Sets all relevant flags and delegations to ensure a user can not participate * @param memberAddr The member to jail */ function jailMember(address memberAddr) external hasAccess(this, FlagHelper.Flag.JAIL_MEMBER) { Member storage member = members[memberAddr]; uint256 flags = member.flags; require(flags.getFlag(FlagHelper.Flag.EXISTS), "member does not exist"); if (!flags.getFlag(FlagHelper.Flag.JAILED)) { member.flags = flags.setFlag(FlagHelper.Flag.JAILED, true); // Stop the member from voting at that point in time _createNewDelegateCheckpoint(memberAddr, address(1)); // 1 instead of 0 to avoid existence check emit MemberJailed(memberAddr); } } /** * @notice Unjails a member * @dev Resets all relevant flags to allow participation * @param memberAddr The member to unjail */ function unjailMember(address memberAddr) external hasAccess(this, FlagHelper.Flag.UNJAIL_MEMBER) { Member storage member = members[memberAddr]; uint256 flags = member.flags; require(flags.getFlag(FlagHelper.Flag.EXISTS), "member does not exist"); if (flags.getFlag(FlagHelper.Flag.JAILED)) { member.flags = flags.setFlag(FlagHelper.Flag.JAILED, false); _createNewDelegateCheckpoint( memberAddr, getPreviousDelegateKey(memberAddr) ); // we do this to re-allow votes emit MemberUnjailed(memberAddr); } } /** * @notice Executes an arbitrary function call * @dev Calls a function and reverts if unsuccessful * @return The return data of the function call * @param _actionTo The address at which the function will be called * @param _actionValue The value to pass in to function call * @param _actionData The data to give the function call */ function execute( address _actionTo, uint256 _actionValue, bytes calldata _actionData ) external hasAccess(this, FlagHelper.Flag.EXECUTE) returns (bytes memory) { (bool success, bytes memory retData) = _actionTo.call{ value: _actionValue }(_actionData); if (!success) { string memory m = _getRevertMsg(retData); revert(m); } return retData; } /** * PROPOSALS */ /** * @notice Submit proposals to the DAO registry * @return The proposal ID of the newly-created proposal */ function submitProposal() external hasAccess(this, FlagHelper.Flag.SUBMIT_PROPOSAL) returns (uint64) { proposals[proposalCount++] = Proposal(msg.sender, 1); uint64 proposalId = proposalCount - 1; emit SubmittedProposal(proposalId, 1); return proposalId; } /** * @notice Sponsor proposals that were submitted to the DAO registry * @dev adds SPONSORED to the proposal flag * @param proposalId The ID of the proposal to sponsor * @param sponsoringMember The member who is sponsoring the proposal */ function sponsorProposal(uint64 proposalId, address sponsoringMember) external hasAccess(this, FlagHelper.Flag.SPONSOR_PROPOSAL) { Proposal storage proposal = _setProposalFlag( proposalId, FlagHelper.Flag.SPONSORED ); uint256 flags = proposal.flags; require( proposal.adapterAddress == msg.sender, "only the adapter that submitted the proposal can process it" ); require( flags.getFlag(FlagHelper.Flag.EXISTS), "proposal does not exist" ); require( !flags.getFlag(FlagHelper.Flag.PROCESSED), "proposal must not be processed" ); require( isActiveMember(sponsoringMember), "only active members can sponsor proposals" ); emit SponsoredProposal(proposalId, flags); } /** * @notice Mark a proposal as processed in the DAO registry * @param proposalId The ID of the proposal that is being processed */ function processProposal(uint64 proposalId) external hasAccess(this, FlagHelper.Flag.PROCESS_PROPOSAL) { Proposal storage proposal = _setProposalFlag( proposalId, FlagHelper.Flag.PROCESSED ); uint256 flags = proposal.flags; emit ProcessedProposal(proposalId, flags); } /** * @notice Sets a flag of a proposal * @dev Reverts if the proposal is already processed * @param proposalId The ID of the proposal to be changed * @param flag The flag that will be set on the proposal */ function _setProposalFlag(uint64 proposalId, FlagHelper.Flag flag) internal returns (Proposal storage) { Proposal storage proposal = proposals[proposalId]; require( proposal.adapterAddress == msg.sender, "only the adapter that submitted the proposal can set its flag" ); uint256 flags = proposal.flags; require( flags.getFlag(FlagHelper.Flag.EXISTS), "proposal does not exist for this dao" ); require( !flags.getFlag(FlagHelper.Flag.PROCESSED), "proposal already processed" ); flags = flags.setFlag(flag, true); proposals[proposalId].flags = flags; return proposals[proposalId]; } /** * @return Whether or not the given token is an available internal token in the bank * @param token The address of the token to look up */ function isInternalToken(address token) external view returns (bool) { return _bank.availableInternalTokens[token]; } /** * @return Whether or not the given token is an available token in the bank * @param token The address of the token to look up */ function isTokenAllowed(address token) external view returns (bool) { return _bank.availableTokens[token]; } /* * MEMBERS */ /** * @return Whether or not a given address is an active member of the DAO * @dev Requires the user to not be jailed and have a positive balance in either * SHARES, LOOT or LOCKED_LOOT * @param addr The address to look up */ function isActiveMember(address addr) public view returns (bool) { address memberAddr = memberAddressesByDelegatedKey[addr]; uint256 memberFlags = members[memberAddr].flags; return memberFlags.getFlag(FlagHelper.Flag.EXISTS) && !memberFlags.getFlag(FlagHelper.Flag.JAILED) && (balanceOf(memberAddr, SHARES) > 0 || balanceOf(memberAddr, LOOT) > 0 || balanceOf(memberAddr, LOCKED_LOOT) > 0); } /** * @return Whether or not a flag is set for a given proposal * @param proposalId The proposal to check against flag * @param flag The flag to check in the proposal */ function getProposalFlag(uint64 proposalId, FlagHelper.Flag flag) external view returns (bool) { return proposals[proposalId].flags.getFlag(flag); } /** * @notice Updates the delegate key of a member * @param memberAddr The member doing the delegation * @param newDelegateKey The member who is being delegated to */ function updateDelegateKey(address memberAddr, address newDelegateKey) external hasAccess(this, FlagHelper.Flag.UPDATE_DELEGATE_KEY) { require(newDelegateKey != address(0), "newDelegateKey cannot be 0"); // skip checks if member is setting the delegate key to their member address if (newDelegateKey != memberAddr) { require( // newDelegate must not be delegated to memberAddressesByDelegatedKey[newDelegateKey] == address(0x0), "cannot overwrite existing members" ); require( // TODO: This will always be memberAddressesByDelegatedKey[0], due to the previous require memberAddressesByDelegatedKey[memberAddressesByDelegatedKey[newDelegateKey]] == address(0x0), "cannot overwrite existing delegate keys" ); } Member storage member = members[memberAddr]; require( member.flags.getFlag(FlagHelper.Flag.EXISTS), "member does not exist" ); // Reset the delegation of the previous delegate memberAddressesByDelegatedKey[getCurrentDelegateKey( memberAddr )] = address(0x0); memberAddressesByDelegatedKey[newDelegateKey] = memberAddr; _createNewDelegateCheckpoint(memberAddr, newDelegateKey); emit UpdateDelegateKey(memberAddr, newDelegateKey); } /* * BANK */ /** * @notice Registers a potential new token in the bank * @dev Can not be a reserved token or an available internal token * @param token The address of the token */ function registerPotentialNewToken(address token) external hasAccess(this, FlagHelper.Flag.REGISTER_NEW_TOKEN) { require(isNotReservedAddress(token), "reservedToken"); require(!_bank.availableInternalTokens[token], "internalToken"); if (!_bank.availableTokens[token]) { _bank.availableTokens[token] = true; _bank.tokens.push(token); } } /** * @notice Registers a potential new internal token in the bank * @dev Can not be a reserved token or an available token * @param token The address of the token */ function registerPotentialNewInternalToken(address token) external hasAccess(this, FlagHelper.Flag.REGISTER_NEW_INTERNAL_TOKEN) { require(isNotReservedAddress(token), "reservedToken"); require(!_bank.availableTokens[token], "internalToken"); if (!_bank.availableInternalTokens[token]) { _bank.availableInternalTokens[token] = true; _bank.internalTokens.push(token); } } /** * Public read-only functions */ /** * @return Whether or not a given address is reserved * @dev Returns false if applicant address is one of the constants GUILD or TOTAL * @param applicant The address to check */ function isNotReservedAddress(address applicant) public pure returns (bool) { return applicant != GUILD && applicant != TOTAL; } /** * Internal bookkeeping */ /** * @return The token from the bank of a given index * @param index The index to look up in the bank's tokens */ function getToken(uint256 index) external view returns (address) { return _bank.tokens[index]; } /** * @return The amount of token addresses in the bank */ function nbTokens() external view returns (uint256) { return _bank.tokens.length; } /** * @return The internal token at a given index * @param index The index to look up in the bank's array of internal tokens */ function getInternalToken(uint256 index) external view returns (address) { return _bank.internalTokens[index]; } /** * @return The amount of internal token addresses in the bank */ function nbInternalTokens() external view returns (uint256) { return _bank.internalTokens.length; } /** * @notice Adds to a user's balance of a given token * @param user The user whose balance will be updated * @param token The token to update * @param amount The new balance */ function addToBalance( address user, address token, uint256 amount ) public hasAccess(this, FlagHelper.Flag.ADD_TO_BALANCE) { require( _bank.availableTokens[token] || _bank.availableInternalTokens[token], "unknown token address" ); uint256 newAmount = balanceOf(user, token) + amount; uint256 newTotalAmount = balanceOf(TOTAL, token) + amount; _createNewAmountCheckpoint(user, token, newAmount); _createNewAmountCheckpoint(TOTAL, token, newTotalAmount); Member storage member = members[user]; if (!member.flags.getFlag(FlagHelper.Flag.EXISTS)) { member.flags = member.flags.setFlag(FlagHelper.Flag.EXISTS, true); memberAddressesByDelegatedKey[user] = user; } } /** * @notice Remove from a user's balance of a given token * @param user The user whose balance will be updated * @param token The token to update * @param amount The new balance */ function subtractFromBalance( address user, address token, uint256 amount ) public hasAccess(this, FlagHelper.Flag.SUB_FROM_BALANCE) { uint256 newAmount = balanceOf(user, token) - amount; uint256 newTotalAmount = balanceOf(TOTAL, token) - amount; _createNewAmountCheckpoint(user, token, newAmount); _createNewAmountCheckpoint(TOTAL, token, newTotalAmount); } /** * @notice Make an internal token transfer * @param from The user who is sending tokens * @param to The user who is receiving tokens * @param amount The new amount to transfer */ function internalTransfer( address from, address to, address token, uint256 amount ) public hasAccess(this, FlagHelper.Flag.INTERNAL_TRANSFER) { uint256 newAmount = balanceOf(from, token).sub(amount); uint256 newAmount2 = balanceOf(to, token).add(amount); _createNewAmountCheckpoint(from, token, newAmount); _createNewAmountCheckpoint(to, token, newAmount2); } /** * @notice Returns an account's balance of a given token * @param account The address to look up * @param tokenAddr The token where the user's balance of which will be returned * @return The amount in account's tokenAddr balance */ function balanceOf(address account, address tokenAddr) public view returns (uint256) { uint32 nCheckpoints = _bank.numCheckpoints[tokenAddr][account]; return nCheckpoints > 0 ? _bank.checkpoints[tokenAddr][account][nCheckpoints - 1].amount : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorAmount( address account, address tokenAddr, uint256 blockNumber ) external view returns (uint256) { require( blockNumber < block.number, "Uni::getPriorAmount: not yet determined" ); uint32 nCheckpoints = _bank.numCheckpoints[tokenAddr][account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if ( _bank.checkpoints[tokenAddr][account][nCheckpoints - 1].fromBlock <= blockNumber ) { return _bank.checkpoints[tokenAddr][account][nCheckpoints - 1].amount; } // Next check implicit zero balance if (_bank.checkpoints[tokenAddr][account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = _bank .checkpoints[tokenAddr][account][center]; if (cp.fromBlock == blockNumber) { return cp.amount; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return _bank.checkpoints[tokenAddr][account][lower].amount; } /** * @param memberAddr The member whose delegate will be returned * @return the delegate key at the current time for a member */ function getCurrentDelegateKey(address memberAddr) public view returns (address) { uint32 nCheckpoints = numCheckpoints[memberAddr]; return nCheckpoints > 0 ? checkpoints[memberAddr][nCheckpoints - 1].delegateKey : memberAddr; } /** * @param memberAddr The member address to look up * @return The delegate key address for memberAddr at the second last checkpoint number */ function getPreviousDelegateKey(address memberAddr) public view returns (address) { uint32 nCheckpoints = numCheckpoints[memberAddr]; return nCheckpoints > 1 ? checkpoints[memberAddr][nCheckpoints - 2].delegateKey : memberAddr; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param memberAddr The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorDelegateKey(address memberAddr, uint256 blockNumber) external view returns (address) { require( blockNumber < block.number, "Uni::getPriorDelegateKey: not yet determined" ); uint32 nCheckpoints = numCheckpoints[memberAddr]; if (nCheckpoints == 0) { return memberAddr; } // First check most recent balance if ( checkpoints[memberAddr][nCheckpoints - 1].fromBlock <= blockNumber ) { return checkpoints[memberAddr][nCheckpoints - 1].delegateKey; } // Next check implicit zero balance if (checkpoints[memberAddr][0].fromBlock > blockNumber) { return memberAddr; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow DelegateCheckpoint memory cp = checkpoints[memberAddr][center]; if (cp.fromBlock == blockNumber) { return cp.delegateKey; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[memberAddr][lower].delegateKey; } /** * @notice Creates a new amount checkpoint for a token of a certain member * @param member The member whose checkpoints will be added to * @param tokenAddr The token of which the balance will be changed * @param amount The amount to be written into the new checkpoint */ function _createNewAmountCheckpoint( address member, address tokenAddr, uint256 amount ) internal { uint32 srcRepNum = _bank.numCheckpoints[tokenAddr][member]; _writeAmountCheckpoint(member, tokenAddr, srcRepNum, amount); emit NewBalance(member, tokenAddr, amount); } /** * @notice Creates a new delegate checkpoint of a certain member * @param member The member whose delegate checkpoints will be added to * @param newDelegateKey The delegate key that will be written into the new checkpoint */ function _createNewDelegateCheckpoint( address member, address newDelegateKey ) internal { uint32 srcRepNum = numCheckpoints[member]; _writeDelegateCheckpoint(member, srcRepNum, newDelegateKey); } /** * @notice Writes to a delegate checkpoint of a certain checkpoint number * @dev Creates a new checkpoint if there is not yet one of the given number * @param member The member whose delegate checkpoints will overwritten * @param nCheckpoints The number of the checkpoint to overwrite * @param newDelegateKey The delegate key that will be written into the checkpoint */ function _writeDelegateCheckpoint( address member, uint32 nCheckpoints, address newDelegateKey ) internal { if ( nCheckpoints > 0 && checkpoints[member][nCheckpoints - 1].fromBlock == block.number ) { checkpoints[member][nCheckpoints - 1].delegateKey = newDelegateKey; } else { checkpoints[member][nCheckpoints] = DelegateCheckpoint( uint96(block.number), newDelegateKey ); numCheckpoints[member] = nCheckpoints + 1; } } /** * @notice Writes to an amount checkpoint of a certain checkpoint number * @dev Creates a new checkpoint if there is not yet one of the given number * @param member The member whose delegate checkpoints will overwritten * @param tokenAddr The token that will have its balance for the user udpated * @param nCheckpoints The number of the checkpoint to overwrite * @param _newAmount The amount to write into the specified checkpoint */ function _writeAmountCheckpoint( address member, address tokenAddr, uint32 nCheckpoints, uint256 _newAmount ) internal { require(_newAmount < type(uint160).max, "too big of a vote"); uint160 newAmount = uint160(_newAmount); if ( nCheckpoints > 0 && _bank.checkpoints[tokenAddr][member][nCheckpoints - 1].fromBlock == block.number ) { _bank.checkpoints[tokenAddr][member][nCheckpoints - 1] .amount = newAmount; } else { _bank.checkpoints[tokenAddr][member][nCheckpoints] = Checkpoint( uint96(block.number), newAmount ); _bank.numCheckpoints[tokenAddr][member] = nCheckpoints + 1; } } /* * Internal Utility Functions */ /** * @dev Get the revert message from a call * @notice This is needed in order to get the human-readable revert message from a call * @param _res Response of the call * @return Revert message string */ function _getRevertMsg(bytes memory _res) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_res.length < 68) return "Transaction reverted silently"; bytes memory revertData = _slice(_res, 4, _res.length - 4); // Remove the selector which is the first 4 bytes return abi.decode(revertData, (string)); // All that remains is the revert string } /** * @notice Slices a bytes type * @param _bytes The bytes that will be sliced * @param _start The start index to begin slicing from * @param _length The number of bytes to include in the slice, starting from _start * @return A new bytes object, that is the same as _bytes, from indices _start to (_start + length) */ function _slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "Read out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add( add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)) ) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add( add( add(_bytes, lengthmod), mul(0x20, iszero(lengthmod)) ), _start ) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } }
* @notice Slices a bytes type @param _bytes The bytes that will be sliced @param _start The start index to begin slicing from @param _length The number of bytes to include in the slice, starting from _start @return A new bytes object, that is the same as _bytes, from indices _start to (_start + length)/ Get a location of some free memory and store it in tempBytes as Solidity does for memory variables. The first word of the slice result is potentially a partial word read from the original array. To read it, we calculate the length of that partial word and start copying that many bytes into the array. The first word we copy will start with data we don't care about, but the last `lengthmod` bytes will land at the beginning of the contents of the new array. When we're done copying, we overwrite the full first word with the actual length of the slice. The multiplication in the next line is necessary because when slicing multiples of 32 bytes (lengthmod == 0) the following copy loop was copying the origin's length and then ending prematurely not copying everything it should. The multiplication in the next line has the same exact purpose as the one above.if we want a zero-length slice let's just return a zero-length array
function _slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length), "Read out of bounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { tempBytes := mload(0x40) let lengthmod := and(_length, 31) let mc := add( add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)) ) let end := add(mc, _length) for { let cc := add( add( add(_bytes, lengthmod), mul(0x20, iszero(lengthmod)) ), _start ) mc := add(mc, 0x20) cc := add(cc, 0x20) mstore(mc, mload(cc)) } mstore(tempBytes, _length) } default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; }
5,421,689
[ 1, 26613, 279, 1731, 618, 225, 389, 3890, 1021, 1731, 716, 903, 506, 27353, 225, 389, 1937, 1021, 787, 770, 358, 2376, 2020, 14774, 628, 225, 389, 2469, 1021, 1300, 434, 1731, 358, 2341, 316, 326, 2788, 16, 5023, 628, 389, 1937, 327, 432, 394, 1731, 733, 16, 716, 353, 326, 1967, 487, 389, 3890, 16, 628, 4295, 389, 1937, 358, 261, 67, 1937, 397, 769, 13176, 968, 279, 2117, 434, 2690, 4843, 3778, 471, 1707, 518, 316, 1906, 2160, 487, 348, 7953, 560, 1552, 364, 3778, 3152, 18, 1021, 1122, 2076, 434, 326, 2788, 563, 353, 13935, 279, 4702, 2076, 855, 628, 326, 2282, 526, 18, 2974, 855, 518, 16, 732, 4604, 326, 769, 434, 716, 4702, 2076, 471, 787, 8933, 716, 4906, 1731, 1368, 326, 526, 18, 1021, 1122, 2076, 732, 1610, 903, 787, 598, 501, 732, 2727, 1404, 7671, 2973, 16, 1496, 326, 1142, 1375, 2469, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 6665, 12, 203, 3639, 1731, 3778, 389, 3890, 16, 203, 3639, 2254, 5034, 389, 1937, 16, 203, 3639, 2254, 5034, 389, 2469, 203, 565, 262, 2713, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 2583, 24899, 3890, 18, 2469, 1545, 261, 67, 1937, 397, 389, 2469, 3631, 315, 1994, 596, 434, 4972, 8863, 203, 203, 3639, 1731, 3778, 1906, 2160, 31, 203, 203, 3639, 19931, 288, 203, 5411, 1620, 353, 7124, 24899, 2469, 13, 203, 7734, 648, 374, 288, 203, 10792, 1906, 2160, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 203, 10792, 2231, 769, 1711, 519, 471, 24899, 2469, 16, 8231, 13, 203, 203, 10792, 2231, 6108, 519, 527, 12, 203, 13491, 527, 12, 5814, 2160, 16, 769, 1711, 3631, 203, 13491, 14064, 12, 20, 92, 3462, 16, 353, 7124, 12, 2469, 1711, 3719, 203, 10792, 262, 203, 10792, 2231, 679, 519, 527, 12, 13952, 16, 389, 2469, 13, 203, 203, 10792, 364, 288, 203, 13491, 2231, 4946, 519, 527, 12, 203, 18701, 527, 12, 203, 27573, 527, 24899, 3890, 16, 769, 1711, 3631, 203, 27573, 14064, 12, 20, 92, 3462, 16, 353, 7124, 12, 2469, 1711, 3719, 203, 18701, 262, 16, 203, 18701, 389, 1937, 203, 13491, 262, 203, 13491, 6108, 519, 527, 12, 13952, 16, 374, 92, 3462, 13, 203, 13491, 4946, 519, 527, 12, 952, 16, 374, 92, 3462, 13, 203, 13491, 312, 2233, 12, 13952, 16, 312, 945, 12, 952, 3719, 203, 10792, 289, 203, 203, 10792, 312, 2233, 12, 5814, 2160, 16, 389, 2 ]
./full_match/5/0xdEA5DDa469e0c8d4193545cA6AaAaeD24F1CeF3b/sources/contracts/core/BaseAccount.sol
* Basic account implementation. this contract provides the basic logic for implementing the IAccount interface - validateUserOp specific account implementation should inherit it and provide the account-specific logic/return value in case of signature failure, with no time-range. equivalent to _packValidationData(true,0,0);
abstract contract BaseAccount is IAccount { using UserOperationLib for UserOperation; uint256 constant internal SIG_VALIDATION_FAILED = 1; pragma solidity ^0.8.12; function getNonce() public view virtual returns (uint256) { return entryPoint().getNonce(address(this), 0); } function entryPoint() public view virtual returns (IEntryPoint); function validateUserOp(UserOperation calldata userOp, bytes32 userOpHash, uint256 missingAccountFunds) external override virtual returns (uint256 validationData) { _requireFromEntryPoint(); validationData = _validateSignature(userOp, userOpHash); _validateNonce(userOp.nonce); _payPrefund(missingAccountFunds); } function _requireFromEntryPoint() internal virtual view { require(msg.sender == address(entryPoint()), "account: not from EntryPoint"); } function _validateSignature(UserOperation calldata userOp, bytes32 userOpHash) internal virtual returns (uint256 validationData); function _validateNonce(uint256 nonce) internal view virtual { } function _payPrefund(uint256 missingAccountFunds) internal virtual { if (missingAccountFunds != 0) { (success); } } function _payPrefund(uint256 missingAccountFunds) internal virtual { if (missingAccountFunds != 0) { (success); } } (bool success,) = payable(msg.sender).call{value : missingAccountFunds, gas : type(uint256).max}(""); }
1,894,917
[ 1, 8252, 2236, 4471, 18, 333, 6835, 8121, 326, 5337, 4058, 364, 19981, 326, 467, 3032, 1560, 225, 300, 1954, 1299, 3817, 2923, 2236, 4471, 1410, 6811, 518, 471, 5615, 326, 2236, 17, 12524, 4058, 19, 2463, 460, 316, 648, 434, 3372, 5166, 16, 598, 1158, 813, 17, 3676, 18, 7680, 358, 389, 2920, 4354, 751, 12, 3767, 16, 20, 16, 20, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 3360, 3032, 353, 467, 3032, 288, 203, 565, 1450, 2177, 2988, 5664, 364, 2177, 2988, 31, 203, 203, 565, 2254, 5034, 5381, 2713, 7004, 67, 5063, 2689, 67, 11965, 273, 404, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 2138, 31, 203, 203, 565, 445, 336, 13611, 1435, 1071, 1476, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 28671, 7675, 588, 13611, 12, 2867, 12, 2211, 3631, 374, 1769, 203, 565, 289, 203, 203, 565, 445, 28671, 1435, 1071, 1476, 5024, 1135, 261, 45, 1622, 2148, 1769, 203, 203, 565, 445, 1954, 1299, 3817, 12, 1299, 2988, 745, 892, 729, 3817, 16, 1731, 1578, 729, 3817, 2310, 16, 2254, 5034, 3315, 3032, 42, 19156, 13, 203, 565, 3903, 3849, 5024, 1135, 261, 11890, 5034, 3379, 751, 13, 288, 203, 3639, 389, 6528, 1265, 1622, 2148, 5621, 203, 3639, 3379, 751, 273, 389, 5662, 5374, 12, 1355, 3817, 16, 729, 3817, 2310, 1769, 203, 3639, 389, 5662, 13611, 12, 1355, 3817, 18, 12824, 1769, 203, 3639, 389, 10239, 23218, 1074, 12, 7337, 3032, 42, 19156, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 6528, 1265, 1622, 2148, 1435, 2713, 5024, 1476, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 4099, 2148, 1435, 3631, 315, 4631, 30, 486, 628, 3841, 2148, 8863, 203, 565, 289, 203, 203, 565, 445, 389, 5662, 5374, 12, 1299, 2988, 745, 892, 729, 3817, 16, 1731, 1578, 729, 3817, 2310, 13, 203, 565, 2713, 5024, 1135, 261, 11890, 5034, 2 ]
pragma solidity ^0.5.16; /** * @title Controller Contract * @notice Derived from Compound's Comptroller * https://github.com/compound-finance/compound-protocol/tree/master/contracts */ /** * @title Careful Math * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } /** * @title Exponential module for storing fixed-precision decimals * */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } function truncate(Exp memory exp) pure internal returns (uint) { return exp.mantissa / expScale; } function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } /** * @title ERC-20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { 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 (uint256); function balanceOf(address owner) external view returns (uint256 balance); function transfer(address dst, uint256 amount) external returns (bool success); function transferFrom(address src, address dst, uint256 amount) external returns (bool success); function approve(address spender, uint256 amount) external returns (bool success); function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } /** * @title EIP20NonStandardInterface * https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256 balance); function transfer(address dst, uint256 amount) external; function transferFrom(address src, address dst, uint256 amount) external; function approve(address spender, uint256 amount) external returns (bool success); function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } contract ArtemcontrollerErrorReporter { event Failure(uint error, uint info, uint detail); function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } enum Error { NO_ERROR, UNAUTHORIZED, CONTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } } contract TokenErrorReporter { event Failure(uint error, uint info, uint detail); function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, CONTROLLER_REJECTION, CONTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_CONTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_CONTROLLER_REJECTION, LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_CONTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_CONTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_CONTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_CONTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_CONTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } } pragma solidity ^0.5.16; contract ControllerInterface { bool public constant isController = true; function enterMarkets(address[] calldata aTokens) external returns (uint[] memory); function exitMarket(address aToken) external returns (uint); function mintAllowed(address aToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address aToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address aToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address aToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address aToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address aToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address aToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address aToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address aTokenBorrowed, address aTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address aTokenBorrowed, address aTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address aTokenCollateral, address aTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address aTokenCollateral, address aTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address aToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address aToken, address src, address dst, uint transferTokens) external; function liquidateCalculateSeizeTokens( address aTokenBorrowed, address aTokenCollateral, uint repayAmount) external view returns (uint, uint); } pragma solidity ^0.5.16; contract InterestRateModel { bool public constant isInterestRateModel = true; function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } pragma solidity ^0.5.16; contract ATokenStorage { /** * for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-aToken operations */ ControllerInterface public controller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first ATokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract ATokenInterface is ATokenStorage { bool public constant isAToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address aTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when controller is changed */ event NewController(ControllerInterface oldController, ControllerInterface newController); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setController(ControllerInterface newController) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract AErc20Storage { /** * @notice Underlying asset for this AToken */ address public underlying; } contract AErc20Interface is AErc20Storage { function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, ATokenInterface aTokenCollateral) external returns (uint); function _addReserves(uint addAmount) external returns (uint); } contract ADelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract ADelegatorInterface is ADelegationStorage { event NewImplementation(address oldImplementation, address newImplementation); function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract ADelegateInterface is ADelegationStorage { function _becomeImplementation(bytes memory data) public; function _resignImplementation() public; } pragma solidity ^0.5.16; contract AToken is ATokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param controller_ The address of the Controller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ControllerInterface controller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the controller uint err = _setController(controller_); require(err == uint(Error.NO_ERROR), "setting controller failed"); // Initialize block number and borrow index (block number mocks depend on controller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = controller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.TRANSFER_CONTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint sraTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, sraTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = sraTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); controller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by controller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint aTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), aTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this aToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this aToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the AToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the AToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this aToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives aTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives aTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = controller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.MINT_CONTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The aToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the aToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of aTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of aTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ controller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems aTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of aTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems aTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming aTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems aTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of aTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming aTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = controller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.REDEEM_CONTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The aToken must handle variations between ERC-20 and ETH underlying. * On success, the aToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ controller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = controller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.BORROW_CONTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The aToken must handle variations between ERC-20 and ETH underlying. * On success, the aToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ controller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = controller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.REPAY_BORROW_CONTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The aToken must handle variations between ERC-20 and ETH underlying. * On success, the aToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ controller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this aToken to be liquidated * @param aTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, ATokenInterface aTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = aTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, aTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this aToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param aTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, ATokenInterface aTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = controller.liquidateBorrowAllowed(address(this), address(aTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_CONTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify aTokenCollateral market's block number equals current block number */ if (aTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = controller.liquidateCalculateSeizeTokens(address(this), address(aTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(aTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(aTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = aTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(aTokenCollateral), seizeTokens); /* We call the defense hook */ controller.liquidateBorrowVerify(address(this), address(aTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another aToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed aToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of aTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another AToken. * Its absolutely critical to use msg.sender as the seizer aToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed aToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of aTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = controller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_CONTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ controller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new controller for the market * @dev Admin function to set a new controller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setController(ControllerInterface newController) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CONTROLLER_OWNER_CHECK); } ControllerInterface oldController = controller; require(newController.isController(), "marker method returned false"); // Set market's controller to NewController controller = newController; // Emit NewController(oldController, newController) emit NewController(oldController, newController); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The aToken must handle variations between ERC-20 and ETH underlying. * On success, the aToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } pragma solidity ^0.5.16; contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a aToken asset * @param aToken The aToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(AToken aToken) external view returns (uint); } pragma solidity ^0.5.16; contract ControllerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of ProxyController */ address public controllerImplementation; /** * @notice Pending brains of ProxyController */ address public pendingControllerImplementation; } contract ControllerV1Storage is ControllerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => AToken[]) public accountAssets; } contract ControllerV2Storage is ControllerV1Storage { struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives ARTEM bool isArtem; } /** * @notice Official mapping of aTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ControllerV3Storage is ControllerV2Storage { struct ArtemMarketState { /// @notice The market's last updated artemBorrowIndex or artemSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets AToken[] public allMarkets; /// @notice The rate at which the flywheel distributes ARTEM, per block uint public artemRate; /// @notice The portion of artemRate that each market currently receives mapping(address => uint) public artemSpeeds; /// @notice The ARTEM market supply state for each market mapping(address => ArtemMarketState) public artemSupplyState; /// @notice The ARTEM market borrow state for each market mapping(address => ArtemMarketState) public artemBorrowState; /// @notice The ARTEM borrow index for each market for each supplier as of the last time they accrued ARTEM mapping(address => mapping(address => uint)) public artemSupplierIndex; /// @notice The ARTEM borrow index for each market for each borrower as of the last time they accrued ARTEM mapping(address => mapping(address => uint)) public artemBorrowerIndex; /// @notice The ARTEM accrued but not yet transferred to each user mapping(address => uint) public artemAccrued; } contract ProxyController is ControllerAdminStorage, ArtemcontrollerErrorReporter { /** * @notice Emitted when pendingControllerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingControllerImplementation is accepted, which means controller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingControllerImplementation; pendingControllerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of controller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingControllerImplementation || pendingControllerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = controllerImplementation; address oldPendingImplementation = pendingControllerImplementation; controllerImplementation = pendingControllerImplementation; pendingControllerImplementation = address(0); emit NewImplementation(oldImplementation, controllerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () payable external { // delegate all other functions to current implementation (bool success, ) = controllerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } pragma experimental ABIEncoderV2; contract Artem { /// @notice EIP-20 token name for this token string public constant name = "Artem"; /// @notice EIP-20 token symbol for this token string public constant symbol = "ARTT"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 4204800e18; // 4.2 million Artem /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Artem token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Artem::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Artem::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Artem::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Artem::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Artem::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Artem::delegateBySig: invalid nonce"); require(now <= expiry, "Artem::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Artem::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Artem::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Artem::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Artem::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Artem::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Artem::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Artem::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Artem::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity ^0.5.16; contract Controller is ControllerV3Storage, ControllerInterface, ArtemcontrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(AToken aToken); /// @notice Emitted when an account enters a market event MarketEntered(AToken aToken, address account); /// @notice Emitted when an account exits a market event MarketExited(AToken aToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(AToken aToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(AToken aToken, string action, bool pauseState); /// @notice Emitted when market artemed status is changed event MarketArtemed(AToken aToken, bool isArtem); /// @notice Emitted when ARTT rate is changed event NewArtemRate(uint oldArtemRate, uint newArtemRate); /// @notice Emitted when a new ARTT speed is calculated for a market event ArtemSpeedUpdated(AToken indexed aToken, uint newSpeed); /// @notice Emitted when ARTT is distributed to a supplier event DistributedSupplierArtem(AToken indexed aToken, address indexed supplier, uint artemDelta, uint artemSupplyIndex); /// @notice Emitted when ARTT is distributed to a borrower event DistributedBorrowerArtem(AToken indexed aToken, address indexed borrower, uint artemDelta, uint artemBorrowIndex); /// @notice The threshold above which the flywheel transfers ARTEM, in wei uint public constant artemClaimThreshold = 0.001e18; /// @notice The initial ARTEM index for a market uint224 public constant artemInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (AToken[] memory) { AToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param aToken The aToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, AToken aToken) external view returns (bool) { return markets[address(aToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param aTokens The list of addresses of the aToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory aTokens) public returns (uint[] memory) { uint len = aTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { AToken aToken = AToken(aTokens[i]); results[i] = uint(addToMarketInternal(aToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param aToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(AToken aToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(aToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(aToken); emit MarketEntered(aToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param aTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address aTokenAddress) external returns (uint) { AToken aToken = AToken(aTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the aToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = aToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(aTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(aToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set aToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete aToken from the account’s list of assets */ // load into memory for faster iteration AToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == aToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 AToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(aToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param aToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address aToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[aToken], "mint is paused"); // Shh - currently unused //minter; //mintAmount; if (!markets[aToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateArtemSupplyIndex(aToken); distributeSupplierArtem(aToken, minter, false); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param aToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address aToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused aToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param aToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of aTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address aToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(aToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateArtemSupplyIndex(aToken); distributeSupplierArtem(aToken, redeemer, false); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address aToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[aToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[aToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, AToken(aToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param aToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address aToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused aToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param aToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address aToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[aToken], "borrow is paused"); if (!markets[aToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[aToken].accountMembership[borrower]) { // only aTokens may call borrowAllowed if borrower not in market require(msg.sender == aToken, "sender must be aToken"); // attempt to add borrower to the market Error err = addToMarketInternal(AToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[aToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(AToken(aToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, AToken(aToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: AToken(aToken).borrowIndex()}); updateArtemBorrowIndex(aToken, borrowIndex); distributeBorrowerArtem(aToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param aToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address aToken, address borrower, uint borrowAmount) external { // Shh - currently unused aToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param aToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address aToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[aToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: AToken(aToken).borrowIndex()}); updateArtemBorrowIndex(aToken, borrowIndex); distributeBorrowerArtem(aToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param aToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address aToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused aToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param aTokenBorrowed Asset which was borrowed by the borrower * @param aTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address aTokenBorrowed, address aTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[aTokenBorrowed].isListed || !markets[aTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = AToken(aTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param aTokenBorrowed Asset which was borrowed by the borrower * @param aTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address aTokenBorrowed, address aTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused aTokenBorrowed; aTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param aTokenCollateral Asset which was used as collateral and will be seized * @param aTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address aTokenCollateral, address aTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[aTokenCollateral].isListed || !markets[aTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (AToken(aTokenCollateral).controller() != AToken(aTokenBorrowed).controller()) { return uint(Error.CONTROLLER_MISMATCH); } // Keep the flywheel moving updateArtemSupplyIndex(aTokenCollateral); distributeSupplierArtem(aTokenCollateral, borrower, false); distributeSupplierArtem(aTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param aTokenCollateral Asset which was used as collateral and will be seized * @param aTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address aTokenCollateral, address aTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused aTokenCollateral; aTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param aToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of aTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address aToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(aToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateArtemSupplyIndex(aToken); distributeSupplierArtem(aToken, src, false); distributeSupplierArtem(aToken, dst, false); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param aToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of aTokens to transfer */ function transferVerify(address aToken, address src, address dst, uint transferTokens) external { // Shh - currently unused aToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `aTokenBalance` is the number of aTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint aTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, AToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, AToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param aTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address aTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, AToken(aTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param aTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral aToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, AToken aTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in AToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { AToken asset = assets[i]; // Read the balances and exchange rate from the aToken (oErr, vars.aTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * aTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.aTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with aTokenModify if (asset == aTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in aToken.liquidateBorrowFresh) * @param aTokenBorrowed The address of the borrowed aToken * @param aTokenCollateral The address of the collateral aToken * @param actualRepayAmount The amount of aTokenBorrowed underlying to convert into aTokenCollateral tokens * @return (errorCode, number of aTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address aTokenBorrowed, address aTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(AToken(aTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(AToken(aTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = AToken(aTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the controller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the controller PriceOracle oldOracle = oracle; // Set controller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param aToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(AToken aToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(aToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(aToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(aToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param aToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(AToken aToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(aToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } aToken.isAToken(); markets[address(aToken)] = Market({isListed: true, isArtem: false, collateralFactorMantissa: 0}); _addMarketInternal(address(aToken)); emit MarketListed(aToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address aToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != AToken(aToken), "market already added"); } allMarkets.push(AToken(aToken)); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(AToken aToken, bool state) public returns (bool) { require(markets[address(aToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(aToken)] = state; emit ActionPaused(aToken, "Mint", state); return state; } function _setBorrowPaused(AToken aToken, bool state) public returns (bool) { require(markets[address(aToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(aToken)] = state; emit ActionPaused(aToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(ProxyController proxycontroller) public { require(msg.sender == proxycontroller.admin(), "only proxycontroller admin can change brains"); require(proxycontroller._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == controllerImplementation; } /*** Artem Distribution ***/ /** * @notice Recalculate and update ARTEM speeds for all ARTEM markets */ function refreshArtemSpeeds() public { require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds"); refreshArtemSpeedsInternal(); } function refreshArtemSpeedsInternal() internal { AToken[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { AToken aToken = allMarkets_[i]; Exp memory borrowIndex = Exp({mantissa: aToken.borrowIndex()}); updateArtemSupplyIndex(address(aToken)); updateArtemBorrowIndex(address(aToken), borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets_.length); for (uint i = 0; i < allMarkets_.length; i++) { AToken aToken = allMarkets_[i]; if (markets[address(aToken)].isArtem) { Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(aToken)}); Exp memory utility = mul_(assetPrice, aToken.totalBorrows()); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (uint i = 0; i < allMarkets_.length; i++) { AToken aToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(artemRate, div_(utilities[i], totalUtility)) : 0; artemSpeeds[address(aToken)] = newSpeed; emit ArtemSpeedUpdated(aToken, newSpeed); } } /** * @notice Accrue ARTEM to the market by updating the supply index * @param aToken The market whose supply index to update */ function updateArtemSupplyIndex(address aToken) internal { ArtemMarketState storage supplyState = artemSupplyState[aToken]; uint supplySpeed = artemSpeeds[aToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = AToken(aToken).totalSupply(); uint artemAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(artemAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); artemSupplyState[aToken] = ArtemMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue ARTEM to the market by updating the borrow index * @param aToken The market whose borrow index to update */ function updateArtemBorrowIndex(address aToken, Exp memory marketBorrowIndex) internal { ArtemMarketState storage borrowState = artemBorrowState[aToken]; uint borrowSpeed = artemSpeeds[aToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(AToken(aToken).totalBorrows(), marketBorrowIndex); uint artemAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(artemAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); artemBorrowState[aToken] = ArtemMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate ARTEM accrued by a supplier and possibly transfer it to them * @param aToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute ARTEM to */ function distributeSupplierArtem(address aToken, address supplier, bool distributeAll) internal { ArtemMarketState storage supplyState = artemSupplyState[aToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: artemSupplierIndex[aToken][supplier]}); artemSupplierIndex[aToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = artemInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = AToken(aToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(artemAccrued[supplier], supplierDelta); artemAccrued[supplier] = transferArtem(supplier, supplierAccrued, distributeAll ? 0 : artemClaimThreshold); emit DistributedSupplierArtem(AToken(aToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate ARTEM accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param aToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute ARTEM to */ function distributeBorrowerArtem(address aToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal { ArtemMarketState storage borrowState = artemBorrowState[aToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: artemBorrowerIndex[aToken][borrower]}); artemBorrowerIndex[aToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(AToken(aToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(artemAccrued[borrower], borrowerDelta); artemAccrued[borrower] = transferArtem(borrower, borrowerAccrued, distributeAll ? 0 : artemClaimThreshold); emit DistributedBorrowerArtem(AToken(aToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Transfer ARTEM to the user, if they are above the threshold * @dev Note: If there is not enough ARTEM, we do not perform the transfer all. * @param user The address of the user to transfer ARTEM to * @param userAccrued The amount of ARTEM to (possibly) transfer * @return The amount of ARTEM which was NOT transferred to the user */ function transferArtem(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { Artem artem = Artem(getArtemAddress()); uint artemRemaining = artem.balanceOf(address(this)); if (userAccrued <= artemRemaining) { artem.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the artem accrued by holder in all markets * @param holder The address to claim ARTEM for */ function claimArtem(address holder) public { return claimArtem(holder, allMarkets); } /** * @notice Claim all the artem accrued by holder in the specified markets * @param holder The address to claim ARTEM for * @param aTokens The list of markets to claim ARTEM in */ function claimArtem(address holder, AToken[] memory aTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimArtem(holders, aTokens, true, true); } /** * @notice Claim all artem accrued by the holders * @param holders The addresses to claim ARTEM for * @param aTokens The list of markets to claim ARTEM in * @param borrowers Whether or not to claim ARTEM earned by borrowing * @param suppliers Whether or not to claim ARTEM earned by supplying */ function claimArtem(address[] memory holders, AToken[] memory aTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < aTokens.length; i++) { AToken aToken = aTokens[i]; require(markets[address(aToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: aToken.borrowIndex()}); updateArtemBorrowIndex(address(aToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerArtem(address(aToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateArtemSupplyIndex(address(aToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierArtem(address(aToken), holders[j], true); } } } } /*** Artem Distribution Admin ***/ /** * @notice Set the amount of ARTEM distributed per block * @param artemRate_ The amount of ARTEM wei per block to distribute */ function _setArtemRate(uint artemRate_) public { require(adminOrInitializing(), "only admin can change artem rate"); uint oldRate = artemRate; artemRate = artemRate_; emit NewArtemRate(oldRate, artemRate_); refreshArtemSpeedsInternal(); } /** * @notice Add markets to artemMarkets, allowing them to earn ARTEM in the flywheel * @param aTokens The addresses of the markets to add */ function _addArtemMarkets(address[] memory aTokens) public { require(adminOrInitializing(), "only admin can add artem market"); for (uint i = 0; i < aTokens.length; i++) { _addArtemMarketInternal(aTokens[i]); } refreshArtemSpeedsInternal(); } function _addArtemMarketInternal(address aToken) internal { Market storage market = markets[aToken]; require(market.isListed == true, "artem market is not listed"); require(market.isArtem == false, "artem market already added"); market.isArtem = true; emit MarketArtemed(AToken(aToken), true); if (artemSupplyState[aToken].index == 0 && artemSupplyState[aToken].block == 0) { artemSupplyState[aToken] = ArtemMarketState({ index: artemInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (artemBorrowState[aToken].index == 0 && artemBorrowState[aToken].block == 0) { artemBorrowState[aToken] = ArtemMarketState({ index: artemInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } /** * @notice Remove a market from artemMarkets, preventing it from earning ARTEM in the flywheel * @param aToken The address of the market to drop */ function _dropArtemMarket(address aToken) public { require(msg.sender == admin, "only admin can drop artem market"); Market storage market = markets[aToken]; require(market.isArtem == true, "market is not a artem market"); market.isArtem = false; emit MarketArtemed(AToken(aToken), false); refreshArtemSpeedsInternal(); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (AToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the Artem token * @return The address of Artem */ function getArtemAddress() public view returns (address) { return 0x77dF79539083DCd4a8898dbA296d899aFef20067; } }
* @notice Checks if the account should be allowed to repay a borrow in the given market @param aToken The market to verify the repay against @param payer The account which would repay the asset @param borrower The account which would borrowed the asset @param repayAmount The amount of the underlying asset the account would repay @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)/ Shh - currently unused
function repayBorrowAllowed( address aToken, address payer, address borrower, uint repayAmount) external returns (uint) { payer; borrower; repayAmount; if (!markets[aToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } updateArtemBorrowIndex(aToken, borrowIndex); distributeBorrowerArtem(aToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); }
7,696,077
[ 1, 4081, 309, 326, 2236, 1410, 506, 2935, 358, 2071, 528, 279, 29759, 316, 326, 864, 13667, 225, 279, 1345, 1021, 13667, 358, 3929, 326, 2071, 528, 5314, 225, 293, 1773, 1021, 2236, 1492, 4102, 2071, 528, 326, 3310, 225, 29759, 264, 1021, 2236, 1492, 4102, 29759, 329, 326, 3310, 225, 2071, 528, 6275, 1021, 3844, 434, 326, 6808, 3310, 326, 2236, 4102, 2071, 528, 327, 374, 309, 326, 2071, 528, 353, 2935, 16, 3541, 279, 23161, 17, 556, 14886, 555, 981, 261, 9704, 1068, 13289, 18, 18281, 13176, 2638, 76, 300, 4551, 10197, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2071, 528, 38, 15318, 5042, 12, 203, 3639, 1758, 279, 1345, 16, 203, 3639, 1758, 293, 1773, 16, 203, 3639, 1758, 29759, 264, 16, 203, 3639, 2254, 2071, 528, 6275, 13, 3903, 1135, 261, 11890, 13, 288, 203, 3639, 293, 1773, 31, 203, 3639, 29759, 264, 31, 203, 3639, 2071, 528, 6275, 31, 203, 203, 3639, 309, 16051, 3355, 2413, 63, 69, 1345, 8009, 291, 682, 329, 13, 288, 203, 5411, 327, 2254, 12, 668, 18, 12693, 1584, 67, 4400, 67, 7085, 2056, 1769, 203, 3639, 289, 203, 203, 3639, 1089, 686, 874, 38, 15318, 1016, 12, 69, 1345, 16, 29759, 1016, 1769, 203, 3639, 25722, 38, 15318, 264, 686, 874, 12, 69, 1345, 16, 29759, 264, 16, 29759, 1016, 16, 629, 1769, 203, 203, 3639, 327, 2254, 12, 668, 18, 3417, 67, 3589, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0), ""); require(!has(role, account), ""); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0), ""); require(has(role, account), ""); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), ""); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender), ""); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract FCS is ERC20Interface, Owned, SafeMath, MinterRole { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; address private _owner; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "FCS"; name = "Five Color Stone"; decimals = 18; _totalSupply = 2000000000000000000000000000; _owner = 0xa45760889D1c27804Dc6D6B89D4095e8Eb99ab72; balances[_owner] = _totalSupply; emit Transfer(address(0), _owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return safeSub(_totalSupply, balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ // function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { // allowed[msg.sender][spender] = tokens; // emit Approval(msg.sender, spender, tokens); // ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); // return true; // } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } /** * @dev Burns a specific amount of tokens from the owner * @param value uint256 The amount of token to be burned */ function burnOwner(uint256 value) public onlyOwner { require(msg.sender != address(0), ""); _totalSupply = safeSub(_totalSupply, value); balances[_owner] = safeSub(balances[_owner], value); emit Transfer(_owner, address(0), value); } /** * @dev Function to mint tokens * @param account The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address account, uint256 value) public onlyMinter returns (bool) { require(account != address(0), ""); require(account != _owner, ""); // _totalSupply = safeAdd(_totalSupply, value); balances[account] = safeAdd(balances[account], value); balances[_owner] = safeSub(balances[_owner], value); emit Transfer(_owner, account, value); return true; } /** * @dev Function to mint tokens * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mintOwner(uint256 value) public onlyMinter returns (bool) { require(msg.sender != address(0), ""); require(msg.sender == _owner, ""); _totalSupply = safeAdd(_totalSupply, value); balances[_owner] = safeAdd(balances[_owner], value); emit Transfer(address(0), _owner, value); return true; } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0), ""); require(account != _owner, ""); balances[account] = safeSub(balances[account], value); balances[_owner] = safeAdd(balances[_owner], value); emit Transfer(account, _owner, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { allowed[account][msg.sender] = safeSub(allowed[account][msg.sender], value); _burn(account, value); emit Approval(account, msg.sender, allowed[account][msg.sender]); } }
* @dev Function to mint tokens @param account The address that will receive the minted tokens. @param value The amount of tokens to mint. @return A boolean that indicates if the operation was successful./ _totalSupply = safeAdd(_totalSupply, value);
function mint(address account, uint256 value) public onlyMinter returns (bool) { require(account != address(0), ""); require(account != _owner, ""); balances[account] = safeAdd(balances[account], value); balances[_owner] = safeSub(balances[_owner], value); emit Transfer(_owner, account, value); return true; }
13,139,702
[ 1, 2083, 358, 312, 474, 2430, 225, 2236, 1021, 1758, 716, 903, 6798, 326, 312, 474, 329, 2430, 18, 225, 460, 1021, 3844, 434, 2430, 358, 312, 474, 18, 327, 432, 1250, 716, 8527, 309, 326, 1674, 1703, 6873, 18, 19, 389, 4963, 3088, 1283, 273, 4183, 986, 24899, 4963, 3088, 1283, 16, 460, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 2236, 16, 2254, 5034, 460, 13, 1071, 1338, 49, 2761, 1135, 261, 6430, 13, 288, 203, 540, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 1408, 1769, 203, 3639, 2583, 12, 4631, 480, 389, 8443, 16, 1408, 1769, 203, 203, 203, 3639, 324, 26488, 63, 4631, 65, 273, 4183, 986, 12, 70, 26488, 63, 4631, 6487, 460, 1769, 203, 3639, 324, 26488, 63, 67, 8443, 65, 273, 4183, 1676, 12, 70, 26488, 63, 67, 8443, 6487, 460, 1769, 203, 3639, 3626, 12279, 24899, 8443, 16, 2236, 16, 460, 1769, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xa6d8C77FFf3CDcc43804275aD9997b603a7817c5/sources/src/ETHButtonswapRouter.sol
* @dev Only accepts ETH via fallback from the WETH contract/
receive() external payable { if (msg.sender != WETH) { revert NonWETHSender(); } }
3,642,058
[ 1, 3386, 8104, 512, 2455, 3970, 5922, 628, 326, 678, 1584, 44, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6798, 1435, 3903, 8843, 429, 288, 203, 3639, 309, 261, 3576, 18, 15330, 480, 678, 1584, 44, 13, 288, 203, 5411, 15226, 3858, 59, 1584, 44, 12021, 5621, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1313161554/0x98E8d4b4F53FA2a2d1b9C651AF919Fc839eE4c1a/sources/contracts/Comptroller.sol
closeFactorMantissa must be strictly greater than this value closeFactorMantissa must not exceed this value No collateralFactorMantissa may exceed this value
{ event MarketListed(CToken cToken); event MarketEntered(CToken cToken, address account); event MarketExited(CToken cToken, address account); event NewCloseFactor( uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa ); event NewCollateralFactor( CToken cToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa ); event NewLiquidationIncentive( uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa ); event NewRewardDistributor( address oldRewardDistributor, address newRewardDistributor ); event NewPriceOracle( PriceOracle oldPriceOracle, PriceOracle newPriceOracle ); event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); event ActionPaused(string action, bool pauseState); event ActionPaused(CToken cToken, string action, bool pauseState); event CompBorrowSpeedUpdated(CToken indexed cToken, uint256 newSpeed); event CompSupplySpeedUpdated(CToken indexed cToken, uint256 newSpeed); event ContributorCompSpeedUpdated( address indexed contributor, uint256 newSpeed ); event DistributedSupplierComp( CToken indexed cToken, address indexed supplier, uint256 compDelta, uint256 compSupplyIndex ); event DistributedBorrowerComp( CToken indexed cToken, address indexed borrower, uint256 compDelta, uint256 compBorrowIndex ); event NewBorrowCap(CToken indexed cToken, uint256 newBorrowCap); event NewBorrowCapGuardian( address oldBorrowCapGuardian, address newBorrowCapGuardian ); event CompGranted(address recipient, uint256 amount); event CompAccruedAdjusted( address indexed user, uint256 oldCompAccrued, uint256 newCompAccrued ); event CompReceivableUpdated( address indexed user, uint256 oldCompReceivable, uint256 newCompReceivable ); uint224 public constant compInitialIndex = 1e36; contract Comptroller is constructor() public { admin = msg.sender; } function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } function enterMarkets(address[] memory cTokens) public returns (uint256[] memory) { uint256 len = cTokens.length; uint256[] memory results = new uint256[](len); for (uint256 i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint256(addToMarketInternal(cToken, msg.sender)); } return results; } function enterMarkets(address[] memory cTokens) public returns (uint256[] memory) { uint256 len = cTokens.length; uint256[] memory results = new uint256[](len); for (uint256 i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint256(addToMarketInternal(cToken, msg.sender)); } return results; } function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { return Error.NO_ERROR; } accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { return Error.NO_ERROR; } accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { return Error.NO_ERROR; } accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } marketToJoin.accountMembership[borrower] = true; function exitMarket(address cTokenAddress) external returns (uint256) { CToken cToken = CToken(cTokenAddress); (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken .getAccountSnapshot(msg.sender); if (amountOwed != 0) { return fail( Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED ); } cTokenAddress, msg.sender, tokensHeld ); if (allowed != 0) { return failOpaque( Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed ); } Market storage marketToExit = markets[address(cToken)]; if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint256(Error.NO_ERROR); } function exitMarket(address cTokenAddress) external returns (uint256) { CToken cToken = CToken(cTokenAddress); (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken .getAccountSnapshot(msg.sender); if (amountOwed != 0) { return fail( Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED ); } cTokenAddress, msg.sender, tokensHeld ); if (allowed != 0) { return failOpaque( Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed ); } Market storage marketToExit = markets[address(cToken)]; if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint256(Error.NO_ERROR); } uint256 allowed = redeemAllowedInternal( function exitMarket(address cTokenAddress) external returns (uint256) { CToken cToken = CToken(cTokenAddress); (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken .getAccountSnapshot(msg.sender); if (amountOwed != 0) { return fail( Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED ); } cTokenAddress, msg.sender, tokensHeld ); if (allowed != 0) { return failOpaque( Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed ); } Market storage marketToExit = markets[address(cToken)]; if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint256(Error.NO_ERROR); } function exitMarket(address cTokenAddress) external returns (uint256) { CToken cToken = CToken(cTokenAddress); (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken .getAccountSnapshot(msg.sender); if (amountOwed != 0) { return fail( Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED ); } cTokenAddress, msg.sender, tokensHeld ); if (allowed != 0) { return failOpaque( Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed ); } Market storage marketToExit = markets[address(cToken)]; if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint256(Error.NO_ERROR); } delete marketToExit.accountMembership[msg.sender]; CToken[] memory userAssetList = accountAssets[msg.sender]; function exitMarket(address cTokenAddress) external returns (uint256) { CToken cToken = CToken(cTokenAddress); (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken .getAccountSnapshot(msg.sender); if (amountOwed != 0) { return fail( Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED ); } cTokenAddress, msg.sender, tokensHeld ); if (allowed != 0) { return failOpaque( Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed ); } Market storage marketToExit = markets[address(cToken)]; if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint256(Error.NO_ERROR); } function exitMarket(address cTokenAddress) external returns (uint256) { CToken cToken = CToken(cTokenAddress); (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken .getAccountSnapshot(msg.sender); if (amountOwed != 0) { return fail( Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED ); } cTokenAddress, msg.sender, tokensHeld ); if (allowed != 0) { return failOpaque( Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed ); } Market storage marketToExit = markets[address(cToken)]; if (!marketToExit.accountMembership[msg.sender]) { return uint256(Error.NO_ERROR); } uint256 len = userAssetList.length; uint256 assetIndex = len; for (uint256 i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint256(Error.NO_ERROR); } assert(assetIndex < len); CToken[] storage storedList = accountAssets[msg.sender]; function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256) { require(!mintGuardianPaused[cToken], "mint is paused"); minter; mintAmount; if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } .updateAndDistributeSupplierRewardsForToken(cToken, minter); return uint256(Error.NO_ERROR); } function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256) { require(!mintGuardianPaused[cToken], "mint is paused"); minter; mintAmount; if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } .updateAndDistributeSupplierRewardsForToken(cToken, minter); return uint256(Error.NO_ERROR); } RewardDistributor(rewardDistributor) function mintVerify( address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens ) external { cToken; minter; actualMintAmount; mintTokens; if (false) { maxAssets = maxAssets; } } function mintVerify( address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens ) external { cToken; minter; actualMintAmount; mintTokens; if (false) { maxAssets = maxAssets; } } function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256) { uint256 allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint256(Error.NO_ERROR)) { return allowed; } .updateAndDistributeSupplierRewardsForToken(cToken, redeemer); return uint256(Error.NO_ERROR); } function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256) { uint256 allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint256(Error.NO_ERROR)) { return allowed; } .updateAndDistributeSupplierRewardsForToken(cToken, redeemer); return uint256(Error.NO_ERROR); } RewardDistributor(rewardDistributor) function redeemAllowedInternal( address cToken, address redeemer, uint256 redeemTokens ) internal view returns (uint256) { if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[redeemer]) { return uint256(Error.NO_ERROR); } Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( redeemer, CToken(cToken), redeemTokens, 0 ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } return uint256(Error.NO_ERROR); } function redeemAllowedInternal( address cToken, address redeemer, uint256 redeemTokens ) internal view returns (uint256) { if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[redeemer]) { return uint256(Error.NO_ERROR); } Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( redeemer, CToken(cToken), redeemTokens, 0 ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } return uint256(Error.NO_ERROR); } function redeemAllowedInternal( address cToken, address redeemer, uint256 redeemTokens ) internal view returns (uint256) { if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[redeemer]) { return uint256(Error.NO_ERROR); } Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( redeemer, CToken(cToken), redeemTokens, 0 ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } return uint256(Error.NO_ERROR); } ( function redeemAllowedInternal( address cToken, address redeemer, uint256 redeemTokens ) internal view returns (uint256) { if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[redeemer]) { return uint256(Error.NO_ERROR); } Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( redeemer, CToken(cToken), redeemTokens, 0 ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } return uint256(Error.NO_ERROR); } function redeemAllowedInternal( address cToken, address redeemer, uint256 redeemTokens ) internal view returns (uint256) { if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[redeemer]) { return uint256(Error.NO_ERROR); } Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( redeemer, CToken(cToken), redeemTokens, 0 ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } return uint256(Error.NO_ERROR); } function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external { cToken; redeemer; if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external { cToken; redeemer; if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { require(msg.sender == cToken, "sender must be cToken"); Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint256(err); } } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint256(Error.PRICE_ERROR); } uint256 borrowCap = borrowCaps[cToken]; if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } ( Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } RewardDistributor(rewardDistributor) .updateAndDistributeBorrowerRewardsForToken( cToken, borrower, borrowIndex ); return uint256(Error.NO_ERROR); } function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { require(msg.sender == cToken, "sender must be cToken"); Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint256(err); } } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint256(Error.PRICE_ERROR); } uint256 borrowCap = borrowCaps[cToken]; if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } ( Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } RewardDistributor(rewardDistributor) .updateAndDistributeBorrowerRewardsForToken( cToken, borrower, borrowIndex ); return uint256(Error.NO_ERROR); } function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { require(msg.sender == cToken, "sender must be cToken"); Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint256(err); } } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint256(Error.PRICE_ERROR); } uint256 borrowCap = borrowCaps[cToken]; if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } ( Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } RewardDistributor(rewardDistributor) .updateAndDistributeBorrowerRewardsForToken( cToken, borrower, borrowIndex ); return uint256(Error.NO_ERROR); } function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { require(msg.sender == cToken, "sender must be cToken"); Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint256(err); } } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint256(Error.PRICE_ERROR); } uint256 borrowCap = borrowCaps[cToken]; if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } ( Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } RewardDistributor(rewardDistributor) .updateAndDistributeBorrowerRewardsForToken( cToken, borrower, borrowIndex ); return uint256(Error.NO_ERROR); } assert(markets[cToken].accountMembership[borrower]); function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { require(msg.sender == cToken, "sender must be cToken"); Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint256(err); } } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint256(Error.PRICE_ERROR); } uint256 borrowCap = borrowCaps[cToken]; if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } ( Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } RewardDistributor(rewardDistributor) .updateAndDistributeBorrowerRewardsForToken( cToken, borrower, borrowIndex ); return uint256(Error.NO_ERROR); } function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { require(msg.sender == cToken, "sender must be cToken"); Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint256(err); } } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint256(Error.PRICE_ERROR); } uint256 borrowCap = borrowCaps[cToken]; if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } ( Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } RewardDistributor(rewardDistributor) .updateAndDistributeBorrowerRewardsForToken( cToken, borrower, borrowIndex ); return uint256(Error.NO_ERROR); } function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { require(msg.sender == cToken, "sender must be cToken"); Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint256(err); } } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint256(Error.PRICE_ERROR); } uint256 borrowCap = borrowCaps[cToken]; if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } ( Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } RewardDistributor(rewardDistributor) .updateAndDistributeBorrowerRewardsForToken( cToken, borrower, borrowIndex ); return uint256(Error.NO_ERROR); } function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256) { require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { require(msg.sender == cToken, "sender must be cToken"); Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint256(err); } } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint256(Error.PRICE_ERROR); } uint256 borrowCap = borrowCaps[cToken]; if (borrowCap != 0) { uint256 totalBorrows = CToken(cToken).totalBorrows(); uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } ( Error err, , uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall > 0) { return uint256(Error.INSUFFICIENT_LIQUIDITY); } RewardDistributor(rewardDistributor) .updateAndDistributeBorrowerRewardsForToken( cToken, borrower, borrowIndex ); return uint256(Error.NO_ERROR); } Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external { cToken; borrower; borrowAmount; if (false) { maxAssets = maxAssets; } } function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external { cToken; borrower; borrowAmount; if (false) { maxAssets = maxAssets; } } function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256) { payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } RewardDistributor(rewardDistributor) .updateAndDistributeBorrowerRewardsForToken( cToken, borrower, borrowIndex ); return uint256(Error.NO_ERROR); } function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256) { payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint256(Error.MARKET_NOT_LISTED); } RewardDistributor(rewardDistributor) .updateAndDistributeBorrowerRewardsForToken( cToken, borrower, borrowIndex ); return uint256(Error.NO_ERROR); } Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()}); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 actualRepayAmount, uint256 borrowerIndex ) external { cToken; payer; borrower; actualRepayAmount; borrowerIndex; if (false) { maxAssets = maxAssets; } } function repayBorrowVerify( address cToken, address payer, address borrower, uint256 actualRepayAmount, uint256 borrowerIndex ) external { cToken; payer; borrower; actualRepayAmount; borrowerIndex; if (false) { maxAssets = maxAssets; } } function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { liquidator; if ( !markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed ) { return uint256(Error.MARKET_NOT_LISTED); } uint256 borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored( borrower ); if (isDeprecated(CToken(cTokenBorrowed))) { require( borrowBalance >= repayAmount, "Can not repay more than the total borrow" ); (Error err, , uint256 shortfall) = getAccountLiquidityInternal( borrower ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall == 0) { return uint256(Error.INSUFFICIENT_SHORTFALL); } borrowBalance ); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } } return uint256(Error.NO_ERROR); } function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { liquidator; if ( !markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed ) { return uint256(Error.MARKET_NOT_LISTED); } uint256 borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored( borrower ); if (isDeprecated(CToken(cTokenBorrowed))) { require( borrowBalance >= repayAmount, "Can not repay more than the total borrow" ); (Error err, , uint256 shortfall) = getAccountLiquidityInternal( borrower ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall == 0) { return uint256(Error.INSUFFICIENT_SHORTFALL); } borrowBalance ); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } } return uint256(Error.NO_ERROR); } function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { liquidator; if ( !markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed ) { return uint256(Error.MARKET_NOT_LISTED); } uint256 borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored( borrower ); if (isDeprecated(CToken(cTokenBorrowed))) { require( borrowBalance >= repayAmount, "Can not repay more than the total borrow" ); (Error err, , uint256 shortfall) = getAccountLiquidityInternal( borrower ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall == 0) { return uint256(Error.INSUFFICIENT_SHORTFALL); } borrowBalance ); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } } return uint256(Error.NO_ERROR); } } else { function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { liquidator; if ( !markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed ) { return uint256(Error.MARKET_NOT_LISTED); } uint256 borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored( borrower ); if (isDeprecated(CToken(cTokenBorrowed))) { require( borrowBalance >= repayAmount, "Can not repay more than the total borrow" ); (Error err, , uint256 shortfall) = getAccountLiquidityInternal( borrower ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall == 0) { return uint256(Error.INSUFFICIENT_SHORTFALL); } borrowBalance ); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } } return uint256(Error.NO_ERROR); } function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { liquidator; if ( !markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed ) { return uint256(Error.MARKET_NOT_LISTED); } uint256 borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored( borrower ); if (isDeprecated(CToken(cTokenBorrowed))) { require( borrowBalance >= repayAmount, "Can not repay more than the total borrow" ); (Error err, , uint256 shortfall) = getAccountLiquidityInternal( borrower ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall == 0) { return uint256(Error.INSUFFICIENT_SHORTFALL); } borrowBalance ); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } } return uint256(Error.NO_ERROR); } uint256 maxClose = mul_ScalarTruncate( Exp({mantissa: closeFactorMantissa}), function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256) { liquidator; if ( !markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed ) { return uint256(Error.MARKET_NOT_LISTED); } uint256 borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored( borrower ); if (isDeprecated(CToken(cTokenBorrowed))) { require( borrowBalance >= repayAmount, "Can not repay more than the total borrow" ); (Error err, , uint256 shortfall) = getAccountLiquidityInternal( borrower ); if (err != Error.NO_ERROR) { return uint256(err); } if (shortfall == 0) { return uint256(Error.INSUFFICIENT_SHORTFALL); } borrowBalance ); if (repayAmount > maxClose) { return uint256(Error.TOO_MUCH_REPAY); } } return uint256(Error.NO_ERROR); } function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 actualRepayAmount, uint256 seizeTokens ) external { cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; if (false) { maxAssets = maxAssets; } } function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 actualRepayAmount, uint256 seizeTokens ) external { cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; if (false) { maxAssets = maxAssets; } } function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256) { require(!seizeGuardianPaused, "seize is paused"); seizeTokens; if ( !markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed ) { return uint256(Error.MARKET_NOT_LISTED); } if ( CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller() ) { return uint256(Error.COMPTROLLER_MISMATCH); } return uint256(Error.NO_ERROR); } function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256) { require(!seizeGuardianPaused, "seize is paused"); seizeTokens; if ( !markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed ) { return uint256(Error.MARKET_NOT_LISTED); } if ( CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller() ) { return uint256(Error.COMPTROLLER_MISMATCH); } return uint256(Error.NO_ERROR); } function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256) { require(!seizeGuardianPaused, "seize is paused"); seizeTokens; if ( !markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed ) { return uint256(Error.MARKET_NOT_LISTED); } if ( CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller() ) { return uint256(Error.COMPTROLLER_MISMATCH); } return uint256(Error.NO_ERROR); } function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external { cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; if (false) { maxAssets = maxAssets; } } function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external { cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; if (false) { maxAssets = maxAssets; } } function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256) { require(!transferGuardianPaused, "transfer is paused"); uint256 allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint256(Error.NO_ERROR)) { return allowed; } .updateAndDistributeSupplierRewardsForToken(cToken, src); RewardDistributor(rewardDistributor) .updateAndDistributeSupplierRewardsForToken(cToken, dst); return uint256(Error.NO_ERROR); } function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256) { require(!transferGuardianPaused, "transfer is paused"); uint256 allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint256(Error.NO_ERROR)) { return allowed; } .updateAndDistributeSupplierRewardsForToken(cToken, src); RewardDistributor(rewardDistributor) .updateAndDistributeSupplierRewardsForToken(cToken, dst); return uint256(Error.NO_ERROR); } RewardDistributor(rewardDistributor) function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external { cToken; src; dst; transferTokens; if (false) { maxAssets = maxAssets; } } function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external { cToken; src; dst; transferTokens; if (false) { maxAssets = maxAssets; } } struct AccountLiquidityLocalVars { uint256 sumCollateral; uint256 sumBorrowPlusEffects; uint256 cTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } account liquidity in excess of collateral requirements, function getAccountLiquidity(address account) public view returns ( uint256, uint256, uint256 ) { ( Error err, uint256 liquidity, uint256 shortfall ) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint256(err), liquidity, shortfall); } account liquidity in excess of collateral requirements, function getAccountLiquidityInternal(address account) internal view returns ( Error, uint256, uint256 ) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } hypothetical account liquidity in excess of collateral requirements, function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) public view returns ( uint256, uint256, uint256 ) { ( Error err, uint256 liquidity, uint256 shortfall ) = getHypotheticalAccountLiquidityInternal( account, CToken(cTokenModify), redeemTokens, borrowAmount ); return (uint256(err), liquidity, shortfall); } hypothetical account liquidity in excess of collateral requirements, function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { uint256 oErr; CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; ( oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa ) = asset.getAccountSnapshot(account); if (oErr != 0) { return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({ mantissa: markets[address(asset)].collateralFactorMantissa }); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice ); vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral ); vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); if (asset == cTokenModify) { vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return ( Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0 ); return ( Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral ); } } function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { uint256 oErr; CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; ( oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa ) = asset.getAccountSnapshot(account); if (oErr != 0) { return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({ mantissa: markets[address(asset)].collateralFactorMantissa }); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice ); vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral ); vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); if (asset == cTokenModify) { vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return ( Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0 ); return ( Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral ); } } function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { uint256 oErr; CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; ( oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa ) = asset.getAccountSnapshot(account); if (oErr != 0) { return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({ mantissa: markets[address(asset)].collateralFactorMantissa }); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice ); vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral ); vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); if (asset == cTokenModify) { vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return ( Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0 ); return ( Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral ); } } function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { uint256 oErr; CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; ( oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa ) = asset.getAccountSnapshot(account); if (oErr != 0) { return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({ mantissa: markets[address(asset)].collateralFactorMantissa }); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice ); vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral ); vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); if (asset == cTokenModify) { vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return ( Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0 ); return ( Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral ); } } vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { uint256 oErr; CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; ( oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa ) = asset.getAccountSnapshot(account); if (oErr != 0) { return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({ mantissa: markets[address(asset)].collateralFactorMantissa }); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice ); vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral ); vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); if (asset == cTokenModify) { vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return ( Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0 ); return ( Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral ); } } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); vars.tokensToDenom = mul_( vars.sumCollateral = mul_ScalarTruncateAddUInt( vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { uint256 oErr; CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; ( oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa ) = asset.getAccountSnapshot(account); if (oErr != 0) { return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({ mantissa: markets[address(asset)].collateralFactorMantissa }); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice ); vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral ); vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); if (asset == cTokenModify) { vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return ( Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0 ); return ( Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral ); } } function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) internal view returns ( Error, uint256, uint256 ) { uint256 oErr; CToken[] memory assets = accountAssets[account]; for (uint256 i = 0; i < assets.length; i++) { CToken asset = assets[i]; ( oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa ) = asset.getAccountSnapshot(account); if (oErr != 0) { return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({ mantissa: markets[address(asset)].collateralFactorMantissa }); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice ); vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral ); vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); if (asset == cTokenModify) { vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return ( Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0 ); return ( Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral ); } } } else { function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256, uint256) { uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice( CToken(cTokenBorrowed) ); uint256 priceCollateralMantissa = oracle.getUnderlyingPrice( CToken(cTokenCollateral) ); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint256(Error.PRICE_ERROR), 0); } uint256 seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; numerator = mul_( ); denominator = mul_( ); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint256(Error.NO_ERROR), seizeTokens); } function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256, uint256) { uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice( CToken(cTokenBorrowed) ); uint256 priceCollateralMantissa = oracle.getUnderlyingPrice( CToken(cTokenCollateral) ); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint256(Error.PRICE_ERROR), 0); } uint256 seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; numerator = mul_( ); denominator = mul_( ); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint256(Error.NO_ERROR), seizeTokens); } uint256 exchangeRateMantissa = CToken(cTokenCollateral) Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}) Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}) function _setRewardDistributor(address payable newRewardDistributor) public returns (uint256) { if (msg.sender != admin) { return uint256(Error.UNAUTHORIZED); } (bool success, ) = newRewardDistributor.call.value(0)( abi.encodeWithSignature("initialize()", 0) ); if (!success) { return uint256(Error.REJECTION); } address oldRewardDistributor = rewardDistributor; rewardDistributor = newRewardDistributor; emit NewRewardDistributor(oldRewardDistributor, rewardDistributor); return uint256(Error.NO_ERROR); } function _setRewardDistributor(address payable newRewardDistributor) public returns (uint256) { if (msg.sender != admin) { return uint256(Error.UNAUTHORIZED); } (bool success, ) = newRewardDistributor.call.value(0)( abi.encodeWithSignature("initialize()", 0) ); if (!success) { return uint256(Error.REJECTION); } address oldRewardDistributor = rewardDistributor; rewardDistributor = newRewardDistributor; emit NewRewardDistributor(oldRewardDistributor, rewardDistributor); return uint256(Error.NO_ERROR); } function _setRewardDistributor(address payable newRewardDistributor) public returns (uint256) { if (msg.sender != admin) { return uint256(Error.UNAUTHORIZED); } (bool success, ) = newRewardDistributor.call.value(0)( abi.encodeWithSignature("initialize()", 0) ); if (!success) { return uint256(Error.REJECTION); } address oldRewardDistributor = rewardDistributor; rewardDistributor = newRewardDistributor; emit NewRewardDistributor(oldRewardDistributor, rewardDistributor); return uint256(Error.NO_ERROR); } function _setPriceOracle(PriceOracle newOracle) public returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK ); } return uint256(Error.NO_ERROR); } function _setPriceOracle(PriceOracle newOracle) public returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK ); } return uint256(Error.NO_ERROR); } PriceOracle oldOracle = oracle; oracle = newOracle; emit NewPriceOracle(oldOracle, newOracle); function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) { require(msg.sender == admin, "only admin can set close factor"); uint256 oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint256(Error.NO_ERROR); } function _setCollateralFactor( CToken cToken, uint256 newCollateralFactorMantissa ) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK ); } if (!market.isListed) { return fail( Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS ); } Exp memory newCollateralFactorExp = Exp({ mantissa: newCollateralFactorMantissa }); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail( Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION ); } newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0 ) { return fail( Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE ); } market.collateralFactorMantissa = newCollateralFactorMantissa; cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa ); return uint256(Error.NO_ERROR); } function _setCollateralFactor( CToken cToken, uint256 newCollateralFactorMantissa ) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK ); } if (!market.isListed) { return fail( Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS ); } Exp memory newCollateralFactorExp = Exp({ mantissa: newCollateralFactorMantissa }); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail( Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION ); } newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0 ) { return fail( Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE ); } market.collateralFactorMantissa = newCollateralFactorMantissa; cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa ); return uint256(Error.NO_ERROR); } Market storage market = markets[address(cToken)]; function _setCollateralFactor( CToken cToken, uint256 newCollateralFactorMantissa ) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK ); } if (!market.isListed) { return fail( Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS ); } Exp memory newCollateralFactorExp = Exp({ mantissa: newCollateralFactorMantissa }); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail( Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION ); } newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0 ) { return fail( Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE ); } market.collateralFactorMantissa = newCollateralFactorMantissa; cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa ); return uint256(Error.NO_ERROR); } function _setCollateralFactor( CToken cToken, uint256 newCollateralFactorMantissa ) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK ); } if (!market.isListed) { return fail( Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS ); } Exp memory newCollateralFactorExp = Exp({ mantissa: newCollateralFactorMantissa }); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail( Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION ); } newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0 ) { return fail( Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE ); } market.collateralFactorMantissa = newCollateralFactorMantissa; cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa ); return uint256(Error.NO_ERROR); } Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); function _setCollateralFactor( CToken cToken, uint256 newCollateralFactorMantissa ) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK ); } if (!market.isListed) { return fail( Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS ); } Exp memory newCollateralFactorExp = Exp({ mantissa: newCollateralFactorMantissa }); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail( Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION ); } newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0 ) { return fail( Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE ); } market.collateralFactorMantissa = newCollateralFactorMantissa; cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa ); return uint256(Error.NO_ERROR); } if ( function _setCollateralFactor( CToken cToken, uint256 newCollateralFactorMantissa ) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK ); } if (!market.isListed) { return fail( Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS ); } Exp memory newCollateralFactorExp = Exp({ mantissa: newCollateralFactorMantissa }); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail( Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION ); } newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0 ) { return fail( Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE ); } market.collateralFactorMantissa = newCollateralFactorMantissa; cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa ); return uint256(Error.NO_ERROR); } uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa; emit NewCollateralFactor( function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK ); } oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa ); return uint256(Error.NO_ERROR); } function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK ); } oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa ); return uint256(Error.NO_ERROR); } uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; emit NewLiquidationIncentive( function _supportMarket(CToken cToken) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK ); } if (markets[address(cToken)].isListed) { return fail( Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS ); } markets[address(cToken)] = Market({ isListed: true, isComped: false, collateralFactorMantissa: 0 }); _addMarketInternal(address(cToken)); _initializeMarket(address(cToken)); emit MarketListed(cToken); return uint256(Error.NO_ERROR); } function _supportMarket(CToken cToken) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK ); } if (markets[address(cToken)].isListed) { return fail( Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS ); } markets[address(cToken)] = Market({ isListed: true, isComped: false, collateralFactorMantissa: 0 }); _addMarketInternal(address(cToken)); _initializeMarket(address(cToken)); emit MarketListed(cToken); return uint256(Error.NO_ERROR); } function _supportMarket(CToken cToken) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK ); } if (markets[address(cToken)].isListed) { return fail( Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS ); } markets[address(cToken)] = Market({ isListed: true, isComped: false, collateralFactorMantissa: 0 }); _addMarketInternal(address(cToken)); _initializeMarket(address(cToken)); emit MarketListed(cToken); return uint256(Error.NO_ERROR); } function _supportMarket(CToken cToken) external returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK ); } if (markets[address(cToken)].isListed) { return fail( Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS ); } markets[address(cToken)] = Market({ isListed: true, isComped: false, collateralFactorMantissa: 0 }); _addMarketInternal(address(cToken)); _initializeMarket(address(cToken)); emit MarketListed(cToken); return uint256(Error.NO_ERROR); } function _addMarketInternal(address cToken) internal { for (uint256 i = 0; i < allMarkets.length; i++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } function _addMarketInternal(address cToken) internal { for (uint256 i = 0; i < allMarkets.length; i++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } function _initializeMarket(address cToken) internal { uint32 blockNumber = safe32( getBlockTimestamp(), "block number exceeds 32 bits" ); CompMarketState storage supplyState = compSupplyState[cToken]; CompMarketState storage borrowState = compBorrowState[cToken]; if (supplyState.index == 0) { supplyState.index = compInitialIndex; } if (borrowState.index == 0) { borrowState.index = compInitialIndex; } } function _initializeMarket(address cToken) internal { uint32 blockNumber = safe32( getBlockTimestamp(), "block number exceeds 32 bits" ); CompMarketState storage supplyState = compSupplyState[cToken]; CompMarketState storage borrowState = compBorrowState[cToken]; if (supplyState.index == 0) { supplyState.index = compInitialIndex; } if (borrowState.index == 0) { borrowState.index = compInitialIndex; } } function _initializeMarket(address cToken) internal { uint32 blockNumber = safe32( getBlockTimestamp(), "block number exceeds 32 bits" ); CompMarketState storage supplyState = compSupplyState[cToken]; CompMarketState storage borrowState = compBorrowState[cToken]; if (supplyState.index == 0) { supplyState.index = compInitialIndex; } if (borrowState.index == 0) { borrowState.index = compInitialIndex; } } supplyState.block = borrowState.block = blockNumber; function _setMarketBorrowCaps( CToken[] calldata cTokens, uint256[] calldata newBorrowCaps ) external { require( msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps" ); uint256 numMarkets = cTokens.length; uint256 numBorrowCaps = newBorrowCaps.length; require( numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input" ); for (uint256 i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } function _setMarketBorrowCaps( CToken[] calldata cTokens, uint256[] calldata newBorrowCaps ) external { require( msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps" ); uint256 numMarkets = cTokens.length; uint256 numBorrowCaps = newBorrowCaps.length; require( numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input" ); for (uint256 i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); address oldBorrowCapGuardian = borrowCapGuardian; borrowCapGuardian = newBorrowCapGuardian; emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } function _setPauseGuardian(address newPauseGuardian) public returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK ); } return uint256(Error.NO_ERROR); } function _setPauseGuardian(address newPauseGuardian) public returns (uint256) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK ); } return uint256(Error.NO_ERROR); } address oldPauseGuardian = pauseGuardian; pauseGuardian = newPauseGuardian; emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); function _setMintPaused(CToken cToken, bool state) public returns (bool) { require( markets[address(cToken)].isListed, "cannot pause a market that is not listed" ); require( msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause" ); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require( markets[address(cToken)].isListed, "cannot pause a market that is not listed" ); require( msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause" ); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require( msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause" ); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require( msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause" ); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require( msg.sender == unitroller.admin(), "only unitroller admin can change brains" ); require( unitroller._acceptImplementation() == 0, "change not authorized" ); } function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == comptrollerImplementation; } function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function isDeprecated(CToken cToken) public view returns (bool) { return markets[address(cToken)].collateralFactorMantissa == 0 && borrowGuardianPaused[address(cToken)] == true && cToken.reserveFactorMantissa() == 1e18; } function getBlockTimestamp() public view returns (uint256) { return block.timestamp; } function isMarketListed(address cTokenAddress) public view returns (bool) { return markets[cTokenAddress].isListed; } }
13,231,637
[ 1, 4412, 6837, 49, 970, 21269, 1297, 506, 23457, 6802, 2353, 333, 460, 1746, 6837, 49, 970, 21269, 1297, 486, 9943, 333, 460, 2631, 4508, 2045, 287, 6837, 49, 970, 21269, 2026, 9943, 333, 460, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 565, 871, 6622, 278, 682, 329, 12, 1268, 969, 276, 1345, 1769, 203, 203, 565, 871, 6622, 278, 10237, 329, 12, 1268, 969, 276, 1345, 16, 1758, 2236, 1769, 203, 203, 565, 871, 6622, 278, 6767, 329, 12, 1268, 969, 276, 1345, 16, 1758, 2236, 1769, 203, 203, 565, 871, 1166, 4605, 6837, 12, 203, 3639, 2254, 5034, 1592, 4605, 6837, 49, 970, 21269, 16, 203, 3639, 2254, 5034, 394, 4605, 6837, 49, 970, 21269, 203, 565, 11272, 203, 203, 565, 871, 1166, 13535, 2045, 287, 6837, 12, 203, 3639, 385, 1345, 276, 1345, 16, 203, 3639, 2254, 5034, 1592, 13535, 2045, 287, 6837, 49, 970, 21269, 16, 203, 3639, 2254, 5034, 394, 13535, 2045, 287, 6837, 49, 970, 21269, 203, 565, 11272, 203, 203, 565, 871, 1166, 48, 18988, 350, 367, 382, 2998, 688, 12, 203, 3639, 2254, 5034, 1592, 48, 18988, 350, 367, 382, 2998, 688, 49, 970, 21269, 16, 203, 3639, 2254, 5034, 394, 48, 18988, 350, 367, 382, 2998, 688, 49, 970, 21269, 203, 565, 11272, 203, 203, 565, 871, 1166, 17631, 1060, 1669, 19293, 12, 203, 3639, 1758, 1592, 17631, 1060, 1669, 19293, 16, 203, 3639, 1758, 394, 17631, 1060, 1669, 19293, 203, 565, 11272, 203, 203, 565, 871, 1166, 5147, 23601, 12, 203, 3639, 20137, 23601, 1592, 5147, 23601, 16, 203, 3639, 20137, 23601, 394, 5147, 23601, 203, 565, 11272, 203, 203, 565, 871, 1166, 19205, 16709, 2779, 12, 2867, 1592, 19205, 16709, 2779, 16, 1758, 394, 19205, 16709, 2779, 1769, 203, 203, 565, 871, 4382, 2 ]
./full_match/1/0x7d648a11AE84487526b7474b6A2BC0BE3a299BBb/sources/contracts/FlexibleNonceForwarder.sol
The tx to be forwarded is too old.
error FlexibleNonceForwarder__TxTooOld(uint256 blockNumber, uint256 blockAgeTolerance);
16,586,461
[ 1, 1986, 2229, 358, 506, 19683, 353, 4885, 1592, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 555, 478, 21873, 13611, 30839, 972, 4188, 10703, 7617, 12, 11890, 5034, 1203, 1854, 16, 2254, 5034, 1203, 9692, 22678, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import './SuperCoin.sol'; contract Election { /* The struct (Candidates) has the following attributes: Internal id, candidate name, candidate agenda, candidate voting counter, candidate picture */ struct Candidate { uint id; //0 string name; //1 string agenda; //2 uint counter; //3 string candidatePicture; //4 address candidateAddress; //5 } // The mapping (candidates) is between candidate id to the candidates attributes mapping(uint => Candidate) public candidates; /* The mapping (voters) is between the voter address and {0,1,2,3,4}. "0" stands for no voting rights "1" stands for the user has a voting right & question rights that wasn't exercised "2" stands for the user has a voting right but asked a question "3" stands for the user has voted "4" stands for pending request for voting rights */ mapping(address => uint) public voters; mapping(uint => address) public registeredVoters; uint public numberOfCandidates; address public admin; uint public votingStartDate; // Voting start date uint public votingEndDate; // Voting end date uint public numberOfVoters; bool public isVotingDatesConfigured; SuperCoin private coin; constructor () public { admin = msg.sender; votingStartDate = 0; votingEndDate = 1; isVotingDatesConfigured = false; registeredVoters[1] = msg.sender; numberOfVoters = 1; voters[msg.sender] = 1; coin = new SuperCoin(6262019); } // The modifier (onlyAdmin) insure that only an admin can use the function modifier onlyAdmin { require( msg.sender == admin, "Only Admin can call this function.");_; } // The modifier (whileVoting) limits changes after voting started (such as adding a candidate or adding voters) modifier whileVoting { require(now < votingEndDate && now >= votingStartDate, "Voting has NOT started yet.");_; } // The modifier (beforeVotingStarted) insure that now is prior to voting start date modifier beforeVotingStarted { require( votingStartDate > now, "Voting has started, this is not allowed during voting time");_; } //MARK: - Getters function isAdmin (address _checkAdmin) public view returns (bool TF) { return (_checkAdmin == admin); } // The function (voterStatus) will return the voting status of the sender {0,1,2} function voterStatus () public view returns (uint status) { return (voters[msg.sender]); } function endVoting () public view returns (bool index) { return (now > votingEndDate && isVotingDatesConfigured); } /* The function (balanceOf) returns the number of tokens that a particular address,
 in this case, the contract owner, has in their account. */ function balanceOf (address _coinOwner) public view returns (uint) { return coin.voterBalance(_coinOwner); } //MARK: - Setters /* The function (addingCandidate) is limited for admin use only (with the help of the onlyAdmin modifier) and can be used only before voting starts (with the help of the beforeVotingStarted modifier), that is, adding a new candidate should take place only before voting starts */ function addingCandidate (string memory _name, string memory _agenda, string memory _picture, address _address) public onlyAdmin beforeVotingStarted { // Adding a new candidate to candidates mapping numberOfCandidates++; candidates[numberOfCandidates] = Candidate(numberOfCandidates, _name, _agenda, 0, _picture, _address); emit CandidatesAdded(numberOfCandidates); } // The function (defineVotingDates) is limited for admin use only (with the help of the onlyAdmin modifier) function defineVotingDates (uint _startDate, uint _endDate) public onlyAdmin { require ( _endDate > _startDate && _startDate > now, "Dates are not valid"); require (votingStartDate == 0 && votingEndDate == 1, "Dates already defined"); // Dates can be defined only once votingStartDate = _startDate; votingEndDate = _endDate; isVotingDatesConfigured = true; } /* The function (vote) can be used only while voting time period (with the help of th whileVoting modifier), it insure the user has voting rights and didn't use them allredy, and pay the voter after he votes. With the first require we insure that voter didn't vote in the past and has the right to vote. The seconde require insure that the candidate exists */ function vote (uint _candidateId) public whileVoting { require(voters[msg.sender] >= 1 && voters[msg.sender] <= 2, "You can not vote, you voted in the past, or you do not have the right to vote"); require(_candidateId > 0 && _candidateId <= numberOfCandidates, "This candidate doesn't exist"); candidates[_candidateId].counter ++; // Increase candidate counter voters[msg.sender] = 3; // Update users status emit VotingTookPlace(_candidateId); getPaid(msg.sender); // after coin is good } /* The function (addVoters) is limited for admin use only (with the help of the onlyAdmin modifier) and can be used only before voting starts (with the help of the beforeVotingStarted modifier), that is, adding a new voter should take place only before voting starts */ function addVoters (address[] memory _voters) public onlyAdmin beforeVotingStarted { for (uint i = 0; i < _voters.length; i++) { if (voters[_voters[i]] != 1) { voters[_voters[i]] = 1; numberOfVoters++; registeredVoters[numberOfVoters] = _voters[i]; } } emit VotersAdded(); } //MARK: - Private /* The function (getPaid) will reward any voter which is entitle, that is, either the voter voted or he asked a question were all candidates answered */ function getPaid (address _receiver) private { //require(coin.voterBalance(admin) > 0, "Next time please vote earlier"); coin.transferCoin(_receiver, 1); // new line - 1 coin for a vote emit VoterGotPaidForVoting(_receiver); } //MARK: - Events event VoterGotPaidForVoting (address indexed receiver); event VotingTookPlace (uint indexed candidateId); event CandidatesAdded (uint indexed candidateId); event VotersAdded (); //----------------------------------------------------------------------------------------------------------------------------// /* Bonus part: Questions from voters and answers candidates + enabling user to request voting rights In order to encourage vote, debate and contact with candidates we thought about a mechanism of questions and answersץ Each voter, after voting started, has the right to ask all candidates one question, if all candidates answered this questions (that is the question was relevant) the voter receives a reward (coin).*/ // The mapping is between question id to question struct mapping (uint => Question) public questionList; // The mapping is between questions and answers mapping (uint => mapping (address => string)) public answerList; /* The struct (Question) has the following attributes: question, counter of answers, questioner address */ struct Question { string question; uint answerCounter; address questioner; } uint public numberOfQuestions; // Counter for the number of questions been asked /* The function (addQuestion) can be used only while voting time period (with the help of the whileVoting modifier), it insure that the voter has voting & question rights, saves the question and update the counter */ function addQuestion (string memory _question) public whileVoting { require(voters[msg.sender] == 1 , "Question can't be asked"); // make sure he has voting & asking rights numberOfQuestions++; voters[msg.sender] = 2; // mark he asked a question questionList[numberOfQuestions] = Question(_question, 0, msg.sender); emit NewQuestion(numberOfQuestions); } /* The function (addAnswer) can be used only be used only by candidates (with the help of isCandidate function), insure that the candidate didn't answer in the past, updates the answers, and check if the questioner entitled to the reward */ function addAnswer (string memory _answer, uint _questionId) public { require(getStringLength(answerList[_questionId][msg.sender]) == 0); // make sure he didn't answered this question require(isCandidate(msg.sender)); // make sure he is a candidate answerList[_questionId][msg.sender] = _answer; // save answer of the candidate questionList[_questionId].answerCounter++; // increase by 1 the answer counter if (questionList[_questionId].answerCounter == numberOfCandidates) { // if answer counter == number of candidates => pay the voter getPaid(questionList[_questionId].questioner); } emit NewAnswer(_questionId, msg.sender); } function getStringLength (string memory _string) private pure returns(uint _length) { bytes memory helper = bytes(_string); return (helper.length); } function isCandidate (address _helper) public view returns(bool ok) { for (uint i = 1; i <= numberOfCandidates; i++) { if (candidates[i].candidateAddress == _helper) { return(true); } } return(false); } event NewQuestion (uint indexed questionId); event NewAnswer (uint indexed questionId, address indexed candidateId); // Enabling user to request voting rights - voter can request from admin to get voting rights: mapping (uint => address) public pendingVoters; uint public numberOfPendingRequest; /* The function (addNewRequesst) can be used only before voting started (with the help of the beforeVoting modifer). It the the requester hasn't have voting rights and does n ot have anther pendding request. update requester status to pendding request (voters == 4) and updating the pendingVoters mapping */ function addNewRequest () public beforeVotingStarted { require(voters[msg.sender] == 0, "Your request is invalid"); // insure he hasn't have voting rights voters[msg.sender] = 4; // update requester status to pendding request numberOfPendingRequest++; // increase counter by one pendingVoters[numberOfPendingRequest] = msg.sender; } /* The function (getPendingRequesters) returns an array of address, oreder by the key in pending voters */ function getPendingRequesters() public view onlyAdmin returns(address[] memory _pendingRequesters) { address[] memory _pendingRequesters; for(uint i = 1; i <= numberOfPendingRequest; i++) { _pendingRequesters[i] = pendingVoters[i]; } return (_pendingRequesters); } function approveRequest(uint _requesterId) public onlyAdmin beforeVotingStarted { require(voters[pendingVoters[_requesterId]] == 4, "Can't approve"); voters[pendingVoters[_requesterId]] == 1; // update his voting rigths pendingVoters[_requesterId] = pendingVoters[numberOfPendingRequest]; numberOfPendingRequest--; } }
The struct (Candidates) has the following attributes:
struct Candidate { } "1" stands for the user has a voting right & question rights that wasn't exercised "2" stands for the user has a voting right but asked a question "3" stands for the user has voted "4" stands for pending request for voting rights */ mapping(address => uint) public voters; mapping(uint => address) public registeredVoters; uint public numberOfCandidates; address public admin; uint public numberOfVoters; bool public isVotingDatesConfigured; SuperCoin private coin;
12,693,260
[ 1, 1986, 1958, 261, 18455, 13, 711, 326, 3751, 1677, 30, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 1697, 385, 8824, 288, 203, 202, 97, 203, 203, 203, 202, 6, 21, 6, 384, 5708, 364, 326, 729, 711, 279, 331, 17128, 2145, 473, 5073, 14989, 716, 14487, 1404, 431, 12610, 5918, 203, 202, 6, 22, 6, 384, 5708, 364, 326, 729, 711, 279, 331, 17128, 2145, 1496, 19279, 279, 5073, 203, 202, 6, 23, 6, 384, 5708, 364, 326, 729, 711, 331, 16474, 203, 202, 6, 24, 6, 384, 5708, 364, 4634, 590, 364, 331, 17128, 14989, 1195, 203, 202, 6770, 12, 2867, 516, 2254, 13, 1071, 331, 352, 414, 31, 203, 203, 202, 6770, 12, 11890, 516, 1758, 13, 1071, 4104, 58, 352, 414, 31, 203, 203, 202, 11890, 1071, 7922, 18455, 31, 203, 202, 2867, 1071, 3981, 31, 203, 202, 11890, 1071, 7922, 58, 352, 414, 31, 203, 202, 6430, 1071, 353, 58, 17128, 15578, 15334, 31, 203, 202, 8051, 27055, 3238, 13170, 31, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0xB7b593a46dDBb9288Bc9A98041866F84b515952E/sources/contracts/aaaaaaa.sol
File contracts/libs/openzeppelin/utils/cryptography/ECDSA.sol* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. These functions can be used to verify that a message was signed by the holder of the private keys of a given address./
library ECDSA { function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } } enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { revert("ECDSA: invalid signature"); revert("ECDSA: invalid signature length"); revert("ECDSA: invalid signature 's' value"); revert("ECDSA: invalid signature 'v' value"); } } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { revert("ECDSA: invalid signature"); revert("ECDSA: invalid signature length"); revert("ECDSA: invalid signature 's' value"); revert("ECDSA: invalid signature 'v' value"); } } } else if (error == RecoverError.InvalidSignature) { } else if (error == RecoverError.InvalidSignatureLength) { } else if (error == RecoverError.InvalidSignatureS) { } else if (error == RecoverError.InvalidSignatureV) { function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); bytes32 r; bytes32 vs; assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); return (address(0), RecoverError.InvalidSignatureLength); } } function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); bytes32 r; bytes32 vs; assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); return (address(0), RecoverError.InvalidSignatureLength); } } function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); bytes32 r; bytes32 vs; assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); return (address(0), RecoverError.InvalidSignatureLength); } } } else if (signature.length == 64) { function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); bytes32 r; bytes32 vs; assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); return (address(0), RecoverError.InvalidSignatureLength); } } } else { function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } address signer = ecrecover(hash, v, r, s); function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } }
7,135,004
[ 1, 812, 20092, 19, 21571, 19, 3190, 94, 881, 84, 292, 267, 19, 5471, 19, 22784, 15669, 19, 7228, 19748, 18, 18281, 225, 10426, 549, 21507, 22901, 11678, 7053, 9249, 15067, 261, 7228, 19748, 13, 5295, 18, 8646, 4186, 848, 506, 1399, 358, 3929, 716, 279, 883, 1703, 6726, 635, 326, 10438, 434, 326, 3238, 1311, 434, 279, 864, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 7773, 19748, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 97, 203, 203, 203, 203, 565, 2792, 868, 3165, 668, 288, 203, 3639, 2631, 668, 16, 203, 3639, 1962, 5374, 16, 203, 3639, 1962, 5374, 1782, 16, 203, 3639, 1962, 5374, 55, 16, 203, 3639, 1962, 5374, 58, 203, 565, 289, 203, 203, 565, 445, 389, 12849, 668, 12, 27622, 668, 555, 13, 3238, 16618, 288, 203, 3639, 309, 261, 1636, 422, 868, 3165, 668, 18, 2279, 668, 13, 288, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 8863, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 769, 8863, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 296, 87, 11, 460, 8863, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 296, 90, 11, 460, 8863, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 12849, 668, 12, 27622, 668, 555, 13, 3238, 16618, 288, 203, 3639, 309, 261, 1636, 422, 868, 3165, 668, 18, 2279, 668, 13, 288, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 8863, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 769, 8863, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 296, 87, 11, 460, 8863, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 2 ]
/** * MIT License * * Copyright (c) 2019 eToroX Labs * * 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. */ pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/access/Roles.sol"; import "./roles/WhitelistAdminRole.sol"; import "./roles/BlacklistAdminRole.sol"; /** * @title The Accesslist contract * @dev Contract that contains a whitelist and a blacklist and manages them */ contract Accesslist is WhitelistAdminRole, BlacklistAdminRole { using Roles for Roles.Role; event WhitelistAdded(address indexed account); event WhitelistRemoved(address indexed account); event BlacklistAdded(address indexed account); event BlacklistRemoved(address indexed account); Roles.Role private whitelist; Roles.Role private blacklist; /** * @dev Calls internal function _addWhitelisted * to add given address to whitelist * @param account Address to be added */ function addWhitelisted(address account) public onlyWhitelistAdmin { _addWhitelisted(account); } /** * @dev Calls internal function _removeWhitelisted * to remove given address from the whitelist * @param account Address to be removed */ function removeWhitelisted(address account) public onlyWhitelistAdmin { _removeWhitelisted(account); } /** * @dev Calls internal function _addBlacklisted * to add given address to blacklist * @param account Address to be added */ function addBlacklisted(address account) public onlyBlacklistAdmin { _addBlacklisted(account); } /** * @dev Calls internal function _removeBlacklisted * to remove given address from blacklist * @param account Address to be removed */ function removeBlacklisted(address account) public onlyBlacklistAdmin { _removeBlacklisted(account); } /** * @dev Checks to see if the given address is whitelisted * @param account Address to be checked * @return true if address is whitelisted */ function isWhitelisted(address account) public view returns (bool) { return whitelist.has(account); } /** * @dev Checks to see if given address is blacklisted * @param account Address to be checked * @return true if address is blacklisted */ function isBlacklisted(address account) public view returns (bool) { return blacklist.has(account); } /** * @dev Checks to see if given address is whitelisted and not blacklisted * @param account Address to be checked * @return true if address has access */ function hasAccess(address account) public view returns (bool) { return isWhitelisted(account) && !isBlacklisted(account); } /** * @dev Adds given address to the whitelist * @param account Address to be added */ function _addWhitelisted(address account) internal { whitelist.add(account); emit WhitelistAdded(account); } /** * @dev Removes given address to the whitelist * @param account Address to be removed */ function _removeWhitelisted(address account) internal { whitelist.remove(account); emit WhitelistRemoved(account); } /** * @dev Adds given address to the blacklist * @param account Address to be added */ function _addBlacklisted(address account) internal { blacklist.add(account); emit BlacklistAdded(account); } /** * @dev Removes given address to the blacklist * @param account Address to be removed */ function _removeBlacklisted(address account) internal { blacklist.remove(account); emit BlacklistRemoved(account); } }
* @dev Removes given address to the whitelist @param account Address to be removed/
function _removeWhitelisted(address account) internal { whitelist.remove(account); emit WhitelistRemoved(account); }
14,067,978
[ 1, 6220, 864, 1758, 358, 326, 10734, 225, 2236, 5267, 358, 506, 3723, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4479, 18927, 329, 12, 2867, 2236, 13, 2713, 288, 203, 3639, 10734, 18, 4479, 12, 4631, 1769, 203, 3639, 3626, 3497, 7523, 10026, 12, 4631, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/noteUSDStorage.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; contract noteUSDStorage { /** WARNING: NEVER RE-ORDER VARIABLES! * Always double-check that new variables are added APPEND-ONLY. * Re-ordering variables can permanently BREAK the deployed proxy contract. */ bool public initialized; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; mapping(address => bool) public blacklist; uint256 internal _totalSupply; string public constant name = "noteUSD"; string public constant symbol = "noteUSD"; uint256 public multiplier; uint8 public constant decimals = 18; address public admin; uint256 internal constant deci = 1e18; bool internal getpause; } // File: contracts/Proxiable.sol pragma solidity ^0.6.0; contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" function updateCodeAddress(address newAddress) internal { require( bytes32( 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7 ) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore( 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress ) } } function proxiableUUID() public pure returns (bytes32) { return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; } } // File: contracts/noteUSD.sol pragma solidity ^0.6.0; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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 whBTCer 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 whBTCer the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this mBTCod 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/BTCereum/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 whBTCer 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 ); } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/BTCereum/solidity/issues/2691 return msg.data; } } 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) { // Solidity only automatically asserts when dividing by 0 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; } } contract LibraryLock is noteUSDStorage { // Ensures no one can manipulate the Logic Contract once it is deployed. // PARITY WALLET HACK PREVENTION modifier delegatedOnly() { require( initialized == true, "The library is locked. No direct 'call' is allowed." ); _; } function initialize() internal { initialized = true; } } contract noteUSD is noteUSDStorage, Context, IERC20, Proxiable, LibraryLock { using SafeMath for uint256; event fTokenBlacklist(address indexed account, bool blocked); event ChangeMultiplier(uint256 multiplier); event AdminChanged(address admin); event CodeUpdated(address indexed newCode); function initialize(uint256 _totalsupply) public { require(!initialized, "The library has already been initialized."); LibraryLock.initialize(); admin = msg.sender; multiplier = 1 * deci; _totalSupply = _totalsupply; _balances[msg.sender] = _totalSupply; } /// @dev Update the logic contract code function updateCode(address newCode) external onlyAdmin delegatedOnly { updateCodeAddress(newCode); emit CodeUpdated(newCode); } function setMultiplier(uint256 _multiplier) external onlyAdmin() ispaused() { require( _multiplier > multiplier, "the multiplier should be greater than previous multiplier" ); multiplier = _multiplier; emit ChangeMultiplier(multiplier); } function totalSupply() public override view returns (uint256) { return _totalSupply.mul(multiplier).div(deci); } function setTotalSupply(uint256 inputTotalsupply) external onlyAdmin() { require( inputTotalsupply > totalSupply(), "the input total supply is not greater than present total supply" ); multiplier = (inputTotalsupply.mul(deci)).div(_totalSupply); emit ChangeMultiplier(multiplier); } function balanceOf(address account) public override view returns (uint256) { uint256 externalAmt; externalAmt = _balances[account].mul(multiplier).div(deci); return externalAmt; } function transfer(address recipient, uint256 amount) public virtual override Notblacklist(msg.sender) Notblacklist(recipient) ispaused() returns (bool) { uint256 internalAmt; uint256 externalAmt = amount; internalAmt = (amount.mul(deci)).div(multiplier); _transfer(msg.sender, recipient, externalAmt); return true; } function allowance(address owner, address spender) public virtual override view returns (uint256) { uint256 internalAmt; uint256 maxapproval = 115792089237316195423570985008687907853269984665640564039457584007913129639935; maxapproval = maxapproval.div(multiplier).mul(deci); if(_allowances[owner][spender] > maxapproval){ internalAmt = 115792089237316195423570985008687907853269984665640564039457584007913129639935; }else{ internalAmt = (_allowances[owner][spender]).mul(multiplier).div(deci); } return internalAmt; } function approve(address spender, uint256 amount) public virtual override Notblacklist(spender) Notblacklist(msg.sender) ispaused() returns (bool) { uint256 internalAmt; uint256 externalAmt = amount; _approve(msg.sender, spender, externalAmt); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public Notblacklist(spender) Notblacklist(msg.sender) ispaused() returns (bool) { uint256 externalAmt = allowance(_msgSender(),spender) ; _approve(_msgSender(), spender, externalAmt.add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public Notblacklist(spender) Notblacklist(msg.sender) ispaused() returns (bool) { uint256 externalAmt = allowance(_msgSender(),spender) ; _approve(_msgSender(), spender, externalAmt.sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override Notblacklist(sender) Notblacklist(msg.sender) Notblacklist(recipient) ispaused() returns (bool) { uint256 externalAmt = allowance(sender,_msgSender()); _transfer(sender, recipient, amount); _approve( sender, _msgSender(), externalAmt.sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function _transfer( address sender, address recipient, uint256 externalAmt ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 internalAmt = externalAmt.mul(deci).div(multiplier); _balances[sender] = _balances[sender].sub( internalAmt, "ERC20: transfer internalAmt exceeds balance" ); _balances[recipient] = _balances[recipient].add(internalAmt); emit Transfer(sender, recipient, externalAmt); } function mint(address mintTo, uint256 amount) public virtual onlyAdmin() ispaused() returns (bool) { uint256 externalAmt = amount; uint256 internalAmt = externalAmt.mul(deci).div(multiplier); _mint(mintTo, internalAmt, externalAmt); return true; } function _mint( address account, uint256 internalAmt, uint256 externalAmt ) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(internalAmt); _balances[account] = _balances[account].add(internalAmt); emit Transfer(address(0), account, externalAmt); } function burn(address burnFrom, uint256 amount) public virtual onlyAdmin() ispaused() returns (bool) { uint256 internalAmt; uint256 externalAmt = amount; internalAmt = externalAmt.mul(deci).div(multiplier); _burn(burnFrom, internalAmt, externalAmt); return true; } function _burn( address account, uint256 internalAmt, uint256 externalAmt ) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub( internalAmt, "ERC20: burn internaAmt exceeds balance" ); _totalSupply = _totalSupply.sub(internalAmt); emit Transfer(account, address(0), externalAmt); } function _approve( address owner, address spender, uint256 externalAmt ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); uint256 internalAmt; uint256 maxapproval = 115792089237316195423570985008687907853269984665640564039457584007913129639935; maxapproval = maxapproval.div(multiplier).mul(deci); if(externalAmt > maxapproval){ internalAmt = 115792089237316195423570985008687907853269984665640564039457584007913129639935; }else{ internalAmt = externalAmt.mul(deci).div(multiplier); } _allowances[owner][spender] = internalAmt; emit Approval(owner, spender,externalAmt); } function TransferOwnerShip(address account) public onlyAdmin() { require(account != address(0), "account cannot be zero address"); require(msg.sender == admin, "you are not the admin"); admin = account; emit AdminChanged(admin); } function pause() external onlyAdmin() { getpause = true; } function unpause() external onlyAdmin() { getpause = false; } // pause unpause modifier ispaused() { require(getpause == false, "the contract is paused"); _; } modifier onlyAdmin() { require(msg.sender == admin, "you are not the admin"); _; } function AddToBlacklist(address account) external onlyAdmin() { blacklist[account] = true; emit fTokenBlacklist(account, true); } function RemoveFromBlacklist(address account) external onlyAdmin() { blacklist[account] = false; emit fTokenBlacklist(account, false); } modifier Notblacklist(address account) { require(!blacklist[account], "account is blacklisted"); _; } }
* @dev Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`./
function decreaseAllowance(address spender, uint256 subtractedValue) public Notblacklist(spender) Notblacklist(msg.sender) ispaused() returns (bool) { uint256 externalAmt = allowance(_msgSender(),spender) ; _approve(_msgSender(), spender, externalAmt.sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; }
567,454
[ 1, 3641, 6478, 23850, 3304, 326, 1699, 1359, 17578, 358, 1375, 87, 1302, 264, 68, 635, 326, 4894, 18, 1220, 353, 392, 10355, 358, 288, 12908, 537, 97, 716, 848, 506, 1399, 487, 279, 20310, 360, 367, 364, 9688, 11893, 316, 288, 45, 654, 39, 3462, 17, 12908, 537, 5496, 7377, 1282, 392, 288, 23461, 97, 871, 11193, 326, 3526, 1699, 1359, 18, 29076, 30, 300, 1375, 87, 1302, 264, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 87, 1302, 264, 68, 1297, 1240, 1699, 1359, 364, 326, 4894, 434, 622, 4520, 1375, 1717, 1575, 329, 620, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20467, 7009, 1359, 12, 2867, 17571, 264, 16, 2254, 5034, 10418, 329, 620, 13, 1071, 7010, 3639, 2288, 22491, 12, 87, 1302, 264, 13, 203, 3639, 2288, 22491, 12, 3576, 18, 15330, 13, 203, 3639, 353, 8774, 3668, 1435, 7010, 3639, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 5034, 3903, 31787, 273, 1699, 1359, 24899, 3576, 12021, 9334, 87, 1302, 264, 13, 274, 203, 3639, 389, 12908, 537, 24899, 3576, 12021, 9334, 17571, 264, 16, 3903, 31787, 18, 1717, 12, 1717, 1575, 329, 620, 16, 315, 654, 39, 3462, 30, 23850, 8905, 1699, 1359, 5712, 3634, 7923, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x4f31804e47cB30ECC93Cf69496C37a9D80F59dcC/sources/contracts/Headscapes.sol
Adds a user-defined title to a Headscape
function addTitle(uint256 tokenId, string memory text) public nonReentrant { require( _msgSender() == ownerOf(tokenId), "You don't own this Headscape" ); require( bytes(tokenIdToTitle[tokenId]).length == 0, "This Headscape already has a title!" ); require( !titleToIsTaken[(keccak256(abi.encodePacked((text))))], "This title has already been taken" ); require( bytes(text).length > 0 && bytes(text).length < 65, "Enter a title at least 1 and up to 64 chars long" ); tokenIdToTitle[tokenId] = cleanString(text); titleToIsTaken[(keccak256(abi.encodePacked((text))))] = true; }
2,989,088
[ 1, 3655, 279, 729, 17, 2178, 2077, 358, 279, 3667, 12476, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 4247, 12, 11890, 5034, 1147, 548, 16, 533, 3778, 977, 13, 1071, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 203, 5411, 389, 3576, 12021, 1435, 422, 3410, 951, 12, 2316, 548, 3631, 203, 5411, 315, 6225, 2727, 1404, 4953, 333, 3667, 12476, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1731, 12, 2316, 28803, 4247, 63, 2316, 548, 65, 2934, 2469, 422, 374, 16, 203, 5411, 315, 2503, 3667, 12476, 1818, 711, 279, 2077, 4442, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 401, 2649, 774, 2520, 27486, 63, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12443, 955, 3719, 3719, 6487, 203, 5411, 315, 2503, 2077, 711, 1818, 2118, 9830, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1731, 12, 955, 2934, 2469, 405, 374, 597, 1731, 12, 955, 2934, 2469, 411, 15892, 16, 203, 5411, 315, 10237, 279, 2077, 622, 4520, 404, 471, 731, 358, 5178, 5230, 1525, 6, 203, 3639, 11272, 203, 3639, 1147, 28803, 4247, 63, 2316, 548, 65, 273, 2721, 780, 12, 955, 1769, 203, 3639, 2077, 774, 2520, 27486, 63, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12443, 955, 3719, 3719, 65, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xc051ae8a4Fb38494E64a1666cEA5Dd39D40FF88F/sources/19_NFT_LATINOAMERICA/nftLatinoAmericaERC721.sol
* @dev Returns bytes converted @param _b bytes1/
function char(bytes1 _b) internal pure returns (bytes1 c) { if (uint8(_b) < 10) return bytes1(uint8(_b) + 0x30); else return bytes1(uint8(_b) + 0x57); }
5,581,244
[ 1, 1356, 1731, 5970, 225, 389, 70, 1731, 21, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1149, 12, 3890, 21, 389, 70, 13, 2713, 16618, 1135, 261, 3890, 21, 276, 13, 288, 203, 3639, 309, 261, 11890, 28, 24899, 70, 13, 411, 1728, 13, 327, 1731, 21, 12, 11890, 28, 24899, 70, 13, 397, 374, 92, 5082, 1769, 203, 3639, 469, 327, 1731, 21, 12, 11890, 28, 24899, 70, 13, 397, 374, 92, 10321, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // For remix //import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/master/contracts/token/ERC721/ERC721.sol"; import '../node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol'; import '../node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol'; contract StarNotary is ERC721, ERC721Metadata { constructor() ERC721Metadata("UdaTokenName", "USYMB") public { } struct Star { string starName; string starStory; string ra; string dec; string mag; bytes32 coordsHash; } mapping(uint256 => Star) public tokenIdToStarInfo; mapping(bytes32 => bool) public unique; mapping(uint256 => uint256) public starsForSale; uint256 public tokenAt; function createStar(string starName, string starStory, string ra, string dec, string mag) public { tokenAt++; bytes32 coordinates; // It should be greater than 3 require(bytes(starName).length > 3); // coordinates = keccak256(abi.encodePacked(ra, dec, mag)); coordinates = coordinatesToHash(ra, dec, mag); require(!checkIfStarExist(coordinates), "We have that Star!"); Star memory newStar = Star(starName, starStory, ra, dec, mag, coordinates); uint256 tokenId = tokenAt; tokenIdToStarInfo[tokenId] = newStar; unique[coordinates] = true; _mint(msg.sender, tokenId); } function tokenIdToStarInfo(uint256 tokenId) public view returns(string, string, string, string, string) { return (tokenIdToStarInfo[tokenId].starName, tokenIdToStarInfo[tokenId].starStory, tokenIdToStarInfo[tokenId].ra, tokenIdToStarInfo[tokenId].dec, tokenIdToStarInfo[tokenId].mag); } function checkIfStarExist(bytes32 coordinates) public view returns(bool) { return unique[coordinates]; } // To avoid: Warning: Function state mutability can be restricted to pure function coordinatesToHash(string ra, string dec, string mag) public pure returns(bytes32) { return keccak256(abi.encodePacked(ra, dec, mag)); } function putStarUpForSale(uint256 tokenId, uint256 price) public { require(this.ownerOf(tokenId) == msg.sender, "You are not the owner of that Star!"); starsForSale[tokenId] = price; } function buyStar(uint256 tokenId) public payable { // If it has a price, it is up for sale require(starsForSale[tokenId] > 0); uint256 starCost = starsForSale[tokenId]; address starOwner = this.ownerOf(tokenId); require(msg.value >= starCost); _removeTokenFrom(starOwner, tokenId); _addTokenTo(msg.sender, tokenId); starOwner.transfer(starCost); // If the value sent is more than the value of the star, we send the remaining back if(msg.value > starCost) { msg.sender.transfer(msg.value - starCost); } // And since it was sold, we remove it from the mapping starsForSale[tokenId] = 0; } // https://medium.com/coinmonks/exploring-non-fungible-token-with-zeppelin-library-erc721-399cb180cfaf function mint(uint256 tokenId) public { super._mint(msg.sender, tokenId); } function transferStar(address starOwner, address to, uint256 tokenId) public { safeTransferFrom(starOwner, to, tokenId); } function exchangeStars(address user1, uint256 user1TokenId, address user2, uint256 user2TokenId) public { require(this.ownerOf(user1TokenId) == user1); require(this.ownerOf(user2TokenId) == user2); _removeTokenFrom(user1, user1TokenId); _addTokenTo(user2, user1TokenId); _removeTokenFrom(user2, user2TokenId); _addTokenTo(user1, user2TokenId); } }
For remiximport "https:raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/master/contracts/token/ERC721/ERC721.sol";
import '../node_modules/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol';
6,394,105
[ 1, 1290, 849, 697, 5666, 315, 4528, 30, 1899, 18, 6662, 1355, 1745, 18, 832, 19, 3678, 62, 881, 84, 292, 267, 19, 3190, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 7525, 19, 16351, 87, 19, 2316, 19, 654, 39, 27, 5340, 19, 654, 39, 27, 5340, 18, 18281, 14432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5666, 25226, 2159, 67, 6400, 19, 3190, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 16351, 87, 19, 2316, 19, 654, 39, 27, 5340, 19, 654, 39, 27, 5340, 18, 18281, 13506, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.10; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; import "eth-token-recover/contracts/TokenRecover.sol"; import "dao-smartcontracts/contracts/dao/DAO.sol"; /** * @title TokenFaucet * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Implementation of a TokenFaucet */ contract TokenFaucet is TokenRecover { using SafeMath for uint256; using SafeERC20 for IERC20; event FaucetCreated(address indexed token); // struct representing the enabled faucet struct FaucetDetail { bool exists; bool enabled; uint256 dailyRate; uint256 referralRate; uint256 totalDistributedTokens; } // struct representing the faucet status for an account struct RecipientDetail { bool exists; mapping(address => uint256) tokens; mapping(address => uint256) lastUpdate; address referral; } // struct representing the referral status struct ReferralDetail { mapping(address => uint256) tokens; address[] recipients; } // the time between two tokens claim uint256 private _pauseTime = 1 days; // the DAO smart contract DAO private _dao; // list of addresses who received tokens address[] private _recipients; // map of address and faucet details mapping(address => FaucetDetail) private _faucetList; // map of address and received token amount mapping(address => RecipientDetail) private _recipientList; // map of address and referred addresses mapping(address => ReferralDetail) private _referralList; /** * @param dao DAO the decentralized organization address */ constructor(address payable dao) public { require(dao != address(0), "TokenFaucet: dao is the zero address"); _dao = DAO(dao); } /** * @return the DAO smart contract */ function dao() public view returns (DAO) { return _dao; } /** * @param token The token address to check * @return if faucet is enabled or not */ function isEnabled(address token) public view returns (bool) { return _faucetList[token].enabled; } /** * @param token The token address to check * @return the daily rate of tokens distributed */ function getDailyRate(address token) public view returns (uint256) { return _faucetList[token].dailyRate; } /** * @param token The token address to check * @return the value earned by referral for each recipient */ function getReferralRate(address token) public view returns (uint256) { return _faucetList[token].referralRate; } /** * @param token The token address to check * @return the sum of distributed tokens */ function totalDistributedTokens(address token) public view returns (uint256) { return _faucetList[token].totalDistributedTokens; } /** * @dev return the number of remaining tokens to distribute * @param token The token address to check * @return uint256 */ function remainingTokens(address token) public view returns (uint256) { return IERC20(token).balanceOf(address(this)); } /** * @return address of a recipient by list index */ function getRecipientAddress(uint256 index) public view returns (address) { return _recipients[index]; } /** * @dev return the recipients length * @return uint */ function getRecipientsLength() public view returns (uint) { return _recipients.length; } /** * @param account The address to check * @param token The token address to check * @return received token amount for the given address */ function receivedTokens(address account, address token) public view returns (uint256) { return _recipientList[account].tokens[token]; } /** * @param account The address to check * @param token The token address to check * @return last tokens received timestamp */ function lastUpdate(address account, address token) public view returns (uint256) { return _recipientList[account].lastUpdate[token]; } /** * @param account The address to check * @return referral for given address */ function getReferral(address account) public view returns (address) { return _recipientList[account].referral; } /** * @param account The address to check * @param token The token address to check * @return earned tokens by referrals */ function earnedByReferral(address account, address token) public view returns (uint256) { return _referralList[account].tokens[token]; } /** * @param account The address to check * @return referred addresses for given address */ function getReferredAddresses(address account) public view returns (address[] memory) { return _referralList[account].recipients; } /** * @param account The address to check * @return referred addresses for given address */ function getReferredAddressesLength(address account) public view returns (uint) { return _referralList[account].recipients.length; } /** * @param account The address to check * @param token The token address to check * @return time of next available claim or zero */ function nextClaimTime(address account, address token) public view returns (uint256) { return lastUpdate(account, token) == 0 ? 0 : lastUpdate(account, token) + _pauseTime; } /** * @param token Address of the token being distributed * @param dailyRate Daily rate of tokens distributed * @param referralRate The value earned by referral */ function createFaucet(address token, uint256 dailyRate, uint256 referralRate) public onlyOwner { require(!_faucetList[token].exists, "TokenFaucet: token faucet already exists"); require(token != address(0), "TokenFaucet: token is the zero address"); require(dailyRate > 0, "TokenFaucet: dailyRate is 0"); require(referralRate > 0, "TokenFaucet: referralRate is 0"); _faucetList[token].exists = true; _faucetList[token].enabled = true; _faucetList[token].dailyRate = dailyRate; _faucetList[token].referralRate = referralRate; emit FaucetCreated(token); } /** * @dev change daily referral rate * @param token Address of tokens being updated * @param newDailyRate Daily rate of tokens distributed * @param newReferralRate The value earned by referral */ function setFaucetRates(address token, uint256 newDailyRate, uint256 newReferralRate) public onlyOwner { require(_faucetList[token].exists, "TokenFaucet: token faucet does not exist"); require(newDailyRate > 0, "TokenFaucet: dailyRate is 0"); require(newReferralRate > 0, "TokenFaucet: referralRate is 0"); _faucetList[token].dailyRate = newDailyRate; _faucetList[token].referralRate = newReferralRate; } /** * @dev disable a faucet * @param token Address of tokens being updated */ function disableFaucet(address token) public onlyOwner { require(_faucetList[token].exists, "TokenFaucet: token faucet does not exist"); _faucetList[token].enabled = false; } /** * @dev enable a faucet * @param token Address of tokens being updated */ function enableFaucet(address token) public onlyOwner { require(_faucetList[token].exists, "TokenFaucet: token faucet does not exist"); _faucetList[token].enabled = true; } /** * @dev function to be called to receive tokens * @param token The token address to distribute */ function getTokens(address token) public { require(_faucetList[token].exists, "TokenFaucet: token faucet does not exist"); require(_dao.isMember(msg.sender), "TokenFaucet: message sender is not dao member"); // distribute tokens _distributeTokens(token, msg.sender, address(0)); } /** * @dev function to be called to receive tokens * @param token The token address to distribute * @param referral Address to an account that is referring */ function getTokensWithReferral(address token, address referral) public { require(_faucetList[token].exists, "TokenFaucet: token faucet does not exist"); require(_dao.isMember(msg.sender), "TokenFaucet: message sender is not dao member"); require(referral != msg.sender, "TokenFaucet: referral cannot be message sender"); // distribute tokens _distributeTokens(token, msg.sender, referral); } /** * @dev The way in which faucet tokens rate is calculated for recipient * @param token Address of tokens being distributed * @param account Address receiving the tokens * @return Number of tokens that can be received */ function _getRecipientTokenAmount(address token, address account) internal view returns (uint256) { uint256 tokenAmount = getDailyRate(token); if (_dao.stakedTokensOf(account) > 0) { tokenAmount = tokenAmount.mul(2); } if (_dao.usedTokensOf(account) > 0) { tokenAmount = tokenAmount.mul(2); } return tokenAmount; } /** * @dev The way in which faucet tokens rate is calculated for referral * @param token Address of tokens being distributed * @param account Address receiving the tokens * @return Number of tokens that can be received */ function _getReferralTokenAmount(address token, address account) internal view returns (uint256) { uint256 tokenAmount = 0; if (_dao.isMember(account)) { tokenAmount = getReferralRate(token); if (_dao.stakedTokensOf(account) > 0) { tokenAmount = tokenAmount.mul(2); } if (_dao.usedTokensOf(account) > 0) { tokenAmount = tokenAmount.mul(2); } } return tokenAmount; } /** * @dev distribute tokens * @param token The token being distributed * @param account Address being distributing * @param referral Address to an account that is referring */ function _distributeTokens(address token, address account, address referral) internal { // solhint-disable-next-line not-rely-on-time require(nextClaimTime(account, token) <= block.timestamp, "TokenFaucet: next claim date is not passed"); // check if recipient exists if (!_recipientList[account].exists) { _recipients.push(account); _recipientList[account].exists = true; // check if valid referral if (referral != address(0)) { _recipientList[account].referral = referral; _referralList[referral].recipients.push(account); } } uint256 recipientTokenAmount = _getRecipientTokenAmount(token, account); // update recipient status // solhint-disable-next-line not-rely-on-time _recipientList[account].lastUpdate[token] = block.timestamp; _recipientList[account].tokens[token] = _recipientList[account].tokens[token].add(recipientTokenAmount); // update faucet status _faucetList[token].totalDistributedTokens = _faucetList[token].totalDistributedTokens.add(recipientTokenAmount); // transfer tokens to recipient IERC20(token).safeTransfer(account, recipientTokenAmount); // check referral if (_recipientList[account].referral != address(0)) { // referral is only the first one referring address firstReferral = _recipientList[account].referral; uint256 referralTokenAmount = _getReferralTokenAmount(token, firstReferral); // referral can earn only if it is dao member if (referralTokenAmount > 0) { // update referral status _referralList[firstReferral].tokens[token] = _referralList[firstReferral].tokens[token].add(referralTokenAmount); // update faucet status _faucetList[token].totalDistributedTokens = _faucetList[token].totalDistributedTokens.add(referralTokenAmount); // transfer tokens to referral IERC20(token).safeTransfer(firstReferral, referralTokenAmount); } } } }
update faucet status
_faucetList[token].totalDistributedTokens = _faucetList[token].totalDistributedTokens.add(recipientTokenAmount);
12,668,738
[ 1, 2725, 11087, 5286, 278, 1267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 507, 5286, 278, 682, 63, 2316, 8009, 4963, 1669, 11050, 5157, 273, 389, 507, 5286, 278, 682, 63, 2316, 8009, 4963, 1669, 11050, 5157, 18, 1289, 12, 20367, 1345, 6275, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x53597d6fc27247d3f36BB4A41dDa7b30527A1b9b/sources/contracts/Crowdfunding.sol
@dev Refund a donation. Donation can be refunded if campaign is ended and goal has not been reached. @param _campaignId Campaign ID. @param _donationId Donation ID.
function refundDonation(uint _campaignId, uint _donationId) external { Donation storage donation = campaignDonations[_campaignId][_donationId]; Campaign storage campaign = campaigns[_campaignId]; require(campaign.status == 0, "Campaign is not active"); require(block.timestamp > campaign.endAt, "Campaign has not ended yet"); require(campaign.amount < campaign.goal, "Campaign goal has been reached"); require(donation.status == 0, "Donation is not active"); require(donation.sender == msg.sender, "Caller is not the donation sender"); donation.status = 2; require(success, "Failed to send Ether"); emit DonationRefunded(_donationId, campaign.id, msg.sender, donation.amount); }
5,673,303
[ 1, 21537, 279, 2727, 367, 18, 7615, 367, 848, 506, 1278, 12254, 309, 8965, 353, 16926, 471, 17683, 711, 486, 2118, 8675, 18, 225, 389, 14608, 548, 17820, 1599, 18, 225, 389, 19752, 367, 548, 7615, 367, 1599, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 16255, 22293, 367, 12, 11890, 389, 14608, 548, 16, 2254, 389, 19752, 367, 548, 13, 3903, 288, 203, 3639, 7615, 367, 2502, 2727, 367, 273, 8965, 22293, 1012, 63, 67, 14608, 548, 6362, 67, 19752, 367, 548, 15533, 203, 3639, 17820, 2502, 8965, 273, 8965, 87, 63, 67, 14608, 548, 15533, 203, 203, 3639, 2583, 12, 14608, 18, 2327, 422, 374, 16, 315, 13432, 353, 486, 2695, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 405, 8965, 18, 409, 861, 16, 315, 13432, 711, 486, 16926, 4671, 8863, 203, 3639, 2583, 12, 14608, 18, 8949, 411, 8965, 18, 27354, 16, 315, 13432, 17683, 711, 2118, 8675, 8863, 203, 3639, 2583, 12, 19752, 367, 18, 2327, 422, 374, 16, 315, 22293, 367, 353, 486, 2695, 8863, 203, 3639, 2583, 12, 19752, 367, 18, 15330, 422, 1234, 18, 15330, 16, 315, 11095, 353, 486, 326, 2727, 367, 5793, 8863, 203, 203, 3639, 2727, 367, 18, 2327, 273, 576, 31, 203, 203, 3639, 2583, 12, 4768, 16, 315, 2925, 358, 1366, 512, 1136, 8863, 203, 203, 3639, 3626, 7615, 367, 1957, 12254, 24899, 19752, 367, 548, 16, 8965, 18, 350, 16, 1234, 18, 15330, 16, 2727, 367, 18, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* _____ _ _ _ | __ \ (_) | | | | | | |_ ___| |_| |_ ___ _ __ | | | \ \ /\ / / | __| __/ _ \ '__| | |__| |\ V V /| | |_| || __/ | |_____/ \_/\_/ |_|\__|\__\___|_| */ // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.8.0; 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; } } /// @title A Decentralised Social Media Platform /// @author Mohit Bhat /// @notice You can use this contract to connect to decentralised social network, share your content to the world in a decentralised way! /// @dev Most of the features are implemented keeping note of security concerns contract Dwitter{ using SafeMath for uint; address payable public owner; //Owner is also a maintainer bool public stopped = false; struct User{ uint id; address ethAddress; string username; string name; string profileImgHash; string profileCoverImgHash; string bio; accountStatus status; // Account Banned or Not } struct Dweet{ uint dweetId; address author; string hashtag; string content; string imgHash; uint timestamp; uint likeCount; uint reportCount; cdStatus status; // Dweet Active-Deleted-Banned } struct Comment{ uint commentId; address author; uint dweetId; string content; uint likeCount; // uint reportCount; uint timestamp; cdStatus status; // Comment Reported and Banned or not } uint public totalDweets=0; uint public totalComments=0; uint public totalUsers=0; ///@dev NP means not present the default value for status enum accountStatus{NP,Active,Banned,Deactivated} enum cdStatus{NP,Active, Banned, Deleted}//Comment-Dweet status // enum dweetStatus{NP,Active, Banned, Deleted} mapping(address=>User) private users; //mapping to get user details from user address mapping(string=>address) private userAddressFromUsername;//to get user address from username // mapping(address=>bool) private registeredUser; //mapping to get user details from user address mapping(string=>bool) private usernames;//To check which username is taken taken=>true, not taken=>false mapping(uint=>Dweet) private dweets;// mapping to get dweet from Id mapping(address=>uint[]) private userDweets; // Array to store dweets(Id) done by user // mapping(uint=>address[]) private dweetLikersList; mapping(uint=>mapping(address=>bool)) private dweetLikers; // Mapping to track who liked which dweet mapping(uint=>Comment) private comments; //Mapping to get comment from comment Id mapping(address=>uint[]) private userComments;// Mapping to track user comments from there address // mapping(uint=>mapping(address=>bool)) private commentReporters; // Mapping to track who reported which comment // mapping(uint=>mapping(address=>bool)) private commentLikers; // Mapping to track who liked on which comment mapping(uint=>uint[]) private dweetComments; // Getting comments for a specific dweet modifier stopInEmergency { require(!stopped,"Dapp has been stopped!"); _; } modifier onlyInEmergency { require(stopped); _; } modifier onlyOwner{require(msg.sender==owner,"You are not owner!"); _;} modifier onlyDweetAuthor(uint id){require(msg.sender==dweets[id].author,"You are not Author!"); _;} modifier onlyCommentAuthor(uint id){require(msg.sender==comments[id].author,"You are not Author!"); _;} modifier onlyAllowedUser(address user){require(users[user].status==accountStatus.Active,"Not a Registered User!"); _;} modifier onlyActiveDweet(uint id){require(dweets[id].status==cdStatus.Active,"Not a active dweet"); _;} modifier onlyActiveComment(uint id){require(comments[id].status==cdStatus.Active,"Not a active comment"); _;} modifier usernameTaken(string memory username){require(!usernames[username],"Username already taken"); _;} // modifier checkUserExists(){require(registeredUser[msg.sender]); _;} modifier checkUserNotExists(address user){require(users[user].status==accountStatus.NP,"User already registered"); _;} event logRegisterUser(address user, uint id); event logUserBanned(address user, uint id); event logDweetCreated(address author, uint userid, uint dweetid, string hashtag); event logDweetDeleted(uint id, string hashtag); // event logCommentBanned(uint id, string hashtag); constructor() { owner=msg.sender; addMaintainer(msg.sender); registerUser("owner","owner","","","owner"); } fallback() external{ revert(); } /* **************************************USER FUNCTIONS******************************************************************************** */ /// @notice Check username available or not /// @param _username username to Check /// @return status true or false function usernameAvailable(string memory _username) public view returns(bool status){ return !usernames[_username]; } /// @notice Register a new user /// @param _username username of username /// @param _name name of person /// @param _imgHash Ipfs Hash of users Profile Image /// @param _coverHash Ipfs Hash of user cover Image /// @param _bio Biography of user function registerUser(string memory _username, string memory _name, string memory _imgHash, string memory _coverHash, string memory _bio ) public stopInEmergency checkUserNotExists(msg.sender) usernameTaken(_username){ usernames[_username]=true;// Attack Prevented totalUsers=totalUsers.add(1); uint id=totalUsers; users[msg.sender]=User(id, msg.sender, _username, _name, _imgHash, _coverHash, _bio, accountStatus.Active); userAddressFromUsername[_username]=msg.sender; emit logRegisterUser(msg.sender, totalUsers); } /// @notice Check accountStatus of user-Registered, Banned or Deleted /// @return status NP, Active, Banned or Deleted function userStatus() public view returns(accountStatus status){ return users[msg.sender].status; } /// @notice Change username of a user /// @param _username New username of user function changeUsername(string memory _username) public stopInEmergency onlyAllowedUser(msg.sender) usernameTaken(_username){ users[msg.sender].username=_username; } /// @notice Get user details /// @return id Id of user /// @return username username of person /// @return name Name of user /// @return imghash user profile image ipfs hash /// @return coverhash usercCover image ipfs hash /// @return bio Biography of user function getUser() public view returns(uint id, string memory username, string memory name, string memory imghash, string memory coverhash, string memory bio){ return(users[msg.sender].id,users[msg.sender].username, users[msg.sender].name, users[msg.sender].profileImgHash, users[msg.sender].profileCoverImgHash, users[msg.sender].bio); } /// @notice Get user details /// @param _user address of user /// @return id Id of user /// @return username username of person /// @return name Name of user /// @return imghash user profile image ipfs hash /// @return coverhash usercCover image ipfs hash /// @return bio Biography of user function getUser(address _user) public view returns(uint id, string memory username, string memory name, string memory imghash, string memory coverhash, string memory bio){ return(users[_user].id,users[_user].username, users[_user].name, users[_user].profileImgHash, users[_user].profileCoverImgHash, users[_user].bio); } /// @notice Ban user Internal Function /// @param _user address of user function banUser(address _user) internal onlyAllowedUser(_user) onlyMaintainer { delete users[_user]; users[_user].status=accountStatus.Banned; emit logUserBanned(msg.sender, users[_user].id); } /* **************************************DWEET FUNCTIONS*********************************************************** */ /// @notice Create a new dweet /// @param _hashtag hashtag of dweet ex. #ethereum /// @param _content content of dweet to show /// @param _imghash Image type content ipfs hash function createDweet(string memory _hashtag, string memory _content, string memory _imghash) public stopInEmergency onlyAllowedUser(msg.sender) { totalDweets=totalDweets.add(1); uint id=totalDweets; dweets[id]=Dweet(id, msg.sender, _hashtag, _content, _imghash, block.timestamp , 0, 0, cdStatus.Active); userDweets[msg.sender].push(totalDweets); emit logDweetCreated(msg.sender, users[msg.sender].id, totalDweets, _hashtag); } /// @notice Ban Dweet Internal Function /// @param _id Id of dweet function banDweet(uint _id) internal{ emit logDweetBanned(_id, dweets[_id].hashtag, maintainerId[msg.sender]); delete dweets[_id]; dweets[_id].status=cdStatus.Banned; for(uint i=0;i<dweetComments[_id].length;i++){ delete dweetComments[_id][i]; } delete dweetComments[_id]; } /// @notice Edit a dweet /// @param _id Id of dweet /// @param _hashtag New tag of dweet /// @param _content New content of dweet /// @param _imghash Hash of new image content function editDweet(uint _id, string memory _hashtag, string memory _content, string memory _imghash) public stopInEmergency onlyActiveDweet(_id) onlyAllowedUser(msg.sender) onlyDweetAuthor(_id) { dweets[_id].hashtag=_hashtag; dweets[_id].content=_content; dweets[_id].imgHash=_imghash; } /// @notice Delete a dweet /// @param _id Id of dweet function deleteDweet(uint _id) public onlyActiveDweet(_id) onlyAllowedUser(msg.sender) stopInEmergency onlyDweetAuthor(_id){ emit logDweetDeleted(_id, dweets[_id].hashtag); delete dweets[_id]; dweets[_id].status=cdStatus.Deleted; for(uint i=0;i<dweetComments[_id].length;i++){ delete dweetComments[_id][i]; } delete dweetComments[_id]; } /// @notice Get a Dweet /// @param _id Id of dweet /// @return author Dweet author address /// @return hashtag Tag of dweet /// @return content Content of dweet /// @return imgHash Hash of image content /// @return timestamp Dweet creation timestamp /// @return likeCount No of likes on dweet function getDweet(uint _id) public onlyAllowedUser(msg.sender) onlyActiveDweet(_id) view returns ( address author, string memory hashtag, string memory content, string memory imgHash, uint timestamp, uint likeCount ){ return (dweets[_id].author, dweets[_id].hashtag, dweets[_id].content, dweets[_id].imgHash, dweets[_id].timestamp, dweets[_id].likeCount); } /// @notice Like a dweets /// @param _id Id of dweet to be likeDweet function likeDweet(uint _id) public onlyAllowedUser(msg.sender) onlyActiveDweet(_id){ require(!dweetLikers[_id][msg.sender]); dweets[_id].likeCount=dweets[_id].likeCount.add(1); dweetLikers[_id][msg.sender]=true; } /// @notice Get list of dweets done by a user /// @return dweetList Array of dweet ids function getUserDweets() public view onlyAllowedUser(msg.sender) returns(uint[] memory dweetList){ return userDweets[msg.sender]; } /// @notice Get list of dweets done by a user /// @param _user User address /// @return dweetList Array of dweet ids function getUserDweets(address _user) public view onlyAllowedUser(msg.sender) returns(uint[] memory dweetList){ return userDweets[_user]; } /* **************************************COMMENT FUNCTIONS************************************************************************* */ /// @notice Create a comment on dweet /// @param _dweetid Id of dweetList /// @param _comment content of comment function createComment(uint _dweetid, string memory _comment) public stopInEmergency onlyAllowedUser(msg.sender) onlyActiveDweet(_dweetid){ totalComments=totalComments.add(1); uint id=totalComments; comments[id]=Comment(id, msg.sender, _dweetid, _comment, 0, block.timestamp, cdStatus.Active); userComments[msg.sender].push(totalComments); dweetComments[_dweetid].push(totalComments); } // function banComment(uint _id) internal { // emit logCommentBanned(_id, dweets[comments[_id].dweetId].hashtag); // delete comments[_id]; // comments[_id].status=cdStatus.Banned; // } /// @notice Get list of dweets done by a user /// @param _commentid Id of comments /// @param _comment New content of comment function editComment(uint _commentid, string memory _comment) public stopInEmergency onlyAllowedUser(msg.sender) onlyActiveComment(_commentid) onlyCommentAuthor(_commentid){ comments[_commentid].content=_comment; } /// @notice Delete a comment /// @param _id Id of comment to be Deleted function deleteComment(uint _id) public stopInEmergency onlyActiveComment(_id) onlyAllowedUser(msg.sender) onlyCommentAuthor(_id) { delete comments[_id]; comments[_id].status=cdStatus.Deleted; } /// @notice Get a comment /// @param _id Id of comment /// @return author Address of author /// @return dweetId Id of dweet /// @return content content of comment /// @return likeCount Likes on commment /// @return timestamp Comment creation timestamp /// @return status status of Comment active-banned-deleted function getComment(uint _id) public view onlyAllowedUser(msg.sender) onlyActiveComment(_id) returns(address author, uint dweetId, string memory content, uint likeCount, uint timestamp, cdStatus status){ return(comments[_id].author, comments[_id].dweetId, comments[_id].content, comments[_id].likeCount, comments[_id].timestamp, comments[_id].status); } /// @notice Get comments done by user /// @return commentList Array of comment ids /// @dev Though onlyAllowedUser can be bypassed easily but still keeping for calls from frontend function getUserComments() public view onlyAllowedUser(msg.sender) returns(uint[] memory commentList){ return userComments[msg.sender]; } /// @notice Get comments done by user /// @param _user address of user /// @return commentList Array of comment ids function getUserComments(address _user) public view onlyAllowedUser(msg.sender) returns(uint[] memory commentList){ return userComments[_user]; } /// @notice Get comments on a dweet /// @return list Array of comment ids function getDweetComments(uint _id) public view onlyAllowedUser(msg.sender) onlyActiveDweet(_id) returns(uint[] memory list){ return(dweetComments[_id]); } /* **********************************Reporting And Maintanining***************************************************************************************** */ uint public totalMaintainers=0; uint[] private dweetsReportedList;// List of ids of reported dweets uint private noOfReportsRequired=1;// No of reports required to term a dweet reported and send for action uint public reportingstakePrice=1936458778290500;// Stake amount to pay while reporting uint public reportingRewardPrice=3872917556581000;// Reward of correct reporting mapping(address=>bool) public isMaintainer; mapping(address=>uint) private maintainerId; mapping(uint=>mapping(address=>bool)) private dweetReporters; // Mapping to track who reported which dweet mapping(uint=>reportAction) private actionOnDweet;// What is the ction on dweet done by maintainers mapping(address=>uint[]) public userReportList;// Ids of dweets reported by a user //mapping(address=>uint) private userRewards; mapping(address=>uint) private fakeReportingReward;// Reward a user get when somebody do a fake reporting against that user mapping(uint=>mapping(address=>userdweetReportingStatus)) private claimedReward;//To check whether user has claimed reward for a particular reporting enum userdweetReportingStatus{NP, Reported, Claimed} enum reportAction{NP, Banned, Free} modifier onlyMaintainer(){ require(isMaintainer[msg.sender],"You are not a maintainer"); _; } modifier paidEnoughforReporter() { require(msg.value >= reportingstakePrice,"You have not paid enough for advertisement"); _;} modifier checkValueforReporter() { _; uint amountToRefund = msg.value.sub(reportingstakePrice); msg.sender.transfer(amountToRefund); } /// @notice Add a maintainer to the platform /// @param _user Address of user to be added as maintainer function addMaintainer(address _user) public onlyOwner { isMaintainer[_user]=true; totalMaintainers=totalMaintainers.add(1); maintainerId[msg.sender]=totalMaintainers; } /// @notice Remove a maintainer /// @param _user Address of user to be removed from maintainer function revokeMaintainer(address _user) public onlyOwner{ isMaintainer[_user]=false; } event logDweetReported(uint id, string hashtag); event logDweetBanned(uint id, string hashtag, uint maintainer); // To track how many dweets were banned to specific hashtag event logDweetFreed(uint id, string hashtag, uint maintainer); // To track how many dweets were banned to specific hashtag /// @notice Report a dweet /// @param _dweetId Id of the dweet to be reported function reportDweet(uint _dweetId) public payable onlyActiveDweet(_dweetId) onlyAllowedUser(msg.sender) paidEnoughforReporter checkValueforReporter{ require(dweets[_dweetId].reportCount<=noOfReportsRequired,"Dweet have got required no of Reports"); require(!dweetReporters[_dweetId][msg.sender],"You have already Reported!"); dweetReporters[_dweetId][msg.sender]=true;//Reentracy attack Prevented userReportList[msg.sender].push(_dweetId); claimedReward[_dweetId][msg.sender]=userdweetReportingStatus.Reported; dweets[_dweetId].reportCount=dweets[_dweetId].reportCount.add(1); uint reports= dweets[_dweetId].reportCount; if(reports==noOfReportsRequired){ dweetsReportedList.push(_dweetId); emit logDweetReported(_dweetId, dweets[_dweetId].hashtag); } } /// @notice Take action on a reported dweets /// @param _dweetId Id of dweets /// @param _action ban or free, true or false function takeAction(uint _dweetId, bool _action) public onlyMaintainer onlyActiveDweet(_dweetId) onlyAllowedUser(msg.sender){ require(actionOnDweet[_dweetId]==reportAction.NP,"Action already taken!"); if(_action){ actionOnDweet[_dweetId]=reportAction.Banned; banDweet(_dweetId); }else{ actionOnDweet[_dweetId]=reportAction.Free; fakeReportingReward[dweets[_dweetId].author]=fakeReportingReward[dweets[_dweetId].author].add(reportingstakePrice.mul(noOfReportsRequired)); emit logDweetFreed(_dweetId, dweets[_dweetId].hashtag, maintainerId[msg.sender]); } } /// @notice Claim right reporting reward /// @param _id Id of dweet on which reward is to be claimed function claimReportingReward(uint _id) public onlyAllowedUser(msg.sender){ require(claimedReward[_id][msg.sender]==userdweetReportingStatus.Reported,"You have not reported or already claimed"); require(userReportList[msg.sender].length>0); require(actionOnDweet[_id]==reportAction.Banned,"Not eligible for reward, Dweet has been freed my mainatiners"); claimedReward[_id][msg.sender]=userdweetReportingStatus.Claimed;//Reentracy Prevented msg.sender.transfer(reportingRewardPrice); } /// @notice Claim fake reporting reward(suit) function claimSuitReward()public onlyAllowedUser(msg.sender){ require(fakeReportingReward[msg.sender]>0,"Not enough balance"); uint amount=fakeReportingReward[msg.sender]; fakeReportingReward[msg.sender]=0;//Attack Prevented msg.sender.transfer(amount); } /// @notice To get list of reportings done by a user /// @param list Array of dweet Ids reported by user function myReportings() public view onlyAllowedUser(msg.sender) returns(uint[] memory list){ return userReportList[msg.sender]; } // function myReportingReward() public view onlyAllowedUser(msg.sender) returns(uint balance){ // return userRewards[msg.sender]; // } /// @notice To get claim status of reporting /// @param _id Id of dweetsReportedList /// @return status status of claim reported or claimed function reportingClaimStatus(uint _id) public view onlyAllowedUser(msg.sender) returns(userdweetReportingStatus status){ return claimedReward[_id][msg.sender]; } /// @notice To get fake reporting reward balance /// @return balance reward balance of user function fakeReportingSuitReward() public view onlyAllowedUser(msg.sender) returns(uint balance){ return fakeReportingReward[msg.sender]; } /// @notice To get list of reported dweets on the platform /// @return list Array of reported dweet ids function getReportedDweets() public view onlyAllowedUser(msg.sender) returns(uint[] memory list){ return(dweetsReportedList); } /// @notice Get action status of reporting on a dweet /// @param _dweetId Id of dweet /// @return status status of action NP-BAN_FREE function getReportedDweetStatus(uint _dweetId) public view onlyAllowedUser(msg.sender) returns(reportAction status){ return(actionOnDweet[_dweetId]); } /* *******************************************Advertisement ************************************************************** */ uint public advertisementCost=96822938914524992; uint public totalAdvertisements=0; uint[] private advertisementsList; enum AdApprovalStatus{NP, Approved, Rejected} struct Advertisement{ uint id; address advertiser; string imgHash; string link; AdApprovalStatus status;// Advertisement Approve or Rejected uint expiry; //timestamp to put expiry of Advertisement } modifier paidEnoughforAdvertisement() { require(msg.value >= advertisementCost); _;} modifier checkValueforAdvertisement() { _; uint amountToRefund = msg.value - advertisementCost; msg.sender.transfer(amountToRefund); } mapping(address=>uint[]) public advertiserAdvertisementsList; mapping(uint=>Advertisement) private advertisements; event logAdvertisementApproved(uint id, uint maintainer); event logAdvertisementRejected(uint id, uint maintainer); /// @notice Submit a new advertisement /// @param _imgHash Ipfs hash of image to be shown as advertisement /// @param _link Href link for the advertisement function submitAdvertisement(string memory _imgHash, string memory _link) public payable onlyAllowedUser(msg.sender) paidEnoughforAdvertisement checkValueforAdvertisement{ totalAdvertisements=totalAdvertisements.add(1); uint id=totalAdvertisements; advertisements[id]=Advertisement(id, msg.sender, _imgHash, _link, AdApprovalStatus.NP, 0); advertisementsList.push(id); advertiserAdvertisementsList[msg.sender].push(id); } /// @notice Approve or reject advertisements /// @param _id Id of advertisement /// @param _decision Approval decision Accepted or Rejected, true or false function advertisementApproval(uint _id, bool _decision) public onlyMaintainer{ require(advertisements[_id].status==AdApprovalStatus.NP,"Approval already given!"); if(_decision){ advertisements[_id].status=AdApprovalStatus.Approved; advertisements[_id].expiry=block.timestamp.add(1 days); emit logAdvertisementApproved(_id,maintainerId[msg.sender]); }else{ advertisements[_id].status=AdApprovalStatus.Rejected; uint refund=advertisementCost.mul(8).div(100); msg.sender.transfer(refund); emit logAdvertisementRejected(_id,maintainerId[msg.sender]); } } /// @notice Get all ads submitted on platform /// @return list Array of advertisement ids function getAds() public view onlyAllowedUser(msg.sender) returns(uint[] memory list){ return(advertisementsList); } /// @notice Get details of a advertisement /// @param _id Id of advertisement /// @return advertiser address of advertiser /// @return imgHash Ipfs hash of advertisement image /// @return link Href link of advertisement /// @return status Approval status of advertisements /// @return expiry advertisement expiry timestamp function getAd(uint _id) public view onlyAllowedUser(msg.sender) returns(address advertiser, string memory imgHash, string memory link, AdApprovalStatus status, uint expiry){ return(advertisements[_id].advertiser, advertisements[_id].imgHash, advertisements[_id].link, advertisements[_id].status, advertisements[_id].expiry); } /// @notice Get advertisement done by user /// @return list Array of advertisement ids function myAdvertisements() public view onlyAllowedUser(msg.sender) returns(uint[] memory list){ return(advertiserAdvertisementsList[msg.sender]); } /// @notice Status of a advertisement /// @param _id Id of advertisement /// @return status Approval status accepted or rejected function getAdvertisementStatus(uint _id) public view onlyAllowedUser(msg.sender) returns(AdApprovalStatus status){ return advertisements[_id].status; } /* ****************************************Owner Admin ****************************************************************************************** */ /// @notice Get balance of contract /// @return balance balance of contract function getBalance()public view onlyOwner() returns(uint balance){ return address(this).balance; } /// @notice Withdraw contract funds to owner /// @param _amount Amount to be withdrawn function transferContractBalance(uint _amount)public onlyOwner{ require(_amount<=address(this).balance,"Withdraw amount greater than balance"); msg.sender.transfer(_amount); } function stopDapp() public onlyOwner{ require(!stopped,"Already stopped"); stopped=true; } function startDapp() public onlyOwner{ require(stopped,"Already started"); stopped=false; } function changeOwner(address payable _newOwner) public onlyOwner{ owner=_newOwner; } }
@notice Claim right reporting reward @param _id Id of dweet on which reward is to be claimed
function claimReportingReward(uint _id) public onlyAllowedUser(msg.sender){ require(claimedReward[_id][msg.sender]==userdweetReportingStatus.Reported,"You have not reported or already claimed"); require(userReportList[msg.sender].length>0); require(actionOnDweet[_id]==reportAction.Banned,"Not eligible for reward, Dweet has been freed my mainatiners"); msg.sender.transfer(reportingRewardPrice); }
7,226,660
[ 1, 9762, 2145, 16096, 19890, 225, 389, 350, 3124, 434, 302, 18028, 603, 1492, 19890, 353, 358, 506, 7516, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 29285, 17631, 1060, 12, 11890, 389, 350, 13, 1071, 1338, 5042, 1299, 12, 3576, 18, 15330, 15329, 203, 3639, 2583, 12, 14784, 329, 17631, 1060, 63, 67, 350, 6362, 3576, 18, 15330, 65, 631, 1355, 72, 18028, 29285, 1482, 18, 426, 1798, 10837, 6225, 1240, 486, 14010, 578, 1818, 7516, 329, 8863, 203, 3639, 2583, 12, 1355, 4820, 682, 63, 3576, 18, 15330, 8009, 2469, 34, 20, 1769, 203, 3639, 2583, 12, 1128, 1398, 40, 18028, 63, 67, 350, 65, 631, 6006, 1803, 18, 38, 10041, 10837, 1248, 21351, 364, 19890, 16, 463, 18028, 711, 2118, 28004, 3399, 2774, 270, 267, 414, 8863, 203, 3639, 1234, 18, 15330, 18, 13866, 12, 20904, 17631, 1060, 5147, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.5.12; contract DSPauseAbstract { function SETOWNER297(address) external; //inject NONSTANDARD NAMING function SETAUTHORITY462(address) external; //inject NONSTANDARD NAMING function SETDELAY997(uint256) external; //inject NONSTANDARD NAMING function PLANS194(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function PROXY33() external view returns (address); //inject NONSTANDARD NAMING function DELAY572() external view returns (uint256); //inject NONSTANDARD NAMING function PLOT308(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING function DROP835(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING function EXEC528(address, bytes32, bytes calldata, uint256) external returns (bytes memory); //inject NONSTANDARD NAMING } contract JugAbstract { function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY27(address) external; //inject NONSTANDARD NAMING function DENY29(address) external; //inject NONSTANDARD NAMING function ILKS89(bytes32) external view returns (uint256, uint256); //inject NONSTANDARD NAMING function VAT322() external view returns (address); //inject NONSTANDARD NAMING function VOW865() external view returns (address); //inject NONSTANDARD NAMING function BASE98() external view returns (address); //inject NONSTANDARD NAMING function INIT382(bytes32) external; //inject NONSTANDARD NAMING function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE935(bytes32, address) external; //inject NONSTANDARD NAMING function DRIP851(bytes32) external returns (uint256); //inject NONSTANDARD NAMING } contract VatAbstract { function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY27(address) external; //inject NONSTANDARD NAMING function DENY29(address) external; //inject NONSTANDARD NAMING function CAN701(address, address) external view returns (uint256); //inject NONSTANDARD NAMING function HOPE401(address) external; //inject NONSTANDARD NAMING function NOPE804(address) external; //inject NONSTANDARD NAMING function ILKS89(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); //inject NONSTANDARD NAMING function URNS72(bytes32, address) external view returns (uint256, uint256); //inject NONSTANDARD NAMING function GEM847(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING function DAI766(address) external view returns (uint256); //inject NONSTANDARD NAMING function SIN979(address) external view returns (uint256); //inject NONSTANDARD NAMING function DEBT96() external view returns (uint256); //inject NONSTANDARD NAMING function VICE796() external view returns (uint256); //inject NONSTANDARD NAMING function LINE365() external view returns (uint256); //inject NONSTANDARD NAMING function LIVE39() external view returns (uint256); //inject NONSTANDARD NAMING function INIT382(bytes32) external; //inject NONSTANDARD NAMING function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING function CAGE573() external; //inject NONSTANDARD NAMING function SLIP893(bytes32, address, int256) external; //inject NONSTANDARD NAMING function FLUX455(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING function MOVE486(address, address, uint256) external; //inject NONSTANDARD NAMING function FROB749(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING function FORK68(bytes32, address, address, int256, int256) external; //inject NONSTANDARD NAMING function GRAB867(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING function HEAL281(uint256) external; //inject NONSTANDARD NAMING function SUCK979(address, address, uint256) external; //inject NONSTANDARD NAMING function FOLD739(bytes32, address, int256) external; //inject NONSTANDARD NAMING } contract VowAbstract { function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY27(address usr) external; //inject NONSTANDARD NAMING function DENY29(address usr) external; //inject NONSTANDARD NAMING function VAT322() external view returns (address); //inject NONSTANDARD NAMING function FLAPPER608() external view returns (address); //inject NONSTANDARD NAMING function FLOPPER190() external view returns (address); //inject NONSTANDARD NAMING function SIN979(uint256) external view returns (uint256); //inject NONSTANDARD NAMING function SIN979() external view returns (uint256); //inject NONSTANDARD NAMING function ASH807() external view returns (uint256); //inject NONSTANDARD NAMING function WAIT426() external view returns (uint256); //inject NONSTANDARD NAMING function DUMP329() external view returns (uint256); //inject NONSTANDARD NAMING function SUMP140() external view returns (uint256); //inject NONSTANDARD NAMING function BUMP430() external view returns (uint256); //inject NONSTANDARD NAMING function HUMP834() external view returns (uint256); //inject NONSTANDARD NAMING function LIVE39() external view returns (uint256); //inject NONSTANDARD NAMING function FILE935(bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE935(bytes32, address) external; //inject NONSTANDARD NAMING function FESS945(uint256) external; //inject NONSTANDARD NAMING function FLOG837(uint256) external; //inject NONSTANDARD NAMING function HEAL281(uint256) external; //inject NONSTANDARD NAMING function KISS865(uint256) external; //inject NONSTANDARD NAMING function FLOP497() external returns (uint256); //inject NONSTANDARD NAMING function FLAP923() external returns (uint256); //inject NONSTANDARD NAMING function CAGE573() external; //inject NONSTANDARD NAMING } contract IlkRegistryAbstract { function WARDS993(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY27(address) external; //inject NONSTANDARD NAMING function DENY29(address) external; //inject NONSTANDARD NAMING function VAT322() external view returns (address); //inject NONSTANDARD NAMING function CAT738() external view returns (address); //inject NONSTANDARD NAMING function SPOT274() external view returns (address); //inject NONSTANDARD NAMING function ILKDATA365(bytes32) external view returns ( //inject NONSTANDARD NAMING uint256, address, address, address, address, uint256, string memory, string memory ); function ILKS89() external view returns (bytes32[] memory); //inject NONSTANDARD NAMING function ILKS89(uint) external view returns (bytes32); //inject NONSTANDARD NAMING function ADD269(address) external; //inject NONSTANDARD NAMING function REMOVE614(bytes32) external; //inject NONSTANDARD NAMING function REMOVEAUTH234(bytes32) external; //inject NONSTANDARD NAMING function FILE935(bytes32, bytes32, address) external; //inject NONSTANDARD NAMING function FILE935(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE935(bytes32, bytes32, string calldata) external; //inject NONSTANDARD NAMING function COUNT649() external view returns (uint256); //inject NONSTANDARD NAMING function LIST141() external view returns (bytes32[] memory); //inject NONSTANDARD NAMING function LIST141(uint256, uint256) external view returns (bytes32[] memory); //inject NONSTANDARD NAMING function GET51(uint256) external view returns (bytes32); //inject NONSTANDARD NAMING function INFO652(bytes32) external view returns ( //inject NONSTANDARD NAMING string memory, string memory, uint256, address, address, address, address ); function POS804(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function GEM847(bytes32) external view returns (address); //inject NONSTANDARD NAMING function PIP889(bytes32) external view returns (address); //inject NONSTANDARD NAMING function JOIN697(bytes32) external view returns (address); //inject NONSTANDARD NAMING function FLIP981(bytes32) external view returns (address); //inject NONSTANDARD NAMING function DEC837(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING function SYMBOL988(bytes32) external view returns (string memory); //inject NONSTANDARD NAMING function NAME950(bytes32) external view returns (string memory); //inject NONSTANDARD NAMING } contract SpellAction { // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/c8e9f709f4bc5d0384b47e0109eb7555f08b84fc/governance/votes/Executive%20vote%20-%20August%2014%2C%202020.md -q -O - 2>/dev/null)" string constant public description524 = //inject NONSTANDARD NAMING "2020-08-14 MakerDAO Weekly Executive Spell | Hash: 0x97294bc0de2100192a54a618351a84574e5d1998da234152e68b4065ac9bea0f"; // MAINNET ADDRESSES // // The contracts in this list should correspond to MCD core contracts, verify // against the current release list at: // https://changelog.makerdao.com/releases/mainnet/1.0.9/contracts.json address constant mcd_vat35 = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; //inject NONSTANDARD NAMING address constant mcd_jug497 = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; //inject NONSTANDARD NAMING address constant mcd_vow892 = 0xA950524441892A31ebddF91d3cEEFa04Bf454466; //inject NONSTANDARD NAMING address constant ilk_registry964 = 0xbE4F921cdFEf2cF5080F9Cf00CC2c14F1F96Bd07; //inject NONSTANDARD NAMING uint256 constant million677 = 10 ** 6; //inject NONSTANDARD NAMING uint256 constant rad54 = 10 ** 45; //inject NONSTANDARD NAMING // Many of the settings that change weekly rely on the rate accumulator // described at https://docs.makerdao.com/smart-contract-modules/rates-module // To check this yourself, use the following rate calculation (example 6%): // // $ bc -l <<< 'scale=27; e( l(1.06)/(60 * 60 * 24 * 365) )' // uint256 constant six_pct_rate891 = 1000000001847694957439350562; //inject NONSTANDARD NAMING uint256 constant fortyfour_pct_rate631 = 1000000011562757347033522598; //inject NONSTANDARD NAMING function EXECUTE336() external { //inject NONSTANDARD NAMING bytes32[] memory ilks = IlkRegistryAbstract(ilk_registry964).LIST141(); for(uint i = 0; i < ilks.length; i++) { // Set all ilks dust value from 20 Dai to 100 Dai VatAbstract(mcd_vat35).FILE935(ilks[i], "dust", 100 * rad54); } // Set the MANA-A stability fee // value is determined by the rate accumulator calculation (see above) // ex. an 8% annual rate will be 1000000002440418608258400030 // // Existing Rate: 8% // New Rate: 6% JugAbstract(mcd_jug497).DRIP851("MANA-A"); JugAbstract(mcd_jug497).FILE935("MANA-A", "duty", six_pct_rate891); // Set the USDC-B stability fee // value is determined by the rate accumulator calculation (see above) // ex. an 8% annual rate will be 1000000002440418608258400030 // // Existing Rate: 46% // New Rate: 44% JugAbstract(mcd_jug497).DRIP851("USDC-B"); JugAbstract(mcd_jug497).FILE935("USDC-B", "duty", fortyfour_pct_rate631); // Sets the system surplus buffer from 500k Dai to 2mm Dai VowAbstract(mcd_vow892).FILE935("hump", 2 * million677 * rad54); } } contract DssSpell { DSPauseAbstract public pause = DSPauseAbstract(0xbE286431454714F511008713973d3B053A2d38f3); address public action; bytes32 public tag; uint256 public eta; bytes public sig; uint256 public expiration; bool public done; constructor() public { sig = abi.encodeWithSignature("execute()"); action = address(new SpellAction()); bytes32 _tag; address _action = action; assembly { _tag := extcodehash(_action) } tag = _tag; expiration = now + 30 days; } function DESCRIPTION887() public view returns (string memory) { //inject NONSTANDARD NAMING return SpellAction(action).description524(); } function SCHEDULE900() public { //inject NONSTANDARD NAMING require(now <= expiration, "This contract has expired"); require(eta == 0, "This spell has already been scheduled"); eta = now + DSPauseAbstract(pause).DELAY572(); pause.PLOT308(action, tag, sig, eta); } function CAST355() public { //inject NONSTANDARD NAMING require(!done, "spell-already-cast"); done = true; pause.EXEC528(action, tag, sig, eta); } }
inject NONSTANDARD NAMING
function DELAY572() external view returns (uint256);
12,918,526
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2030, 7868, 25, 9060, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {ICurveDeposit, ICurve, IUtil} from "../../interfaces/ICurve.sol"; import {ICore} from "../../interfaces/ICore.sol"; import {IPeak} from "../../interfaces/IPeak.sol"; import {Uni} from "../../interfaces/Uni.sol"; import {Initializable} from "../../common/Initializable.sol"; import {OwnableProxy} from "../../common/OwnableProxy.sol"; import {IGauge, IMintr} from "./IGauge.sol"; contract CurveSusdPeak is OwnableProxy, Initializable, IPeak { using SafeERC20 for IERC20; using SafeMath for uint; using Math for uint; uint constant MAX = uint(-1); uint constant N_COINS = 4; string constant ERR_SLIPPAGE = "They see you slippin"; uint[N_COINS] ZEROES = [uint(0),uint(0),uint(0),uint(0)]; address[N_COINS] underlyingCoins; uint[N_COINS] feed; ICurveDeposit curveDeposit; // deposit contract ICurve curve; // swap contract IERC20 curveToken; // LP token contract IUtil util; IGauge gauge; IMintr mintr; ICore core; function migrate(address destinationPeak, uint sCrv) public onlyOwner { if (sCrv == 0) { sCrv = gauge.balanceOf(address(this)); } // withdraw from gauge gauge.withdraw(sCrv, false); // remove liquidity from sPool sCrv = curveToken.balanceOf(address(this)); curve.remove_liquidity(sCrv, ZEROES); // swap sUSD for tether uint sUSD = IERC20(underlyingCoins[3]).balanceOf((address(this))); IERC20(underlyingCoins[3]).safeApprove(address(curve), 0); IERC20(underlyingCoins[3]).safeApprove(address(curve), sUSD); curve.exchange(int128(3), int128(2), sUSD, 0); // Add liquidity to yPool ICurveDeposit y = ICurveDeposit(0xbBC81d23Ea2c3ec7e56D39296F0cbB648873a5d3); uint[4] memory amounts; for (uint i = 0; i < 3; i++) { amounts[i] = IERC20(underlyingCoins[i]).balanceOf((address(this))); IERC20(underlyingCoins[i]).safeApprove(address(y), 0); IERC20(underlyingCoins[i]).safeApprove(address(y), amounts[i]); } y.add_liquidity(amounts, 0); IERC20 yCrv = IERC20(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); uint bal = yCrv.balanceOf(address(this)); (,,uint8 state) = core.peaks(destinationPeak); require(state == 1, "Not a valid peak"); yCrv.safeTransfer(destinationPeak, bal); } function initialize( ICurveDeposit _curveDeposit, ICurve _curve, IERC20 _curveToken, ICore _core, IUtil _util, IGauge _gauge, IMintr _mintr, address[N_COINS] memory _underlyingCoins ) public notInitialized { curveDeposit = _curveDeposit; curve = _curve; curveToken = _curveToken; core = _core; util = _util; gauge = _gauge; mintr = _mintr; underlyingCoins = _underlyingCoins; replenishApprovals(MAX); } /** * @dev Mint DUSD * @param inAmounts Exact inAmounts in the same order as required by the curve pool * @param minDusdAmount Minimum DUSD to mint, used for capping slippage */ function mint(uint[N_COINS] calldata inAmounts, uint minDusdAmount) external returns (uint dusdAmount) { address[N_COINS] memory coins = underlyingCoins; for (uint i = 0; i < N_COINS; i++) { if (inAmounts[i] > 0) { IERC20(coins[i]).safeTransferFrom(msg.sender, address(this), inAmounts[i]); } } dusdAmount = _mint(inAmounts, minDusdAmount); stake(); } function _mint(uint[N_COINS] memory inAmounts, uint minDusdAmount) internal returns (uint dusdAmount) { uint _old = portfolioValue(); curve.add_liquidity(inAmounts, 0); uint _new = portfolioValue(); dusdAmount = core.mint(_new.sub(_old), msg.sender); require(dusdAmount >= minDusdAmount, ERR_SLIPPAGE); } /** * @notice Mint DUSD with Curve LP tokens * @param inAmount Exact amount of Curve LP tokens * @param minDusdAmount Minimum DUSD to mint, used for capping slippage */ function mintWithScrv(uint inAmount, uint minDusdAmount) external returns (uint dusdAmount) { curveToken.safeTransferFrom(msg.sender, address(this), inAmount); dusdAmount = core.mint(sCrvToUsd(inAmount), msg.sender); require(dusdAmount >= minDusdAmount, ERR_SLIPPAGE); _stake(inAmount); } /** * @dev Redeem DUSD * @param dusdAmount Exact dusdAmount to burn * @param minAmounts Min expected amounts to cap slippage */ function redeem(uint dusdAmount, uint[N_COINS] calldata minAmounts) external { uint sCrv = _secureFunding(core.redeem(dusdAmount, msg.sender)); curve.remove_liquidity(sCrv, ZEROES); address[N_COINS] memory coins = underlyingCoins; IERC20 coin; uint toTransfer; for (uint i = 0; i < N_COINS; i++) { coin = IERC20(coins[i]); toTransfer = coin.balanceOf(address(this)); require(toTransfer >= minAmounts[i], ERR_SLIPPAGE); coin.safeTransfer(msg.sender, toTransfer); } } function redeemInSingleCoin(uint dusdAmount, uint i, uint minOut) external { uint sCrv = _secureFunding(core.redeem(dusdAmount, msg.sender)); curveDeposit.remove_liquidity_one_coin(sCrv, int128(i), minOut); IERC20 coin = IERC20(underlyingCoins[i]); uint toTransfer = coin.balanceOf(address(this)); require(toTransfer >= minOut, ERR_SLIPPAGE); coin.safeTransfer(msg.sender, toTransfer); } function redeemInScrv(uint dusdAmount, uint minOut) external { uint sCrv = _secureFunding(core.redeem(dusdAmount, msg.sender)); require(sCrv >= minOut, ERR_SLIPPAGE); curveToken.safeTransfer(msg.sender, sCrv); } /** * @notice Stake in sCrv Gauge */ function stake() public { _stake(curveToken.balanceOf(address(this))); } // thank you Andre :) function harvest(bool shouldClaim, uint minDusdAmount) external onlyOwner returns(uint) { if (shouldClaim) { claimRewards(); } address uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address[] memory path = new address[](3); path[1] = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // weth address __crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); IERC20 crv = IERC20(__crv); uint _crv = crv.balanceOf(address(this)); uint _usdt; if (_crv > 0) { crv.safeApprove(uni, 0); crv.safeApprove(uni, _crv); path[0] = __crv; address __usdt = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); path[2] = __usdt; Uni(uni).swapExactTokensForTokens(_crv, uint(0), path, address(this), now.add(1800)); _usdt = IERC20(__usdt).balanceOf(address(this)); } address __snx = address(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F); IERC20 snx = IERC20(__snx); uint _snx = snx.balanceOf(address(this)); uint _usdc; if (_snx > 0) { snx.safeApprove(uni, 0); snx.safeApprove(uni, _snx); path[0] = __snx; address __usdc = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); path[2] = __usdc; Uni(uni).swapExactTokensForTokens(_snx, uint(0), path, address(this), now.add(1800)); _usdc = IERC20(__usdc).balanceOf(address(this)); } return _mint([0,_usdc,_usdt,0], minDusdAmount); } function getRewards(address[] calldata tokens, address destination) external onlyOwner { claimRewards(); for (uint i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i]); require( address(token) != address(curveToken), "Admin can't withdraw curve lp tokens" ); token.safeTransfer(destination, token.balanceOf(address(this))); } } function claimRewards() public { mintr.mint(address(gauge)); gauge.claim_rewards(); } function replenishApprovals(uint value) public { curveToken.safeIncreaseAllowance(address(curveDeposit), value); curveToken.safeIncreaseAllowance(address(gauge), value); for (uint i = 0; i < N_COINS; i++) { IERC20(underlyingCoins[i]).safeIncreaseAllowance(address(curve), value); } } /* ##### View Functions ##### */ function calcMint(uint[N_COINS] memory inAmounts) public view returns (uint dusdAmount) { return sCrvToUsd(curve.calc_token_amount(inAmounts, true /* deposit */)); } function calcMintWithScrv(uint inAmount) public view returns (uint dusdAmount) { return sCrvToUsd(inAmount); } function calcRedeem(uint dusdAmount) public view returns(uint[N_COINS] memory amounts) { uint usd = core.dusdToUsd(dusdAmount, true); uint exchangeRate = sCrvToUsd(1e18); uint sCrv = usd.mul(1e18).div(exchangeRate); uint totalSupply = curveToken.totalSupply(); for(uint i = 0; i < N_COINS; i++) { amounts[i] = curve.balances(int128(i)).mul(sCrv).div(totalSupply); } } function calcRedeemWithScrv(uint dusdAmount) public view returns(uint amount) { uint usd = core.dusdToUsd(dusdAmount, true); uint exchangeRate = sCrvToUsd(1e18); amount = usd.mul(1e18).div(exchangeRate); } function calcRedeemInSingleCoin(uint dusdAmount, uint i) public view returns(uint amount) { uint sCrv = usdToScrv(core.dusdToUsd(dusdAmount, true)); amount = curveDeposit.calc_withdraw_one_coin(sCrv, int128(i)); } function usdToScrv(uint usd) public view returns(uint sCrv) { uint exchangeRate = sCrvToUsd(1e18); if (exchangeRate > 0) { return usd.mul(1e18).div(exchangeRate); } } function portfolioValue() public view returns(uint) { return sCrvToUsd(sCrvBalance()); } function sCrvToUsd(uint sCrvBal) public view returns(uint) { return _sCrvToUsd(sCrvBal, feed); } function sCrvBalance() public view returns(uint) { return curveToken.balanceOf(address(this)) .add(gauge.balanceOf(address(this))); } function vars() public view returns( address _curveDeposit, address _curve, address _curveToken, address _util, address _gauge, address _mintr, address _core, address[N_COINS] memory _underlyingCoins, uint[N_COINS] memory _feed ) { return( address(curveDeposit), address(curve), address(curveToken), address(util), address(gauge), address(mintr), address(core), underlyingCoins, feed ); } /* ##### Internal Functions ##### */ function _sCrvToUsd(uint sCrvBal, uint[N_COINS] memory /* _feed */) internal view returns(uint) { return sCrvBal.mul(curve.get_virtual_price()).div(1e18); } function _secureFunding(uint usd) internal returns(uint sCrv) { sCrv = usdToScrv(usd).min(sCrvBalance()); // in an extreme scenario there might not be enough sCrv to redeem gauge.withdraw(sCrv, false); } function _stake(uint amount) internal { if (amount > 0) { gauge.deposit(amount); } } }
Add liquidity to yPool
ICurveDeposit y = ICurveDeposit(0xbBC81d23Ea2c3ec7e56D39296F0cbB648873a5d3);
2,576,539
[ 1, 986, 4501, 372, 24237, 358, 677, 2864, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 467, 9423, 758, 1724, 677, 273, 467, 9423, 758, 1724, 12, 20, 6114, 16283, 11861, 72, 4366, 41, 69, 22, 71, 23, 557, 27, 73, 4313, 40, 5520, 5540, 26, 42, 20, 7358, 38, 1105, 5482, 9036, 69, 25, 72, 23, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; /* Utilities & Common Modifiers */ contract Utils { // events for debugging event Trace(string _data); event TraceAddress(address _data); event TraceUint256(uint256 _data); event TraceUint(uint _data); event TraceBytes32(bytes32 _data); event TraceBool(bool _data); /** constructor */ function Utils() { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // verifies that x is smaller than y modifier smallerThan(uint _x, uint _y) { require(_x < _y); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != 0x0); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } }
/ events for debugging
contract Utils { event Trace(string _data); event TraceAddress(address _data); event TraceUint256(uint256 _data); event TraceUint(uint _data); event TraceBytes32(bytes32 _data); event TraceBool(bool _data); constructor Utilities & Common Modifiers function Utils() { } modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } modifier smallerThan(uint _x, uint _y) { require(_x < _y); _; } modifier validAddress(address _address) { require(_address != 0x0); _; } modifier notThis(address _address) { require(_address != address(this)); _; } }
12,793,631
[ 1, 19, 2641, 364, 10450, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6091, 288, 203, 203, 565, 871, 2677, 12, 1080, 389, 892, 1769, 203, 565, 871, 2677, 1887, 12, 2867, 389, 892, 1769, 203, 565, 871, 2677, 5487, 5034, 12, 11890, 5034, 389, 892, 1769, 203, 565, 871, 2677, 5487, 12, 11890, 389, 892, 1769, 203, 565, 871, 2677, 2160, 1578, 12, 3890, 1578, 389, 892, 1769, 203, 565, 871, 2677, 7464, 12, 6430, 389, 892, 1769, 203, 203, 3639, 3885, 203, 565, 26703, 473, 5658, 3431, 3383, 203, 565, 445, 6091, 1435, 288, 203, 565, 289, 203, 377, 203, 203, 565, 9606, 6802, 9516, 7170, 12, 11890, 5034, 389, 8949, 13, 288, 203, 3639, 2583, 24899, 8949, 405, 374, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 10648, 9516, 12, 11890, 389, 92, 16, 2254, 389, 93, 13, 288, 203, 3639, 2583, 24899, 92, 411, 389, 93, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 923, 1887, 12, 2867, 389, 2867, 13, 288, 203, 3639, 2583, 24899, 2867, 480, 374, 92, 20, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 486, 2503, 12, 2867, 389, 2867, 13, 288, 203, 3639, 2583, 24899, 2867, 480, 1758, 12, 2211, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./IFactoryERC721.sol"; import "./Token.sol"; /** * @title The Mike Tyson NFT Collection by Cory Van Lew * An NFT powered by Ether Cards - https://ether.cards */ contract TokenFactory is FactoryERC721, Ownable { using Strings for string; event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); uint256 public HG2G = 42; address public proxyRegistryAddress; address public nftAddress; string public baseURI = "https://client-metadata.ether.cards/api/tyson/collection/"; constructor(address _proxyRegistryAddress, address _nftAddress) { proxyRegistryAddress = _proxyRegistryAddress; nftAddress = _nftAddress; fireTransferEvents(address(0), owner()); } function name() override external pure returns (string memory) { return "The Mike Tyson NFT Collection Sale"; } function symbol() override external pure returns (string memory) { return "TNFT"; } function supportsFactoryInterface() override public pure returns (bool) { return true; } function numOptions() override public view returns (uint256) { Token token = Token(nftAddress); return token.numSeries(); } function transferOwnership(address newOwner) override public onlyOwner { address _prevOwner = owner(); super.transferOwnership(newOwner); fireTransferEvents(_prevOwner, newOwner); } function fireTransferEvents(address _from, address _to) private { for (uint256 i = 0; i < numOptions(); i++) { emit Transfer(_from, _to, i); } } function mint(uint256 _optionId, address _toAddress) override public { // Must be sent from the owner proxy or owner. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); assert( address(proxyRegistry.proxies(owner())) == _msgSender() || owner() == _msgSender() ); Token token = Token(nftAddress); require(_optionId < numOptions(), "Series does not exist"); require(token.available(_optionId) > 0, "No more tokens available in this series"); token.mintTo(_toAddress,_optionId); } function canMint(uint256 _optionId) override public view returns (bool) { Token token = Token(nftAddress); if (_optionId >= numOptions()) { return false; } return token.available(_optionId) > 0; } function tokenURI(uint256 _optionId) override external view returns (string memory) { return string(abi.encodePacked(baseURI, Strings.toString(_optionId))); } /** * Hack to get things to work automatically on OpenSea. * Use transferFrom so the frontend doesn't have to worry about different method names. */ function transferFrom( address _from, address _to, uint256 _tokenId ) public { mint(_tokenId, _to); } function setBaseURI(string memory _base) external onlyOwner { baseURI = _base; } /** * Hack to get things to work automatically on OpenSea. * Use isApprovedForAll so the frontend doesn't have to worry about different method names. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { if (owner() == _owner && _owner == _operator) { return true; } ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if ( owner() == _owner && address(proxyRegistry.proxies(_owner)) == _operator ) { return true; } return false; } /** * Hack to get things to work automatically on OpenSea. * Use isApprovedForAll so the frontend doesn't have to worry about different method names. */ function ownerOf(uint256 _tokenId) public view returns (address _owner) { return owner(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @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. */ abstract 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() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual 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 virtual onlyOwner { _setOwner(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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * This is a generic factory contract that can be used to mint tokens. The configuration * for minting is specified by an _optionId, which can be used to delineate various * ways of minting. */ interface FactoryERC721 { /** * Returns the name of this factory. */ function name() external view returns (string memory); /** * Returns the symbol for this factory. */ function symbol() external view returns (string memory); /** * Number of options the factory supports. */ function numOptions() external view returns (uint256); /** * @dev Returns whether the option ID can be minted. Can return false if the developer wishes to * restrict a total supply per option ID (or overall). */ function canMint(uint256 _optionId) external view returns (bool); /** * @dev Returns a URL specifying some metadata about the option. This metadata can be of the * same structure as the ERC721 metadata. */ function tokenURI(uint256 _optionId) external view returns (string memory); /** * Indicates that this is a factory contract. Ideally would use EIP 165 supportsInterface() */ function supportsFactoryInterface() external view returns (bool); /** * @dev Mints asset(s) in accordance to a specific address with a particular "option". This should be * callable only by the contract owner or the owner's Wyvern Proxy (later universal login will solve this). * Options should also be delineated 0 - (numOptions() - 1) for convenient indexing. * @param _optionId the option id * @param _toAddress address of the future owner of the asset(s) */ function mint(uint256 _optionId, address _toAddress) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Tradable.sol"; /** * @title The Mike Tyson NFT Collection by Cory Van Lew * An NFT powered by Ether Cards - https://ether.cards */ contract Token is ERC721Tradable { string _tokenURI = "https://client-metadata.ether.cards/api/tyson/"; string _contractURI = "https://client-metadata.ether.cards/api/tyson/contract"; uint256 public HG2G = 42; constructor(address _proxyRegistryAddress) ERC721Tradable("The Mike Tyson NFT Collection by Cory Van Lew", "TYSON", _proxyRegistryAddress) {} function baseTokenURI() override public view returns (string memory) { return _tokenURI; } function setTokenURI(string memory _uri) external onlyOwner { _tokenURI = _uri; } function contractURI() public view returns (string memory) { return _contractURI; } function setContractURI(string memory _uri) external onlyOwner { _contractURI = _uri; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 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. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./common/meta-transactions/ContentMixin.sol"; import "./common/meta-transactions/NativeMetaTransaction.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; mapping (address => bool) operators; mapping (uint256 => uint256) tokenToSeries; struct Series { string name; string baseURI; uint256 start; uint256 current; uint256 supply; } Series[] collections; event NewCollection(uint256 collection_id,string name,string baseURI,uint256 start,uint256 supply); constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } modifier ownerOrOperator() { require(msgSender() == owner() || operators[msgSender()],"caller is neither the owner nor the operator"); _; } function setOperator(address _operator, bool status) external onlyOwner { if (status) { operators[_operator] = status; } else { delete operators[_operator]; } } function addSeries( string[] memory _names, string[] memory baseURIs, uint256[] memory _starts, uint256[] memory _supplys ) external onlyOwner { require (_names.length == baseURIs.length, "len 1 & 2 not equal"); require (_names.length == _starts.length, "len 1 & 3 not equal"); require (_names.length == _supplys.length, "len 1 & 4 not equal"); for (uint j = 0; j < _names.length; j++){ collections.push(Series(_names[j],baseURIs[j],_starts[j],0, _supplys[j])); emit NewCollection(collections.length-1,_names[j],baseURIs[j],_starts[j], _supplys[j]); } } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function preMintTo(address _to, uint256[] memory _seriesz) public ownerOrOperator { for (uint j = 0; j < _seriesz.length; j++){ uint256 collection = _seriesz[j]; require(collection < collections.length, "Invalid Collection"); uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to, uint256 collection) public ownerOrOperator { require(collection < collections.length, "Invalid Collection"); uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } function privateMint(address _to, uint256 collection) public onlyOwner { require(collections[collection].supply == 250,"Wrong collection"); for (uint i = 0; i < 25; i++) { uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId(uint256 collection) private returns (uint256) { Series storage coll = collections[collection]; uint pointer = coll.current++; require(pointer < coll.supply, "No tokens available"); uint256 reply = coll.start + pointer; return reply; } /** * @dev increments the value of _currentTokenId */ function baseTokenURI() virtual public view returns (string memory); function seriesURI(uint256 collection) public view returns (string memory) { require(collection < collections.length, "Invalid Collection"); return collections[collection].baseURI; } function seriesStart(uint256 collection) internal view returns (uint256) { require(collection < collections.length, "Invalid Collection"); return collections[collection].start; } function seriesName(uint256 collection) public view returns (string memory) { require(collection < collections.length, "Invalid Collection"); return collections[collection].name; } function tokenURI(uint256 _tokenId) override public view returns (string memory) { require(_exists(_tokenId),"Token does not exist"); uint256 collection = tokenToSeries[_tokenId]; uint256 adjustedID = _tokenId - seriesStart(collection)+1; return string(abi.encodePacked(baseTokenURI(),seriesURI(collection),"/", Strings.toString(adjustedID))); } function numSeries() external view returns (uint256) { return collections.length; } function available(uint256 collectionId) external view returns (uint256) { require(collectionId < collections.length, "Invalid Collection"); Series memory coll = collections[collectionId]; return coll.supply - coll.current; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address _owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == operator) { return true; } return super.isApprovedForAll(_owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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 a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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 a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting 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) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import {EIP712Base} from "./EIP712Base.sol"; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @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"); (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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Initializable} from "./Initializable.sol"; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } }
* @dev Mints a token to an address with a tokenURI. @param _to address of the future owner of the token/
function preMintTo(address _to, uint256[] memory _seriesz) public ownerOrOperator { for (uint j = 0; j < _seriesz.length; j++){ uint256 collection = _seriesz[j]; require(collection < collections.length, "Invalid Collection"); uint256 newTokenId = _getNextTokenId(collection); _mint(_to, newTokenId); tokenToSeries[newTokenId] = collection; } }
592,984
[ 1, 49, 28142, 279, 1147, 358, 392, 1758, 598, 279, 1147, 3098, 18, 225, 389, 869, 1758, 434, 326, 3563, 3410, 434, 326, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 675, 49, 474, 774, 12, 2867, 389, 869, 16, 2254, 5034, 8526, 3778, 389, 10222, 94, 13, 1071, 3410, 1162, 5592, 288, 203, 3639, 364, 261, 11890, 525, 273, 374, 31, 525, 411, 389, 10222, 94, 18, 2469, 31, 525, 27245, 95, 203, 5411, 2254, 5034, 1849, 273, 389, 10222, 94, 63, 78, 15533, 203, 5411, 2583, 12, 5548, 411, 6980, 18, 2469, 16, 315, 1941, 2200, 8863, 203, 5411, 2254, 5034, 394, 1345, 548, 273, 389, 588, 9399, 548, 12, 5548, 1769, 203, 5411, 389, 81, 474, 24899, 869, 16, 394, 1345, 548, 1769, 203, 5411, 1147, 774, 6485, 63, 2704, 1345, 548, 65, 273, 1849, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright (C) 2017 ethbets * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ pragma solidity ^0.4.11; import './bet.sol'; import './governanceInterface.sol'; contract Ebets { modifier onlyOwner() { require(msg.sender == owner); _; } address owner; uint8 public constant TAX = 10; mapping (string => Bet[]) bets; //indexed by category /* TODO: ALSO FIRE CATEGORY EVENT * TODO: INDEX category! There is an issue with web3 that prevents us to do it * right now: https://github.com/ethereum/web3.js/issues/434 */ event createdBet(address betAddr, string category); function Ebets() { owner = msg.sender; } function createBet(GovernanceInterface arbiter, string team0Name, string team1Name, string category, uint[] timestamps) { Bet bet = new Bet(arbiter, team0Name, team1Name, timestamps, TAX); // Featured by default for resolver if (msg.sender == owner) bet.toggleFeatured(); bets[category].push(bet); createdBet(bet, category); } function modifyCategory(uint betIdx, string oldCategory, string newCategory) onlyOwner() { Bet bet = bets[oldCategory][betIdx]; removeBet(oldCategory, betIdx); bets[newCategory].push(bet); } function toggleFeatured(uint betIdx, string category) onlyOwner() { bets[category][betIdx].toggleFeatured(); } function getBetsByCategory(string category) constant returns(Bet[]) { return bets[category]; } function removeBet(string category, uint index) internal { bets[category][index] = bets[category][bets[category].length - 1]; delete bets[category][bets[category].length - 1]; } }
Featured by default for resolver
function createBet(GovernanceInterface arbiter, string team0Name, string team1Name, string category, uint[] timestamps) { Bet bet = new Bet(arbiter, team0Name, team1Name, timestamps, TAX); if (msg.sender == owner) bet.toggleFeatured(); bets[category].push(bet); createdBet(bet, category); }
7,238,562
[ 1, 4595, 72, 635, 805, 364, 5039, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 752, 38, 278, 12, 43, 1643, 82, 1359, 1358, 419, 70, 2165, 16, 533, 5927, 20, 461, 16, 203, 8227, 533, 5927, 21, 461, 16, 533, 3150, 16, 7010, 8227, 2254, 8526, 11267, 13, 288, 203, 203, 565, 605, 278, 2701, 273, 394, 605, 278, 12, 6779, 2165, 16, 5927, 20, 461, 16, 5927, 21, 461, 16, 11267, 16, 399, 2501, 1769, 203, 565, 309, 261, 3576, 18, 15330, 422, 3410, 13, 203, 1377, 2701, 18, 14401, 4595, 72, 5621, 203, 565, 324, 2413, 63, 4743, 8009, 6206, 12, 70, 278, 1769, 203, 565, 2522, 38, 278, 12, 70, 278, 16, 3150, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xB6EE8d1284773061b9bCb5Ba1E72d4f86477C412/sources/contracts/extension/Staking721Upgradeable.sol
@dev Withdraw logic. Override to add custom logic.
function _withdraw(uint256[] calldata _tokenIds) internal virtual { uint256 _amountStaked = stakers[msg.sender].amountStaked; uint256 len = _tokenIds.length; require(len != 0, "Withdrawing 0 tokens"); require(_amountStaked >= len, "Withdrawing more than staked"); _updateUnclaimedRewardsForStaker(msg.sender); if (_amountStaked == len) { for (uint256 i; i < stakersArray.length; ++i) { if (stakersArray[i] == msg.sender) { stakersArray[i] = stakersArray[stakersArray.length - 1]; stakersArray.pop(); } } } stakers[msg.sender].amountStaked -= len; for (uint256 i; i < len; ++i) { require(stakerAddress[_tokenIds[i]] == msg.sender, "Not staker"); stakerAddress[_tokenIds[i]] = address(0); IERC721(nftCollection).transferFrom(address(this), msg.sender, _tokenIds[i]); } emit TokensWithdrawn(msg.sender, _tokenIds); }
9,531,183
[ 1, 1190, 9446, 4058, 18, 1439, 358, 527, 1679, 4058, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1918, 9446, 12, 11890, 5034, 8526, 745, 892, 389, 2316, 2673, 13, 2713, 5024, 288, 203, 3639, 2254, 5034, 389, 8949, 510, 9477, 273, 384, 581, 414, 63, 3576, 18, 15330, 8009, 8949, 510, 9477, 31, 203, 3639, 2254, 5034, 562, 273, 389, 2316, 2673, 18, 2469, 31, 203, 3639, 2583, 12, 1897, 480, 374, 16, 315, 1190, 9446, 310, 374, 2430, 8863, 203, 3639, 2583, 24899, 8949, 510, 9477, 1545, 562, 16, 315, 1190, 9446, 310, 1898, 2353, 384, 9477, 8863, 203, 203, 3639, 389, 2725, 984, 14784, 329, 17631, 14727, 1290, 510, 6388, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 309, 261, 67, 8949, 510, 9477, 422, 562, 13, 288, 203, 5411, 364, 261, 11890, 5034, 277, 31, 277, 411, 384, 581, 414, 1076, 18, 2469, 31, 965, 77, 13, 288, 203, 7734, 309, 261, 334, 581, 414, 1076, 63, 77, 65, 422, 1234, 18, 15330, 13, 288, 203, 10792, 384, 581, 414, 1076, 63, 77, 65, 273, 384, 581, 414, 1076, 63, 334, 581, 414, 1076, 18, 2469, 300, 404, 15533, 203, 10792, 384, 581, 414, 1076, 18, 5120, 5621, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 3639, 384, 581, 414, 63, 3576, 18, 15330, 8009, 8949, 510, 9477, 3947, 562, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 562, 31, 965, 77, 13, 288, 203, 5411, 2583, 12, 334, 6388, 1887, 63, 67, 2316, 2673, 63, 77, 13563, 422, 1234, 18, 15330, 16, 315, 1248, 384, 6388, 8863, 203, 2 ]
pragma solidity ^0.4.11; //TODO: read security stuff //TODO: when placing a bid, do an inplace sort so that the final request doesn't run out of gas //SECURITY: Always change all variables and only as the very last act, transfer ether. //SECURITY: perform all bookkeeping on the same scope level in case malicious actor gets stack to 1024 and then you try to do something with function call and //it isn't atomic //SECURITY: use invariants to trigger safe mode if any of the invariants become inconsistent. //TODO: add modifier to allow owner to disable the entire contract in case I want to launch a newer version. //TODO: make a withdrawal function //TODO: Implement GetBounty with datafeed and decimla places //TODO: check how many pythia we can tolerate before gas becomes a problem /*Domain language: Post bounty, OfferKreshmoi, Reward bounty, Collect bounty reward, Successful kreshmoi */ //TODO: implement a GetBountyReward to check the reward offered on each bounty. import "./StringUtils.sol"; import "./PythiaBase.sol"; contract Pythia is PythiaBase { mapping (address => uint) rewardForSuccessfulProphecies; //stores the ether value of each successful kreshmoi. And yes, you can forget about reentrancy attacks. mapping (string => Kreshmoi[]) successfulKreshmoi; //key is USDETH or CPIXZA for instance mapping (string => Bounty[]) openBounties; mapping (address => uint) refundsForFailedBounties; mapping (address => uint) donations; mapping (string => string) datafeedDescriptions; mapping (string => uint) datafeedChangeCost; string[] datafeedNames; mapping (address => PostBountyDetails ) validationTickets; function Pythia() { } function() payable { donations[msg.sender] = msg.value; } function setDescription(string datafeed, string description) payable { uint index = 0; for (uint i = 0; i < datafeedNames.length; i++) { if (StringUtils.equal(datafeedNames[i], datafeed)) { index = i; break; } } if (index==0) { if (msg.value>=1) datafeedNames.push(datafeed); datafeedChangeCost[datafeed] = 1; datafeedDescriptions[datafeed] = description; } else if (msg.value>=datafeedChangeCost[datafeed]*2) { datafeedNames[index] = description; datafeedChangeCost[datafeed] *= 2; datafeedDescriptions[datafeed] = description; } } function getDatafeedNameChangeCost(string datafeed) returns (uint) { if (datafeedChangeCost[datafeed]==0) { return 1; } return datafeedChangeCost[datafeed]*2; } function getDescriptionByName(string datafeed) returns (string) { return datafeedDescriptions[datafeed]; } function getDescriptionByIndex(uint index) returns (string) { if (index<0 || index > datafeedNames.length) { Debugging("Index out of bounds"); return "ERROR: INDEX OUT OF BOUNDS"; } return datafeedNames[index]; } function generatePostBountyValidationTicket(string datafeed,uint8 requiredSampleSize,uint16 maxBlockRange,uint maxValueRange,uint8 decimalPlaces) payable { bool validationSuccess = true; if (msg.value/requiredSampleSize<1) { BountyValidationCheckFailed(datafeed,msg.sender,"ether reward too small"); validationSuccess = false; } if (requiredSampleSize<2) { BountyValidationCheckFailed(datafeed,msg.sender,"At least 2 predictions for an oracle to be considered a pythia"); validationSuccess = false; } if (validateDataFeedFails(datafeed,msg.sender)) { validationSuccess = false; } if (openBounties[datafeed].length>10) { BountListFull(datafeed); validationSuccess = false; } if (validationSuccess) { validationTickets[msg.sender] = PostBountyDetails({datafeed:datafeed, value:msg.value, sampleSize:requiredSampleSize, maxBlockRange:maxBlockRange, maxValueRange:maxValueRange, decimalPlaces:decimalPlaces, fresh:true}); } refundsForFailedBounties[msg.sender] += msg.value; ValidationTicketGenerated(msg.sender); } function pushOldBountiesOffCliff(string datafeed) { if (openBounties[datafeed].length>0) { address refundAddress = openBounties[datafeed][0].poster; uint refund = openBounties[datafeed][0].szaboRewardPerOracle*openBounties[datafeed][0].requiredSampleSize; refundsForFailedBounties[refundAddress] += refund*9/10; //spam prevention penalty for (uint i = 0;i<openBounties[datafeed].length-1;i++) { openBounties[datafeed][i] = openBounties[datafeed][i+1]; } delete openBounties[datafeed][openBounties[datafeed].length-1]; openBounties[datafeed].length--; } } function postBounty() payable { PostBountyDetails memory validationObject; if (validationTickets[msg.sender].fresh) { validationObject = validationTickets[msg.sender]; validationTickets[msg.sender].fresh= false; } else if (msg.value!=validationTickets[msg.sender].value) { InvalidBountyValidationTicket(msg.sender,validationTickets[msg.sender].datafeed); refundsForFailedBounties[msg.sender] += msg.value; return; } Bounty memory bounty = Bounty({ maxBlockRange:validationObject.maxBlockRange, maxValueRange:validationObject.maxValueRange, szaboRewardPerOracle:(msg.value/validationObject.sampleSize)/1 szabo, requiredSampleSize:validationObject.sampleSize, decimalPlaces:validationObject.decimalPlaces, predictions: new int64[](validationObject.sampleSize), oracles: new address[](validationObject.sampleSize), earliestBlock:0, poster: msg.sender }); openBounties[validationObject.datafeed].push(bounty); BountyPosted (msg.sender,validationObject.datafeed,bounty.szaboRewardPerOracle); } function getOracleReward() returns (uint) { return rewardForSuccessfulProphecies[msg.sender]*1 szabo; } function collectOracleReward() { uint reward = getOracleReward(); rewardForSuccessfulProphecies[msg.sender] = 0; msg.sender.transfer(reward); } function claimRefundsDue() { uint refund = refundsForFailedBounties[msg.sender]; refundsForFailedBounties[msg.sender] = 0; RefundProcessed(msg.sender); msg.sender.transfer(refund); } function getBounties(string datafeed) returns (uint8[] sampleSize,uint8[] decimalPlaces,uint[] rewardPerOracle) { for (uint i = 0; i<openBounties[datafeed].length;i++) { sampleSize[i] = openBounties[datafeed][i].requiredSampleSize; decimalPlaces[i] = openBounties[datafeed][i].decimalPlaces; rewardPerOracle[i] = openBounties[datafeed][i].szaboRewardPerOracle; } } function offerKreshmoi(string datafeed, uint8 index, int64 predictionValue) {//TODO: limiting factor on number of open bounties to participate in Bounty memory bounty = openBounties[datafeed][index]; if (bounty.earliestBlock==0 || block.number - uint(bounty.earliestBlock)>uint(bounty.maxBlockRange)) { clearBounty(datafeed,index,"Max block registers exceeded. All previous bounty hunters have been erased. Bounty reset at current block."); } int128[] memory registers = new int128[](4);//0 = smallest,1 = largest,2 = average value,3 = order of magnitude if (bounty.predictions.length>0) { registers[0] = bounty.predictions[0]; registers[1] = bounty.predictions[0]; } else { registers[0] = 0; registers[1] = 0; } for (uint j = 1;j<bounty.predictions.length;j++) { registers[2] += bounty.predictions[j]; if (registers[1] < bounty.predictions[j]) registers[1] = bounty.predictions[j]; if (registers[0] > bounty.predictions[j]) registers[0] = bounty.predictions[j]; } if (predictionValue > registers[1]) registers[1] = predictionValue; if (uint(registers[1]-registers[0])>bounty.maxValueRange) { clearBounty(datafeed,index,"The kreshmoi offered exceeded the maximum allowable registers for this bounty. All previous bounty hunters have been erased. Bounty reset at current block."); } for (j = 0;j < openBounties[datafeed][index].oracles.length;j++) { if (openBounties[datafeed][index].oracles[j]==msg.sender) { KreshmoiOfferFailed (msg.sender, datafeed, "oracle cannot post 2 predictions for same bounty"); return; } } openBounties[datafeed][index].predictions.push(predictionValue); openBounties[datafeed][index].oracles.push(msg.sender); if (openBounties[datafeed][index].predictions.length == bounty.requiredSampleSize) { registers[2] += predictionValue; registers[3] = 1; for (j = 0;j < openBounties[datafeed][index].decimalPlaces;j++) { registers[3]*=10; } registers[2] *= registers[3]; registers[2] /= openBounties[datafeed][index].requiredSampleSize; successfulKreshmoi[datafeed].push(Kreshmoi({ blockRange: uint16(block.number - openBounties[datafeed][index].earliestBlock), decimalPlaces:openBounties[datafeed][index].decimalPlaces, value: int64(registers[2]), sampleSize:openBounties[datafeed][index].requiredSampleSize, valueRange:uint(registers[1]-registers[0]), bountyPoster:openBounties[datafeed][index].poster })); address[] memory oracles = bounty.oracles; uint reward = bounty.szaboRewardPerOracle; for (j = 0;j<oracles.length;j++) { rewardForSuccessfulProphecies[oracles[j]] += reward; } delete openBounties[datafeed][index]; for (j = index;j<openBounties[datafeed].length-1;j++) { openBounties[datafeed][j] = openBounties[datafeed][j+1]; } KreshmoiOffered(msg.sender,datafeed); ProphecyDelivered(datafeed); return; } KreshmoiOffered(msg.sender,datafeed); } function getKreshmoi(string datafeed) returns (int64[],uint8[]) { int64[] memory values = new int64[](successfulKreshmoi[datafeed].length); uint8[] memory decimalPlaces = new uint8[](successfulKreshmoi[datafeed].length); for (uint i =0;i<successfulKreshmoi[datafeed].length;i++) { values[i] = successfulKreshmoi[datafeed][i].value; decimalPlaces[i] = successfulKreshmoi[datafeed][i].decimalPlaces; } return (values, decimalPlaces); } function clearBounty(string datafeed, uint index, string reason) internal { openBounties[datafeed][index].earliestBlock = block.number; delete openBounties[datafeed][index].predictions; delete openBounties[datafeed][index].oracles; BountyCleared(datafeed,index,reason); } function validateDataFeedFails(string datafeed, address sender) internal returns(bool) { bytes memory chararray = bytes(datafeed); if (chararray.length>10) { BountyValidationCheckFailed(datafeed, sender, "datafeed name must contain at most 10 characters"); return true; } if (chararray.length<3) { BountyValidationCheckFailed(datafeed, sender, "datafeed name must contain at least 3 characters"); return true; } string memory validString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; bytes memory validCharacterSet = bytes(validString); Debugging(datafeed); for (uint i = 0;i<chararray.length;i++) { bool existsInValidSet = false; for (uint j =0;j<36;j++) { if (chararray[i]==validCharacterSet[j]) existsInValidSet= true; } if (!existsInValidSet) { BountyValidationCheckFailed(datafeed, sender,"Characters must be uppercase alphanumeric."); return true; } } return false; } event Debugging(string message); event DebuggingUINT(string message,uint additional); event BountyValidationCheckFailed(string datafeed, address from, string reason); event InvalidBountyValidationTicket(address sender, string datafeed); event BountListFull(string datafeed); event BountyCleared(string datafeed, uint index, string reason); event BountyPosted (address from, string datafeed, uint rewardPerOracle); event KreshmoiOffered (address from, string datafeed); event KreshmoiOfferFailed (address from, string datafeed, string reason); event ProphecyDelivered (string datafeed); event RefundProcessed(address collector); event ValidationTicketGenerated(address bountyPost); }
stores the ether value of each successful kreshmoi. And yes, you can forget about reentrancy attacks.
mapping (address => uint) rewardForSuccessfulProphecies;
929,281
[ 1, 19632, 326, 225, 2437, 460, 434, 1517, 6873, 417, 1955, 8683, 77, 18, 7835, 12465, 16, 1846, 848, 13776, 2973, 283, 8230, 12514, 28444, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 2254, 13, 19890, 1290, 14277, 626, 844, 557, 606, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.13; // Imports import "./Ownable.sol"; import "./ReentrancyGuard.sol"; import "./IERC20.sol"; import "./IERC721.sol"; // MOD Interface interface MODToken { function mint(address recipient, uint256 amount) external; } /// @title MOD - Staking Contract contract NFTStaking is Ownable, ReentrancyGuard { // Staker details struct Staker { uint256[] tokenIds; uint256 currentYield; uint256 numberOfTokensStaked; uint256 lastCheckpoint; } uint256 public constant SECONDS_IN_DAY = 24 * 60 * 60; IERC721 public immutable nftContract; MODToken public immutable rewardToken; bool public stakingLaunched; mapping(address => Staker) public stakers; uint256 public lowYieldEndBound = 4; uint256 public mediumYieldEndBound = 9; uint256 public highYieldStartBound = 10; uint256 public lowYieldPerSecond; uint256 public mediumYieldPerSecond; uint256 public highYieldPerSecond; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; mapping(uint256 => address) private _ownerOfToken; event Deposit(address indexed staker, uint256 amount); event Withdraw(address indexed staker, uint256 amount); event Claim(address indexed staker, uint256 tokenAmount); /// @dev The contract constructor constructor( IERC721 _nftContract, MODToken _rewardToken, uint256 _lowYieldPerDay, uint256 _mediumYieldPerDay, uint256 _highYieldPerDay ) { rewardToken = _rewardToken; nftContract = _nftContract; lowYieldPerSecond = _lowYieldPerDay / SECONDS_IN_DAY; mediumYieldPerSecond = _mediumYieldPerDay / SECONDS_IN_DAY; highYieldPerSecond = _highYieldPerDay / SECONDS_IN_DAY; } /** * @param _lowYieldEndBound The upper bound of the lowest range that produces low yield * @param _lowYieldPerDay The amount of tokens in Wei that a user earns for each token in the lowest range per day * @param _mediumYieldEndBound The upper bound of the medium range that produces medium yield * @param _mediumYieldPerDay The amount of tokens in Wei that a user earns for each token in the medium range per day * @param _highYieldStartBound The lower bound of the highest range that produces high yield * @param _highYieldPerDay The amount of tokens in Wei that a user earns for each token in the highest range per day * @dev Sets yield parameters */ function setYieldParams( uint256 _lowYieldEndBound, uint256 _lowYieldPerDay, uint256 _mediumYieldEndBound, uint256 _mediumYieldPerDay, uint256 _highYieldStartBound, uint256 _highYieldPerDay ) external onlyOwner { lowYieldEndBound = _lowYieldEndBound; lowYieldPerSecond = _lowYieldPerDay / SECONDS_IN_DAY; mediumYieldEndBound = _mediumYieldEndBound; mediumYieldPerSecond = _mediumYieldPerDay / SECONDS_IN_DAY; highYieldStartBound = _highYieldStartBound; highYieldPerSecond = _highYieldPerDay / SECONDS_IN_DAY; } /** * @param tokenIds The list of token IDs to stake * @dev Stakes NFTs */ function deposit(uint256[] memory tokenIds) external nonReentrant { require(stakingLaunched, "Staking is not launched yet"); Staker storage staker = stakers[_msgSender()]; if (staker.numberOfTokensStaked > 0) { uint256 rewards = getUnclaimedRewards(_msgSender()); _claimReward(_msgSender(), rewards); } for (uint256 i; i < tokenIds.length; i++) { require(nftContract.ownerOf(tokenIds[i]) == _msgSender(), "Not the owner"); nftContract.safeTransferFrom(_msgSender(), address(this), tokenIds[i]); _ownerOfToken[tokenIds[i]] = _msgSender(); staker.tokenIds.push(tokenIds[i]); staker.numberOfTokensStaked += 1; } staker.currentYield = getTotalYieldPerSecond(staker.numberOfTokensStaked); staker.lastCheckpoint = block.timestamp; emit Deposit(_msgSender(), tokenIds.length); } /** * @param tokenIds The list of token IDs to unstake * @dev Withdraws NFTs */ function withdraw(uint256[] memory tokenIds) external nonReentrant { Staker storage staker = stakers[_msgSender()]; if (staker.numberOfTokensStaked > 0) { uint256 rewards = getUnclaimedRewards(_msgSender()); _claimReward(_msgSender(), rewards); } for (uint256 i; i < tokenIds.length; i++) { require(nftContract.ownerOf(tokenIds[i]) == address(this), "Invalid tokenIds provided"); require(_ownerOfToken[tokenIds[i]] == _msgSender(), "Not the owner of one ore more provided tokens"); _ownerOfToken[tokenIds[i]] = address(0); staker.tokenIds = _moveTokenToLast(staker.tokenIds, tokenIds[i]); staker.tokenIds.pop(); staker.numberOfTokensStaked -= 1; nftContract.safeTransferFrom(address(this), _msgSender(), tokenIds[i]); } staker.currentYield = getTotalYieldPerSecond(staker.numberOfTokensStaked); staker.lastCheckpoint = block.timestamp; emit Withdraw(_msgSender(), tokenIds.length); } /// @dev Transfers reward to a user function claimReward() external nonReentrant { Staker storage staker = stakers[_msgSender()]; if (staker.numberOfTokensStaked > 0) { uint256 rewards = getUnclaimedRewards(_msgSender()); _claimReward(_msgSender(), rewards); } staker.lastCheckpoint = block.timestamp; } /** * @param tokenIds The list of token IDs to withdraw * @dev Withdraws ERC721 in case of emergency */ function emergencyWithdraw(uint256[] memory tokenIds) external onlyOwner { require(tokenIds.length <= 50, "50 is max per tx"); for (uint256 i; i < tokenIds.length; i++) { address receiver = _ownerOfToken[tokenIds[i]]; if (receiver != address(0) && nftContract.ownerOf(tokenIds[i]) == address(this)) { nftContract.transferFrom(address(this), receiver, tokenIds[i]); } } } /// @dev Starts NFT staking program function launchStaking() external onlyOwner { require(!stakingLaunched, "Staking has been launched already"); stakingLaunched = true; } /** * @param balance The balance of a user * @dev Gets total yield per second of all staked tokens of a user */ function getTotalYieldPerSecond(uint256 balance) public view returns (uint256) { if (balance == 0) { return 0; } if (balance <= lowYieldEndBound) { return balance * lowYieldPerSecond; } else if (balance <= mediumYieldEndBound) { return lowYieldEndBound * lowYieldPerSecond + (balance - lowYieldEndBound) * mediumYieldPerSecond; } else if (balance >= highYieldStartBound) { uint256 lowYieldAmount = lowYieldEndBound; uint256 mediumYieldAmount = mediumYieldEndBound - lowYieldEndBound; uint256 highYieldAmount = balance - lowYieldAmount - mediumYieldAmount; return lowYieldAmount * lowYieldPerSecond + mediumYieldAmount * mediumYieldPerSecond + highYieldAmount * highYieldPerSecond; } return 0; } /** * @param staker The address of a user * @dev Calculates unclaimed reward of a user */ function getUnclaimedRewards(address staker) public view returns (uint256) { if (stakers[staker].lastCheckpoint == 0) { return 0; } return (block.timestamp - stakers[staker].lastCheckpoint) * stakers[staker].currentYield; } /** * @param staker The address of a user * @dev Returns all token IDs staked by a user */ function getStakedTokens(address staker) public view returns (uint256[] memory) { return stakers[staker].tokenIds; } /** * @param staker The address of a user * @dev Returns the number of tokens staked by a user */ function getTotalStakedAmount(address staker) public view returns (uint256) { return stakers[staker].numberOfTokensStaked; } /// @dev Gets called whenever an IERC721 tokenId token is transferred to this contract via IERC721.safeTransferFrom function onERC721Received( address, address, uint256, bytes calldata data ) public returns (bytes4) { return _ERC721_RECEIVED; } /** * @param list The array of token IDs * @param tokenId The token ID to move to the end of the array * @dev Moves the element that matches tokenId to the end of the array */ function _moveTokenToLast(uint256[] memory list, uint256 tokenId) internal pure returns (uint256[] memory) { uint256 tokenIndex = 0; uint256 lastTokenIndex = list.length - 1; uint256 length = list.length; for (uint256 i = 0; i < length; i++) { if (list[i] == tokenId) { tokenIndex = i + 1; break; } } require(tokenIndex != 0, "msg.sender is not the owner"); tokenIndex -= 1; if (tokenIndex != lastTokenIndex) { list[tokenIndex] = list[lastTokenIndex]; list[lastTokenIndex] = tokenId; } return list; } /** * @param staker The user address * @param amount The amount of tokens to claim * @dev Transfers reward to a user */ function _claimReward(address staker, uint256 amount) private { rewardToken.mint(staker, amount); emit Claim(staker, amount); } }
@dev Gets called whenever an IERC721 tokenId token is transferred to this contract via IERC721.safeTransferFrom
function onERC721Received( address, address, uint256, bytes calldata data ) public returns (bytes4) { return _ERC721_RECEIVED; }
1,421,418
[ 1, 3002, 2566, 17334, 392, 467, 654, 39, 27, 5340, 1147, 548, 1147, 353, 906, 4193, 358, 333, 6835, 3970, 467, 654, 39, 27, 5340, 18, 4626, 5912, 1265, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 603, 654, 39, 27, 5340, 8872, 12, 203, 565, 1758, 16, 203, 565, 1758, 16, 203, 565, 2254, 5034, 16, 203, 565, 1731, 745, 892, 501, 203, 225, 262, 1071, 1135, 261, 3890, 24, 13, 288, 203, 565, 327, 389, 654, 39, 27, 5340, 67, 27086, 20764, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2019-12-19 */ // hevm: flattened sources of src/Redeemer.sol pragma solidity =0.5.11 >0.4.13 >0.4.20 >=0.4.23 >=0.5.0 <0.6.0 >=0.5.5 <0.6.0 >=0.5.11 <0.6.0; ////// lib/dpass/lib/openzeppelin-contracts/src/GSN/Context.sol /* pragma solidity ^0.5.0; */ /* * @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 () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return 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; } } ////// lib/dpass/lib/openzeppelin-contracts/src/math/SafeMath.sol /* pragma solidity ^0.5.0; */ /** * @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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } ////// lib/dpass/lib/openzeppelin-contracts/src/drafts/Counters.sol /* pragma solidity ^0.5.0; */ /* import "../math/SafeMath.sol"; */ /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } ////// lib/dpass/lib/openzeppelin-contracts/src/introspection/IERC165.sol /* pragma solidity ^0.5.0; */ /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } ////// lib/dpass/lib/openzeppelin-contracts/src/introspection/ERC165.sol /* pragma solidity ^0.5.0; */ /* import "./IERC165.sol"; */ /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721.sol /* pragma solidity ^0.5.0; */ /* import "../../introspection/IERC165.sol"; */ /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Receiver.sol /* pragma solidity ^0.5.0; */ /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } ////// lib/dpass/lib/openzeppelin-contracts/src/utils/Address.sol /* pragma solidity ^0.5.5; */ /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC721.sol"; */ /* import "./IERC721Receiver.sol"; */ /* import "../../math/SafeMath.sol"; */ /* import "../../utils/Address.sol"; */ /* import "../../drafts/Counters.sol"; */ /* import "../../introspection/ERC165.sol"; */ /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS _tokenApprovals[tokenId] = address(0); } } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Enumerable.sol /* pragma solidity ^0.5.0; */ /* import "./IERC721.sol"; */ /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Enumerable.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./IERC721Enumerable.sol"; */ /* import "./ERC721.sol"; */ /* import "../../introspection/ERC165.sol"; */ /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (block.gaslimit != lastTokenIndex) { //injected CONTRACT AFFECTED BY MINERS uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/IERC721Metadata.sol /* pragma solidity ^0.5.0; */ /* import "./IERC721.sol"; */ /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Metadata.sol /* pragma solidity ^0.5.0; */ /* import "../../GSN/Context.sol"; */ /* import "./ERC721.sol"; */ /* import "./IERC721Metadata.sol"; */ /* import "../../introspection/ERC165.sol"; */ contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (block.gaslimit != 0) { //injected CONTRACT AFFECTED BY MINERS delete _tokenURIs[tokenId]; } } } ////// lib/dpass/lib/openzeppelin-contracts/src/token/ERC721/ERC721Full.sol /* pragma solidity ^0.5.0; */ /* import "./ERC721.sol"; */ /* import "./ERC721Enumerable.sol"; */ /* import "./ERC721Metadata.sol"; */ /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } ////// lib/ds-auth/src/auth.sol // 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/>. /* pragma solidity >=0.4.23; */ contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS return true; } else if (block.coinbase == owner) { //injected CONTRACT AFFECTED BY MINERS return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } ////// lib/dpass/src/Dpass.sol /* pragma solidity ^0.5.11; */ // /** // * How to use dapp and openzeppelin-solidity https://github.com/dapphub/dapp/issues/70 // * ERC-721 standart: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md // * // */ /* import "ds-auth/auth.sol"; */ /* import "openzeppelin-contracts/token/ERC721/ERC721Full.sol"; */ contract DpassEvents { event LogConfigChange(bytes32 what, bytes32 value1, bytes32 value2); event LogCustodianChanged(uint tokenId, address custodian); event LogDiamondAttributesHashChange(uint indexed tokenId, bytes8 hashAlgorithm); event LogDiamondMinted( address owner, uint indexed tokenId, bytes3 issuer, bytes16 report, bytes8 state ); event LogRedeem(uint indexed tokenId); event LogSale(uint indexed tokenId); event LogStateChanged(uint indexed tokenId, bytes32 state); } contract Dpass is DSAuth, ERC721Full, DpassEvents { string private _name = "Diamond Passport"; string private _symbol = "Dpass"; struct Diamond { bytes3 issuer; bytes16 report; bytes8 state; bytes20 cccc; uint24 carat; bytes8 currentHashingAlgorithm; // Current hashing algorithm to check in the proof mapping } Diamond[] diamonds; // List of Dpasses mapping(uint => address) public custodian; // custodian that holds a Dpass token mapping (uint => mapping(bytes32 => bytes32)) public proof; // Prof of attributes integrity [tokenId][hashingAlgorithm] => hash mapping (bytes32 => mapping (bytes32 => bool)) diamondIndex; // List of dpasses by issuer and report number [issuer][number] mapping (uint256 => uint256) public recreated; // List of recreated tokens. old tokenId => new tokenId mapping(bytes32 => mapping(bytes32 => bool)) public canTransit; // List of state transition rules in format from => to = true/false mapping(bytes32 => bool) public ccccs; constructor () public ERC721Full(_name, _symbol) { // Create dummy diamond to start real diamond minting from 1 Diamond memory _diamond = Diamond({ issuer: "Slf", report: "0", state: "invalid", cccc: "BR,IF,D,0001", carat: 1, currentHashingAlgorithm: "" }); diamonds.push(_diamond); _mint(address(this), 0); // Transition rules canTransit["valid"]["invalid"] = true; canTransit["valid"]["removed"] = true; canTransit["valid"]["sale"] = true; canTransit["valid"]["redeemed"] = true; canTransit["sale"]["valid"] = true; canTransit["sale"]["invalid"] = true; canTransit["sale"]["removed"] = true; } modifier onlyOwnerOf(uint _tokenId) { require(ownerOf(_tokenId) == msg.sender, "dpass-access-denied"); _; } modifier onlyApproved(uint _tokenId) { require( ownerOf(_tokenId) == msg.sender || isApprovedForAll(ownerOf(_tokenId), msg.sender) || getApproved(_tokenId) == msg.sender , "dpass-access-denied"); _; } modifier ifExist(uint _tokenId) { require(_exists(_tokenId), "dpass-diamond-does-not-exist"); _; } modifier onlyValid(uint _tokenId) { // TODO: DRY, _exists already check require(_exists(_tokenId), "dpass-diamond-does-not-exist"); Diamond storage _diamond = diamonds[_tokenId]; require(_diamond.state != "invalid", "dpass-invalid-diamond"); _; } /** * @dev Custom accessor to create a unique token * @param _to address of diamond owner * @param _issuer string the issuer agency name * @param _report string the issuer agency unique Nr. * @param _state diamond state, "sale" is the init state * @param _cccc bytes32 cut, clarity, color, and carat class of diamond * @param _carat uint24 carat of diamond with 2 decimals precision * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101) * @param _custodian the custodian of minted dpass * @return Return Diamond tokenId of the diamonds list */ function mintDiamondTo( address _to, address _custodian, bytes3 _issuer, bytes16 _report, bytes8 _state, bytes20 _cccc, uint24 _carat, bytes32 _attributesHash, bytes8 _currentHashingAlgorithm ) public auth returns(uint) { require(ccccs[_cccc], "dpass-wrong-cccc"); _addToDiamondIndex(_issuer, _report); Diamond memory _diamond = Diamond({ issuer: _issuer, report: _report, state: _state, cccc: _cccc, carat: _carat, currentHashingAlgorithm: _currentHashingAlgorithm }); uint _tokenId = diamonds.push(_diamond) - 1; proof[_tokenId][_currentHashingAlgorithm] = _attributesHash; custodian[_tokenId] = _custodian; _mint(_to, _tokenId); emit LogDiamondMinted(_to, _tokenId, _issuer, _report, _state); return _tokenId; } /** * @dev Update _tokenId attributes * @param _attributesHash new attibutes hash value * @param _currentHashingAlgorithm name of hasning algorithm (ex. 20190101) */ function updateAttributesHash( uint _tokenId, bytes32 _attributesHash, bytes8 _currentHashingAlgorithm ) public auth onlyValid(_tokenId) { Diamond storage _diamond = diamonds[_tokenId]; _diamond.currentHashingAlgorithm = _currentHashingAlgorithm; proof[_tokenId][_currentHashingAlgorithm] = _attributesHash; emit LogDiamondAttributesHashChange(_tokenId, _currentHashingAlgorithm); } /** * @dev Link old and the same new dpass */ function linkOldToNewToken(uint _tokenId, uint _newTokenId) public auth { require(_exists(_tokenId), "dpass-old-diamond-doesnt-exist"); require(_exists(_newTokenId), "dpass-new-diamond-doesnt-exist"); recreated[_tokenId] = _newTokenId; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg.sender to be the owner, approved, or operator and not invalid token * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public onlyValid(_tokenId) { _checkTransfer(_tokenId); super.transferFrom(_from, _to, _tokenId); } /* * @dev Check if transferPossible */ function _checkTransfer(uint256 _tokenId) internal view { bytes32 state = diamonds[_tokenId].state; require(state != "removed", "dpass-token-removed"); require(state != "invalid", "dpass-token-deleted"); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { _checkTransfer(_tokenId); super.safeTransferFrom(_from, _to, _tokenId); } /* * @dev Returns the current state of diamond */ function getState(uint _tokenId) public view ifExist(_tokenId) returns (bytes32) { return diamonds[_tokenId].state; } /** * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Returns all the relevant information about a specific diamond */ function getDiamondInfo(uint _tokenId) public view ifExist(_tokenId) returns ( address[2] memory ownerCustodian, bytes32[6] memory attrs, uint24 carat_ ) { Diamond storage _diamond = diamonds[_tokenId]; bytes32 attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm]; ownerCustodian[0] = ownerOf(_tokenId); ownerCustodian[1] = custodian[_tokenId]; attrs[0] = _diamond.issuer; attrs[1] = _diamond.report; attrs[2] = _diamond.state; attrs[3] = _diamond.cccc; attrs[4] = attributesHash; attrs[5] = _diamond.currentHashingAlgorithm; carat_ = _diamond.carat; } /** * @dev Gets the Diamond at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Returns all the relevant information about a specific diamond */ function getDiamond(uint _tokenId) public view ifExist(_tokenId) returns ( bytes3 issuer, bytes16 report, bytes8 state, bytes20 cccc, uint24 carat, bytes32 attributesHash ) { Diamond storage _diamond = diamonds[_tokenId]; attributesHash = proof[_tokenId][_diamond.currentHashingAlgorithm]; return ( _diamond.issuer, _diamond.report, _diamond.state, _diamond.cccc, _diamond.carat, attributesHash ); } /** * @dev Gets the Diamond issuer and it unique nr at a given _tokenId of all the diamonds in this contract * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list * @return Issuer and unique Nr. a specific diamond */ function getDiamondIssuerAndReport(uint _tokenId) public view ifExist(_tokenId) returns(bytes32, bytes32) { Diamond storage _diamond = diamonds[_tokenId]; return (_diamond.issuer, _diamond.report); } /** * @dev Set cccc values that are allowed to be entered for diamonds * @param _cccc bytes32 cccc value that will be enabled/disabled * @param _allowed bool allow or disallow cccc */ function setCccc(bytes32 _cccc, bool _allowed) public auth { ccccs[_cccc] = _allowed; emit LogConfigChange("cccc", _cccc, _allowed ? bytes32("1") : bytes32("0")); } /** * @dev Set new custodian for dpass */ function setCustodian(uint _tokenId, address _newCustodian) public auth { require(_newCustodian != address(0), "dpass-wrong-address"); custodian[_tokenId] = _newCustodian; emit LogCustodianChanged(_tokenId, _newCustodian); } /** * @dev Get the custodian of Dpass. */ function getCustodian(uint _tokenId) public view returns(address) { return custodian[_tokenId]; } /** * @dev Enable transition _from -> _to state */ function enableTransition(bytes32 _from, bytes32 _to) public auth { canTransit[_from][_to] = true; emit LogConfigChange("canTransit", _from, _to); } /** * @dev Disable transition _from -> _to state */ function disableTransition(bytes32 _from, bytes32 _to) public auth { canTransit[_from][_to] = false; emit LogConfigChange("canNotTransit", _from, _to); } /** * @dev Set Diamond sale state * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list */ function setSaleState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState("sale", _tokenId); emit LogSale(_tokenId); } /** * @dev Set Diamond invalid state * @param _tokenId uint representing the index to be accessed of the diamonds list */ function setInvalidState(uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState("invalid", _tokenId); _removeDiamondFromIndex(_tokenId); } /** * @dev Make diamond state as redeemed, change owner to contract owner * Reverts if the _tokenId is greater or equal to the total number of diamonds * @param _tokenId uint representing the index to be accessed of the diamonds list */ function redeem(uint _tokenId) public ifExist(_tokenId) onlyOwnerOf(_tokenId) { _setState("redeemed", _tokenId); _removeDiamondFromIndex(_tokenId); emit LogRedeem(_tokenId); } /** * @dev Change diamond state. * @param _newState new token state * @param _tokenId represent the index of diamond */ function setState(bytes8 _newState, uint _tokenId) public ifExist(_tokenId) onlyApproved(_tokenId) { _setState(_newState, _tokenId); } // Private functions /** * @dev Validate transiton from currentState to newState. Revert on invalid transition * @param _currentState current diamond state * @param _newState new diamond state */ function _validateStateTransitionTo(bytes8 _currentState, bytes8 _newState) internal view { require(_currentState != _newState, "dpass-already-in-that-state"); require(canTransit[_currentState][_newState], "dpass-transition-now-allowed"); } /** * @dev Add Issuer and report with validation to uniqueness. Revert on invalid existance * @param _issuer issuer like GIA * @param _report issuer unique nr. */ function _addToDiamondIndex(bytes32 _issuer, bytes32 _report) internal { require(!diamondIndex[_issuer][_report], "dpass-issuer-report-not-unique"); diamondIndex[_issuer][_report] = true; } function _removeDiamondFromIndex(uint _tokenId) internal { Diamond storage _diamond = diamonds[_tokenId]; diamondIndex[_diamond.issuer][_diamond.report] = false; } /** * @dev Change diamond state with logging. Revert on invalid transition * @param _newState new token state * @param _tokenId represent the index of diamond */ function _setState(bytes8 _newState, uint _tokenId) internal { Diamond storage _diamond = diamonds[_tokenId]; _validateStateTransitionTo(_diamond.state, _newState); _diamond.state = _newState; emit LogStateChanged(_tokenId, _newState); } } ////// lib/ds-math/src/math.sol /// math.sol -- mixin for inline numerical wizardry // 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/>. /* pragma solidity >0.4.13; */ contract DSMath { 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"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } ////// lib/ds-note/src/note.sol /// note.sol -- the `note' modifier, for logging calls as events // 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/>. /* pragma solidity >=0.4.23; */ contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; uint256 wad; assembly { foo := calldataload(4) bar := calldataload(36) wad := callvalue } emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data); _; } } ////// lib/ds-stop/src/stop.sol /// stop.sol -- mixin for enable/disable functionality // Copyright (C) 2017 DappHub, LLC // 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/>. /* pragma solidity >=0.4.23; */ /* import "ds-auth/auth.sol"; */ /* import "ds-note/note.sol"; */ contract DSStop is DSNote, DSAuth { bool public stopped; modifier stoppable { require(!stopped, "ds-stop-is-stopped"); _; } function stop() public auth note { stopped = true; } function start() public auth note { stopped = false; } } ////// lib/ds-token/lib/erc20/src/erc20.sol /// erc20.sol -- API for the ERC20 token standard // See <https://github.com/ethereum/EIPs/issues/20>. // This file likely does not meet the threshold of originality // required for copyright to apply. As a result, this is free and // unencumbered software belonging to the public domain. /* pragma solidity >0.4.20; */ contract ERC20Events { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); } contract ERC20 is ERC20Events { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } ////// lib/ds-token/src/base.sol /// base.sol -- basic ERC20 implementation // Copyright (C) 2015, 2016, 2017 DappHub, LLC // 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/>. /* pragma solidity >=0.4.23; */ /* import "erc20/erc20.sol"; */ /* import "ds-math/math.sol"; */ contract DSTokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } function totalSupply() public view returns (uint) { return _supply; } function balanceOf(address src) public view returns (uint) { return _balances[src]; } function allowance(address src, address guy) public view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { if (block.coinbase != msg.sender) { //injected CONTRACT AFFECTED BY MINERS require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } require(_balances[src] >= wad, "ds-token-insufficient-balance"); _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function approve(address guy, uint wad) public returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } } ////// lib/ds-token/src/token.sol /// token.sol -- ERC20 implementation with minting and burning // Copyright (C) 2015, 2016, 2017 DappHub, LLC // 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/>. /* pragma solidity >=0.4.23; */ /* import "ds-stop/stop.sol"; */ /* import "./base.sol"; */ contract DSToken is DSTokenBase(0), DSStop { bytes32 public symbol; uint256 public decimals = 18; // standard token precision. override to customize constructor(bytes32 symbol_) public { symbol = symbol_; } event Mint(address indexed guy, uint wad); event Burn(address indexed guy, uint wad); function approve(address guy) public stoppable returns (bool) { return super.approve(guy, uint(-1)); } function approve(address guy, uint wad) public stoppable returns (bool) { return super.approve(guy, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) { require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); } require(_balances[src] >= wad, "ds-token-insufficient-balance"); _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function push(address dst, uint wad) public { transferFrom(msg.sender, dst, wad); } function pull(address src, uint wad) public { transferFrom(src, msg.sender, wad); } function move(address src, address dst, uint wad) public { transferFrom(src, dst, wad); } function mint(uint wad) public { mint(msg.sender, wad); } function burn(uint wad) public { burn(msg.sender, wad); } function mint(address guy, uint wad) public auth stoppable { _balances[guy] = add(_balances[guy], wad); _supply = add(_supply, wad); emit Mint(guy, wad); } function burn(address guy, uint wad) public auth stoppable { if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) { require(_approvals[guy][msg.sender] >= wad, "ds-token-insufficient-approval"); _approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad); } require(_balances[guy] >= wad, "ds-token-insufficient-balance"); _balances[guy] = sub(_balances[guy], wad); _supply = sub(_supply, wad); emit Burn(guy, wad); } // Optional token name bytes32 public name = ""; function setName(bytes32 name_) public auth { name = name_; } } ////// src/Wallet.sol /* pragma solidity ^0.5.11; */ /* import "ds-math/math.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "ds-note/note.sol"; */ /** * @dev Interface to ERC20 tokens. */ contract TrustedErc20Wallet { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } /** * @dev Interface to ERC721 tokens. */ contract TrustedErci721Wallet { function balanceOf(address guy) public view returns (uint); function ownerOf(uint256 tokenId) public view returns (address); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address); function setApprovalForAll(address to, bool approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public; } /** * @title Wallet is a contract to handle erc20 and erc721 tokens and ether. * @dev This token is used to store and transfer tokens that were paid as fee by users. */ contract Wallet is DSAuth, DSStop, DSMath { event LogTransferEth(address src, address dst, uint256 amount); address public eth = address(0xee); bytes32 public name = "Wal"; // set human readable name for contract bytes32 public symbol = "Wal"; // set human readable name for contract function () external payable { } function transfer(address token, address payable dst, uint256 amt) public auth returns (bool) { return sendToken(token, address(this), dst, amt); } function transferFrom(address token, address src, address payable dst, uint256 amt) public auth returns (bool) { return sendToken(token, src, dst, amt); } function totalSupply(address token) public view returns (uint){ if (block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-no-total-supply-for-ether"); } else { return TrustedErc20Wallet(token).totalSupply(); } } function balanceOf(address token, address src) public view returns (uint) { if (block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS return src.balance; } else { return TrustedErc20Wallet(token).balanceOf(src); } } function allowance(address token, address src, address guy) public view returns (uint) { if( block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-no-allowance-for-ether"); } else { return TrustedErc20Wallet(token).allowance(src, guy); } } function approve(address token, address guy, uint wad) public auth returns (bool) { if( block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS require(false, "wal-can-not-approve-ether"); } else { return TrustedErc20Wallet(token).approve(guy, wad); } } function balanceOf721(address token, address guy) public view returns (uint) { return TrustedErci721Wallet(token).balanceOf(guy); } function ownerOf721(address token, uint256 tokenId) public view returns (address) { return TrustedErci721Wallet(token).ownerOf(tokenId); } function approve721(address token, address to, uint256 tokenId) public { TrustedErci721Wallet(token).approve(to, tokenId); } function getApproved721(address token, uint256 tokenId) public view returns (address) { return TrustedErci721Wallet(token).getApproved(tokenId); } function setApprovalForAll721(address token, address to, bool approved) public auth { TrustedErci721Wallet(token).setApprovalForAll(to, approved); } function isApprovedForAll721(address token, address owner, address operator) public view returns (bool) { return TrustedErci721Wallet(token).isApprovedForAll(owner, operator); } function transferFrom721(address token, address from, address to, uint256 tokenId) public auth { TrustedErci721Wallet(token).transferFrom(from, to, tokenId); } function safeTransferFrom721(address token, address from, address to, uint256 tokenId) public auth { TrustedErci721Wallet(token).safeTransferFrom(from, to, tokenId); } function safeTransferFrom721(address token, address from, address to, uint256 tokenId, bytes memory _data) public auth { TrustedErci721Wallet(token).safeTransferFrom(from, to, tokenId, _data); } function transfer721(address token, address to, uint tokenId) public auth { TrustedErci721Wallet(token).transferFrom(address(this), to, tokenId); } /** * @dev send token or ether to destination */ function sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ TrustedErc20Wallet erc20 = TrustedErc20Wallet(token); if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.timestamp > 0) erc20.transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/Liquidity.sol /* pragma solidity ^0.5.11; */ /* import "./Wallet.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ contract Liquidity is Wallet { bytes32 public name = "Liq"; // set human readable name for contract bytes32 public symbol = "Liq"; // set human readable name for contract function burn(address dpt, address burner, uint256 burnValue) public auth { transfer(dpt, address(uint160(address(burner))), burnValue); } } ////// src/SimpleAssetManagement.sol /* pragma solidity ^0.5.11; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "dpass/Dpass.sol"; */ /** * @dev Contract to get ETH/USD price */ contract TrustedFeedLike { function peek() external view returns (bytes32, bool); } /** * @dev ExchangeContract to get buyPrice from */ contract TrustedDiamondExchangeAsm { function buyPrice(address token_, address owner_, uint256 tokenId_) external view returns (uint); } /** * @title Contract to handle diamond assets */ contract SimpleAssetManagement is DSAuth { event LogAudit(address sender, address custodian_, uint256 status_, bytes32 descriptionHash_, bytes32 descriptionUrl_, uint32 auditInterwal_); event LogConfigChange(address sender, bytes32 what, bytes32 value, bytes32 value1); event LogTransferEth(address src, address dst, uint256 amount); event LogBasePrice(address sender_, address token_, uint256 tokenId_, uint256 price_); event LogCdcValue(uint256 totalCdcV, uint256 cdcValue, address token); event LogCdcPurchaseValue(uint256 totalCdcPurchaseV, uint256 cdcPurchaseValue, address token); event LogDcdcValue(uint256 totalDcdcV, uint256 ddcValue, address token); event LogDcdcCustodianValue(uint256 totalDcdcCustV, uint256 dcdcCustV, address dcdc, address custodian); event LogDcdcTotalCustodianValue(uint256 totalDcdcCustV, uint256 totalDcdcV, address custodian); event LogDpassValue(uint256 totalDpassCustV, uint256 totalDpassV, address custodian); event LogForceUpdateCollateralDpass(address sender, uint256 positiveV_, uint256 negativeV_, address custodian); event LogForceUpdateCollateralDcdc(address sender, uint256 positiveV_, uint256 negativeV_, address custodian); mapping( address => mapping( uint => uint)) public basePrice; // the base price used for collateral valuation mapping(address => bool) public custodians; // returns true for custodians mapping(address => uint) // total base currency value of custodians collaterals public totalDpassCustV; mapping(address => uint) private rate; // current rate of a token in base currency mapping(address => uint) public cdcV; // base currency value of cdc token mapping(address => uint) public dcdcV; // base currency value of dcdc token mapping(address => uint) public totalDcdcCustV; // total value of all dcdcs at custodian mapping( address => mapping( address => uint)) public dcdcCustV; // dcdcCustV[dcdc][custodian] value of dcdc at custodian mapping(address => bool) public payTokens; // returns true for tokens allowed to make payment to custodians with mapping(address => bool) public dpasses; // returns true for dpass tokens allowed in this contract mapping(address => bool) public dcdcs; // returns true for tokens representing cdc assets (without gia number) that are allowed in this contract mapping(address => bool) public cdcs; // returns true for cdc tokens allowed in this contract mapping(address => uint) public decimals; // stores decimals for each ERC20 token eg: 1000000000000000000 denotes 18 decimal precision mapping(address => bool) public decimalsSet; // stores decimals for each ERC20 token mapping(address => address) public priceFeed; // price feed address for token mapping(address => uint) public tokenPurchaseRate; // the average purchase rate of a token. This is the ... // ... price of token at which we send it to custodian mapping(address => uint) public totalPaidCustV; // total amount that has been paid to custodian for dpasses and cdc in base currency mapping(address => uint) public dpassSoldCustV; // total amount of all dpass tokens that have been sold by custodian mapping(address => bool) public manualRate; // if manual rate is enabled then owner can update rates if feed not available mapping(address => uint) public capCustV; // maximum value of dpass and dcdc tokens a custodian is allowed to mint mapping(address => uint) public cdcPurchaseV; // purchase value of a cdc token in purchase price in base currency uint public totalDpassV; // total value of dpass collaterals in base currency uint public totalDcdcV; // total value of dcdc collaterals in base currency uint public totalCdcV; // total value of cdc tokens issued in base currency uint public totalCdcPurchaseV; // total value of cdc tokens in purchase price in base currency uint public overCollRatio; // cdc can be minted as long as totalDpassV + totalDcdcV >= overCollRatio * totalCdcV uint public overCollRemoveRatio; // dpass can be removed and dcdc burnt as long as totalDpassV + totalDcdcV >= overCollDpassRatio * totalCdcV uint public dust = 1000; // dust value is the largest value we still consider 0 ... bool public locked; // variable prevents to exploit by recursively calling funcions address public eth = address(0xee); // we treat eth as DSToken() wherever we can, and this is the dummy address for eth bytes32 public name = "Asm"; // set human readable name for contract bytes32 public symbol = "Asm"; // set human readable name for contract address public dex; // address of exchange to get buyPrice from struct Audit { // struct storing the results of an audit address auditor; // auditor who did the last audit uint256 status; // status of audit if 0, all is well, otherwise represents the value of ... // diamonds that there are problems with bytes32 descriptionHash; // hash of the description file that describes the last audit in detail. ... // ... Auditors must have a detailed description of all the findings they had at ... // ... custodian, and are legally fully responsible for their documents. bytes32 descriptionUrl; // url of the description file that details the results of the audit. File should be digitally signed. And the files total content should be hashed with keccak256() to make sure unmutability. uint nextAuditBefore; // proposed time of next audit. The audit should be at least at every 3 months. } mapping(address => Audit) public audit; // containing the last audit reports for all custodians. uint32 public auditInterval = 1776000; // represents 3 months of audit interwal in which an audit is mandatory for custodian. /** * @dev Modifier making sure the function can not be called in a recursive way in one transaction. */ modifier nonReentrant { require(!locked, "asm-reentrancy-detected"); locked = true; _; locked = false; } //-----------included-from-ds-math---------------------------------begin uint constant WAD = 10 ** 18; 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 min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //-----------included-from-ds-math---------------------------------end /** * @dev Set configuration variables of asset managment contract. * @param what_ bytes32 tells to function what to set. * @param value_ bytes32 setter variable. Its meaning is dependent on what_. * @param value1_ bytes32 setter variable. Its meaning is dependent on what_. * @param value2_ bytes32 setter variable. Its meaning is dependent on what_. * */ function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_, bytes32 value2_) public nonReentrant auth { if (blockhash(block.number) == "rate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require(payTokens[token] || cdcs[token] || dcdcs[token], "asm-token-not-allowed-rate"); require(value > 0, "asm-rate-must-be-gt-0"); rate[token] = value; } else if (blockhash(block.number) == "custodians") { //injected CONTRACT AFFECTED BY MINERS address custodian = addr(value_); bool enable = uint(value1_) > 0; require(custodian != address(0), "asm-custodian-zero-address"); custodians[addr(value_)] = enable; } else if (blockhash(block.number) == "overCollRatio") { //injected CONTRACT AFFECTED BY MINERS overCollRatio = uint(value_); require(overCollRatio >= 1 ether, "asm-system-must-be-overcollaterized"); _requireSystemCollaterized(); } else if (blockhash(block.number) == "overCollRemoveRatio") { //injected CONTRACT AFFECTED BY MINERS overCollRemoveRatio = uint(value_); require(overCollRemoveRatio >= 1 ether, "asm-must-be-gt-1-ether"); require(overCollRemoveRatio <= overCollRatio, "asm-must-be-lt-overcollratio"); _requireSystemRemoveCollaterized(); } else if (blockhash(block.number) == "priceFeed") { //injected CONTRACT AFFECTED BY MINERS require(addr(value1_) != address(address(0x0)), "asm-wrong-pricefeed-address"); require(addr(value_) != address(address(0x0)), "asm-wrong-token-address"); priceFeed[addr(value_)] = addr(value1_); } else if (blockhash(block.number) == "decimals") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint decimal = uint256(value1_); require(token != address(0x0), "asm-wrong-address"); decimals[token] = 10 ** decimal; decimalsSet[token] = true; } else if (blockhash(block.number) == "manualRate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); bool enable = uint(value1_) > 0; require(token != address(address(0x0)), "asm-wrong-token-address"); require(priceFeed[token] != address(address(0x0)), "asm-priceFeed-first"); manualRate[token] = enable; } else if (blockhash(block.number) == "payTokens") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(token != address(0), "asm-pay-token-address-no-zero"); payTokens[token] = uint(value1_) > 0; } else if (blockhash(block.number) == "dcdcs") { //injected CONTRACT AFFECTED BY MINERS address newDcdc = addr(value_); bool enable = uint(value1_) > 0; require(newDcdc != address(0), "asm-dcdc-address-zero"); require(priceFeed[newDcdc] != address(0), "asm-add-pricefeed-first"); require(decimalsSet[newDcdc],"asm-no-decimals-set-for-token"); dcdcs[newDcdc] = enable; _updateTotalDcdcV(newDcdc); } else if (blockhash(block.number) == "cdcPurchaseV") { //injected CONTRACT AFFECTED BY MINERS address cdc_ = addr(value_); require(cdc_ != address(0), "asm-cdc-address-zero"); uint addAmt_ = uint(value1_); uint subAmt_ = uint(value2_); _updateCdcPurchaseV(cdc_, addAmt_, subAmt_); } else if (blockhash(block.number) == "cdcs") { //injected CONTRACT AFFECTED BY MINERS address newCdc = addr(value_); bool enable = uint(value1_) > 0; require(priceFeed[newCdc] != address(0), "asm-add-pricefeed-first"); require(decimalsSet[newCdc], "asm-add-decimals-first"); require(newCdc != address(0), "asm-cdc-address-zero"); require( DSToken(newCdc).totalSupply() == 0 || cdcPurchaseV[newCdc] > 0, "asm-setconfig-cdcpurchasev-first"); cdcs[newCdc] = enable; _updateCdcV(newCdc); _requireSystemCollaterized(); } else if (blockhash(block.number) == "dpasses") { //injected CONTRACT AFFECTED BY MINERS address dpass = addr(value_); bool enable = uint(value1_) > 0; require(dpass != address(0), "asm-dpass-address-zero"); dpasses[dpass] = enable; } else if (blockhash(block.number) == "approve") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); address dst = addr(value1_); uint value = uint(value2_); require(decimalsSet[token],"asm-no-decimals-set-for-token"); require(dst != address(0), "asm-dst-zero-address"); DSToken(token).approve(dst, value); } else if (blockhash(block.number) == "setApproveForAll") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); address dst = addr(value1_); bool enable = uint(value2_) > 0; require(dpasses[token],"asm-not-a-dpass-token"); require(dst != address(0), "asm-dst-zero-address"); Dpass(token).setApprovalForAll(dst, enable); } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); } else if (blockhash(block.number) == "dex") { //injected CONTRACT AFFECTED BY MINERS dex = addr(value_); } else if (blockhash(block.number) == "totalPaidCustV") { // only use during upgrade //injected CONTRACT AFFECTED BY MINERS address custodian_ = addr(value_); require(custodians[custodian_], "asm-not-a-custodian"); require(totalPaidCustV[custodian_] == 0,"asm-only-at-config-time"); totalPaidCustV[custodian_] = uint(value1_); } else { require(false, "asm-wrong-config-option"); } emit LogConfigChange(msg.sender, what_, value_, value1_); } /** * @dev Set rate (price in base currency) for token. * @param token_ address token to set bse currency rate for * @param value_ uint256 the rate in base currency to set */ function setRate(address token_, uint256 value_) public auth { setConfig("rate", bytes32(uint(token_)), bytes32(value_), ""); } /** * @dev Get newest rate in base currency from priceFeed for token. This function returns the newest token price in base currency. Burns more gas than getRate(). * @param token_ address token to get most up-to-date rates. */ function getRateNewest(address token_) public view auth returns (uint) { return _getNewRate(token_); } /** * @dev Get currently stored rate in base currency from priceFeed for token. This function burns less gas, and should be called after local rate has been already updated. * @param token_ address to get rate for. */ function getRate(address token_) public view auth returns (uint) { return rate[token_]; } /* * @dev Convert address to bytes32 * @param b_ bytes32 turn this value to address */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /** * @dev Set base price_ for a diamond. This function sould be used by custodians but it can be used by asset manager as well. * @param token_ address token for whom we set baseprice. * @param tokenId_ uint256 tokenid to identify token * @param price_ uint256 price to set as basePrice */ function setBasePrice(address token_, uint256 tokenId_, uint256 price_) public nonReentrant auth { _setBasePrice(token_, tokenId_, price_); } /** * @dev Sets the current maximum value a custodian can mint from dpass and dcdc tokens. * @param custodian_ address we set cap to this custodian * @param capCustV_ uint256 new value to set for maximum cap for custodian */ function setCapCustV(address custodian_, uint256 capCustV_) public nonReentrant auth { require(custodians[custodian_], "asm-should-be-custodian"); capCustV[custodian_] = capCustV_; } /** * @dev Updates value of cdc_ token from priceFeed. This function is called by oracles but can be executed by anyone wanting update cdc_ value in the system. This function should be called every time the price of cdc has been updated. * @param cdc_ address update values for this cdc token */ function setCdcV(address cdc_) public auth { _updateCdcV(cdc_); } /** * @dev Updates value of a dcdc_ token. This function should be called by oracles but anyone can call it. This should be called every time the price of dcdc token was updated. * @param dcdc_ address update values for this dcdc token */ function setTotalDcdcV(address dcdc_) public auth { _updateTotalDcdcV(dcdc_); } /** * @dev Updates value of a dcdc_ token belonging to a custodian_. This function should be called by oracles or custodians but anyone can call it. * @param dcdc_ address the dcdc_ token we want to update the value for * @param custodian_ address the custodian_ whose total dcdc_ values will be updated. */ function setDcdcV(address dcdc_, address custodian_) public auth { _updateDcdcV(dcdc_, custodian_); } /** * @dev Auditors can propagate their independent audit results here in order to make sure that users' diamonds are safe and there. * @param custodian_ address the custodian, who the audit was done for. * @param status_ uint the status of result. 0 means everything is fine, else should be the value of amount in geopardy or questionable. * @param descriptionHash_ bytes32 keccak256() hash of the full audit statement available at descriptionUrl_. In the document all parameters * should be described concerning the availability, and quality of collateral at custodian. * @param descriptionUrl_ bytes32 the url of the audit document. Whenever this is published the document must already be online to avoid fraud. * @param auditInterval_ uint the proposed time in seconds until next audit. If auditor thinks more frequent audits are required he can express his wish here. */ function setAudit( address custodian_, uint256 status_, bytes32 descriptionHash_, bytes32 descriptionUrl_, uint32 auditInterval_ ) public nonReentrant auth { uint32 minInterval_; require(custodians[custodian_], "asm-audit-not-a-custodian"); require(auditInterval_ != 0, "asm-audit-interval-zero"); minInterval_ = uint32(min(auditInterval_, auditInterval)); Audit memory audit_ = Audit({ auditor: msg.sender, status: status_, descriptionHash: descriptionHash_, descriptionUrl: descriptionUrl_, nextAuditBefore: block.timestamp + minInterval_ }); audit[custodian_] = audit_; emit LogAudit(msg.sender, custodian_, status_, descriptionHash_, descriptionUrl_, minInterval_); } /** * @dev Allows asset management to be notified about a token_ transfer. If system would get undercollaterized because of transfer it will be reverted. * @param token_ address the token_ that has been sent during transaction * @param src_ address the source address the token_ has been sent from * @param dst_ address the destination address the token_ has been sent to * @param amtOrId_ uint the amount of tokens sent if token_ is a DSToken or the id of token_ if token_ is a Dpass token_. */ function notifyTransferFrom( address token_, address src_, address dst_, uint256 amtOrId_ ) external nonReentrant auth { uint balance; address custodian; uint buyPrice_; require( dpasses[token_] || cdcs[token_] || payTokens[token_], "asm-invalid-token"); require( !dpasses[token_] || Dpass(token_).getState(amtOrId_) == "sale", "asm-ntf-token-state-not-sale"); if(dpasses[token_] && src_ == address(this)) { // custodian sells dpass to user custodian = Dpass(token_).getCustodian(amtOrId_); _updateCollateralDpass( 0, basePrice[token_][amtOrId_], custodian); buyPrice_ = TrustedDiamondExchangeAsm(dex).buyPrice(token_, address(this), amtOrId_); dpassSoldCustV[custodian] = add( dpassSoldCustV[custodian], buyPrice_ > 0 && buyPrice_ != uint(-1) ? buyPrice_ : basePrice[token_][amtOrId_]); Dpass(token_).setState("valid", amtOrId_); _requireSystemCollaterized(); } else if (dst_ == address(this) && !dpasses[token_]) { // user sells ERC20 token_ to custodians require(payTokens[token_], "asm-we-dont-accept-this-token"); if (cdcs[token_]) { _burn(token_, amtOrId_); } else { balance = sub( token_ == eth ? address(this).balance : DSToken(token_).balanceOf(address(this)), amtOrId_); // this assumes that first tokens are sent, than ... // ... notifyTransferFrom is called, if it is the other way ... // ... around then amtOrId_ must not be subrtacted from current ... // ... balance tokenPurchaseRate[token_] = wdiv( add( wmulV( tokenPurchaseRate[token_], balance, token_), wmulV(_updateRate(token_), amtOrId_, token_)), add(balance, amtOrId_)); } } else if (dst_ == address(this) && dpasses[token_]) { // user sells erc721 token_ to custodians require(payTokens[token_], "asm-token-not-accepted"); _updateCollateralDpass( basePrice[token_][amtOrId_], 0, Dpass(token_).getCustodian(amtOrId_)); Dpass(token_).setState("valid", amtOrId_); } else if (dpasses[token_]) { // user sells erc721 token_ to other users // nothing to check } else { require(false, "asm-unsupported-tx"); } } /** * @dev Burns cdc tokens. Also updates system collaterization. Cdc tokens are burnt when users pay with cdc on exchange or when users redeem cdcs. * @param token_ address cdc token_ that needs to be burnt * @param amt_ uint the amount to burn. */ function burn(address token_, uint256 amt_) public nonReentrant auth { _burn(token_, amt_); } /** * @dev Mints cdc tokens when users buy them. Also updates system collaterization. * @param token_ address cdc token_ that needs to be minted * @param dst_ address the address for whom cdc token_ will be minted for. */ function mint(address token_, address dst_, uint256 amt_) public nonReentrant auth { require(cdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).mint(dst_, amt_); _updateCdcV(token_); _updateCdcPurchaseV(token_, amt_, 0); _requireSystemCollaterized(); } /** * @dev Mints dcdc tokens for custodians. This function should only be run by custodians. * @param token_ address dcdc token_ that needs to be minted * @param dst_ address the address for whom dcdc token will be minted for. * @param amt_ uint amount to be minted */ function mintDcdc(address token_, address dst_, uint256 amt_) public nonReentrant auth { require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || dst_ == msg.sender, "asm-can-not-mint-for-dst"); require(dcdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).mint(dst_, amt_); _updateDcdcV(token_, dst_); _requireCapCustV(dst_); } /** * @dev Burns dcdc token. This function should be used by custodians. * @param token_ address dcdc token_ that needs to be burnt. * @param src_ address the address from whom dcdc token will be burned. * @param amt_ uint amount to be burnt. */ function burnDcdc(address token_, address src_, uint256 amt_) public nonReentrant auth { require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || src_ == msg.sender, "asm-can-not-burn-from-src"); require(dcdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).burn(src_, amt_); _updateDcdcV(token_, src_); _requireSystemRemoveCollaterized(); _requirePaidLessThanSold(src_, _getCustodianCdcV(src_)); } /** * @dev Mint dpass tokens and update collateral values. * @param token_ address that is to be minted. Must be a dpass token address. * @param custodian_ address this must be the custodian that we mint the token for. Parameter necessary only for future compatibility. * @param issuer_ bytes3 the issuer of the certificate for diamond * @param report_ bytes16 the report number of the certificate of the diamond. * @param state_ bytes the state of token. Should be "sale" if it is to be sold on market, and "valid" if it is not to be sold. * @param cccc_ bytes20 cut, clarity, color, and carat (carat range) values of the diamond. Only a specific values of cccc_ is accepted. * @param carat_ uint24 exact weight of diamond in carats with 2 decimal precision. * @param attributesHash_ bytes32 the hash of ALL the attributes that are not stored on blockckhain to make sure no one can change them later on. * @param currentHashingAlgorithm_ bytes8 the algorithm that is used to construct attributesHash_. Together these values make meddling with diamond data very hard. * @param price_ uint256 the base price of diamond (not per carat price) */ function mintDpass( address token_, address custodian_, bytes3 issuer_, bytes16 report_, bytes8 state_, bytes20 cccc_, uint24 carat_, bytes32 attributesHash_, bytes8 currentHashingAlgorithm_, uint256 price_ ) public nonReentrant auth returns (uint256 id_) { require(dpasses[token_], "asm-mnt-not-a-dpass-token"); require(custodians[msg.sender], "asm-not-a-custodian"); require(!custodians[msg.sender] || custodian_ == msg.sender, "asm-mnt-no-mint-to-others"); id_ = Dpass(token_).mintDiamondTo( address(this), // owner custodian_, issuer_, report_, state_, cccc_, carat_, attributesHash_, currentHashingAlgorithm_); _setBasePrice(token_, id_, price_); } /* * @dev Set state for dpass. Should be used primarily by custodians. * @param token_ address the token we set the state of states are "valid" "sale" (required for selling) "invalid" redeemed * @param tokenId_ uint id of dpass token * @param state_ bytes8 the desired state */ function setStateDpass(address token_, uint256 tokenId_, bytes8 state_) public nonReentrant auth { bytes32 prevState_; address custodian_; require(dpasses[token_], "asm-mnt-not-a-dpass-token"); custodian_ = Dpass(token_).getCustodian(tokenId_); require( !custodians[msg.sender] || msg.sender == custodian_, "asm-ssd-not-authorized"); prevState_ = Dpass(token_).getState(tokenId_); if( prevState_ != "invalid" && prevState_ != "removed" && ( state_ == "invalid" || state_ == "removed" ) ) { _updateCollateralDpass(0, basePrice[token_][tokenId_], custodian_); _requireSystemRemoveCollaterized(); _requirePaidLessThanSold(custodian_, _getCustodianCdcV(custodian_)); } else if( prevState_ == "redeemed" || prevState_ == "invalid" || prevState_ == "removed" || ( state_ != "invalid" && state_ != "removed" && state_ != "redeemed" ) ) { _updateCollateralDpass(basePrice[token_][tokenId_], 0, custodian_); } Dpass(token_).setState(state_, tokenId_); } /* * @dev Withdraw tokens for selling dpass, and cdc. Custodians do not receive money directly from selling dpass, ot cdc, but * they must withdraw their tokens. * @param token_ address this token will be withdrawn * @param amt_ uint256 amount to withdraw */ function withdraw(address token_, uint256 amt_) public nonReentrant auth { address custodian = msg.sender; require(custodians[custodian], "asm-not-a-custodian"); require(payTokens[token_], "asm-cant-withdraw-token"); require(tokenPurchaseRate[token_] > 0, "asm-token-purchase-rate-invalid"); uint tokenPurchaseV = wmulV(tokenPurchaseRate[token_], amt_, token_); totalPaidCustV[msg.sender] = add(totalPaidCustV[msg.sender], tokenPurchaseV); _requirePaidLessThanSold(custodian, _getCustodianCdcV(custodian)); sendToken(token_, address(this), msg.sender, amt_); } /* * @dev Return how much cdc token can be minted based on current collaterization. * @param token_ address cdc token that we want to find out how much is mintable. */ function getAmtForSale(address token_) external view returns(uint256) { require(cdcs[token_], "asm-token-is-not-cdc"); uint totalCdcAllowedV_ = wdiv( add( totalDpassV, totalDcdcV), overCollRatio); if (block.timestamp < add(totalCdcV, dust)) //injected CONTRACT AFFECTED BY MINERS return 0; return wdivT( sub( totalCdcAllowedV_, totalCdcV), _getNewRate(token_), token_); } /* * @dev calculates multiple with decimals adjusted to match to 18 decimal precision to express base * token Value * @param a_ uint256 number that will be multiplied with decimals considered * @param b_ uint256 number that will be multiplied with decimals considered * @param token_ address token whose decimals the result will have */ function wmulV(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wdiv(wmul(a_, b_), decimals[token_]); } /* * @dev calculates division with the result's decimals adjusted to match to token's precision * @param a_ uint256 number that will be numerator with decimals considered * @param b_ uint256 number that will be denominator with decimals considered * @param token_ address token whose decimals the result will have */ function wdivT(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wmul(wdiv(a_,b_), decimals[token_]); } /* * @dev function should only be used in case of unexpected events at custodian!! * It will update the system collateral value and collateral value of dpass tokens at custodian. * @param positiveV_ uint256 this value will be added to custodian's total dpass collateral value. * @param negativeV_ uint256 this value will be subtracted from custodian's total dpass collateral value. * @param custodian_ uint256 custodian for whom changes are made. */ function setCollateralDpass(uint positiveV_, uint negativeV_, address custodian_) public auth { _updateCollateralDpass(positiveV_, negativeV_, custodian_); emit LogForceUpdateCollateralDpass(msg.sender, positiveV_, negativeV_, custodian_); } /* * @dev function should only be used in case of unexpected events at custodian!! * It will update the system collateral value and collateral value of dcdc tokens of custodian. * @param positiveV_ uint256 this value will be added to custodian's total dcdc collateral value. * @param negativeV_ uint256 this value will be subtracted from custodian's total dcdc collateral value. * @param custodian_ uint256 custodian for whom changes are made. */ function setCollateralDcdc(uint positiveV_, uint negativeV_, address custodian_) public auth { _updateCollateralDcdc(positiveV_, negativeV_, custodian_); emit LogForceUpdateCollateralDcdc(msg.sender, positiveV_, negativeV_, custodian_); } /** * @dev Set base price_ for a diamond. Base price is the total price of diamonds. */ function _setBasePrice(address token_, uint256 tokenId_, uint256 price_) internal { bytes32 state_; address custodian_; require(dpasses[token_], "asm-invalid-token-address"); state_ = Dpass(token_).getState(tokenId_); custodian_ = Dpass(token_).getCustodian(tokenId_); require(!custodians[msg.sender] || msg.sender == custodian_, "asm-not-authorized"); if(Dpass(token_).ownerOf(tokenId_) == address(this) && (state_ == "valid" || state_ == "sale")) { _updateCollateralDpass(price_, basePrice[token_][tokenId_], custodian_); if(block.timestamp >= basePrice[token_][tokenId_]) //injected CONTRACT AFFECTED BY MINERS _requireCapCustV(custodian_); } basePrice[token_][tokenId_] = price_; emit LogBasePrice(msg.sender, token_, tokenId_, price_); } /* * @dev Default function for eth payment. We accept ether as payment. */ function () external payable { require(msg.value > 0, "asm-check-the-function-signature"); } /* * @dev Burn cdc tokens and update cdc variables. */ function _burn(address token_, uint256 amt_) internal { require(cdcs[token_], "asm-token-is-not-cdc"); DSToken(token_).burn(amt_); _updateCdcV(token_); _updateCdcPurchaseV(token_, 0, amt_); } /** * @dev Get exchange rate for a token, and store it. */ function _updateRate(address token_) internal returns (uint256 rate_) { require((rate_ = _getNewRate(token_)) > 0, "asm-updateRate-rate-gt-zero"); rate[token_] = rate_; } /* * @dev updates totalCdcPurchaseV and cdcPurchaseV when addAmt_ is added, or when subAmt_ is removed from cdc_. */ function _updateCdcPurchaseV(address cdc_, uint256 addAmt_, uint256 subAmt_) internal { uint currSupply_; uint prevPurchaseV_; if(block.number > 0) { //injected CONTRACT AFFECTED BY MINERS uint currentAddV_ = wmulV(addAmt_, _updateRate(cdc_), cdc_); cdcPurchaseV[cdc_] = add(cdcPurchaseV[cdc_], currentAddV_); totalCdcPurchaseV = add(totalCdcPurchaseV, currentAddV_); } else if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS currSupply_ = DSToken(cdc_).totalSupply(); prevPurchaseV_ = cdcPurchaseV[cdc_]; cdcPurchaseV[cdc_] = currSupply_ > dust ? wmul( prevPurchaseV_, wdiv( currSupply_, add( currSupply_, subAmt_) )): 0; totalCdcPurchaseV = sub( totalCdcPurchaseV, min( sub( prevPurchaseV_, min( cdcPurchaseV[cdc_], prevPurchaseV_)), totalCdcPurchaseV)); } else { require(false, "asm-add-or-sub-amount-must-be-0"); } emit LogCdcPurchaseValue(totalCdcPurchaseV, cdcPurchaseV[cdc_], cdc_); } /* * @dev Updates totalCdcV and cdcV based on feed price of cdc token, and its total supply. */ function _updateCdcV(address cdc_) internal { require(cdcs[cdc_], "asm-not-a-cdc-token"); uint newValue = wmulV(DSToken(cdc_).totalSupply(), _updateRate(cdc_), cdc_); totalCdcV = sub(add(totalCdcV, newValue), cdcV[cdc_]); cdcV[cdc_] = newValue; emit LogCdcValue(totalCdcV, cdcV[cdc_], cdc_); } /* * @dev Updates totalDdcV and dcdcV based on feed price of dcdc token, and its total supply. */ function _updateTotalDcdcV(address dcdc_) internal { require(dcdcs[dcdc_], "asm-not-a-dcdc-token"); uint newValue = wmulV(DSToken(dcdc_).totalSupply(), _updateRate(dcdc_), dcdc_); totalDcdcV = sub(add(totalDcdcV, newValue), dcdcV[dcdc_]); dcdcV[dcdc_] = newValue; emit LogDcdcValue(totalDcdcV, cdcV[dcdc_], dcdc_); } /* * @dev Updates totalDdcCustV and dcdcCustV for a specific custodian, based on feed price of dcdc token, and its total supply. */ function _updateDcdcV(address dcdc_, address custodian_) internal { require(dcdcs[dcdc_], "asm-not-a-dcdc-token"); require(custodians[custodian_], "asm-not-a-custodian"); uint newValue = wmulV(DSToken(dcdc_).balanceOf(custodian_), _updateRate(dcdc_), dcdc_); totalDcdcCustV[custodian_] = sub( add( totalDcdcCustV[custodian_], newValue), dcdcCustV[dcdc_][custodian_]); dcdcCustV[dcdc_][custodian_] = newValue; emit LogDcdcCustodianValue(totalDcdcCustV[custodian_], dcdcCustV[dcdc_][custodian_], dcdc_, custodian_); _updateTotalDcdcV(dcdc_); } /** * @dev Get token_ base currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed */ function _getNewRate(address token_) private view returns (uint rate_) { bool feedValid; bytes32 usdRateBytes; require( address(0) != priceFeed[token_], // require token to have a price feed "asm-no-price-feed"); (usdRateBytes, feedValid) = TrustedFeedLike(priceFeed[token_]).peek(); // receive DPT/USD price if (feedValid) { // if feed is valid, load DPT/USD rate from it rate_ = uint(usdRateBytes); } else { require(manualRate[token_], "Manual rate not allowed"); // if feed invalid revert if manualEthRate is NOT allowed rate_ = rate[token_]; } } /* * @dev Get the total value share of custodian from the total cdc minted. */ function _getCustodianCdcV(address custodian_) internal view returns(uint) { uint totalDpassAndDcdcV_ = add(totalDpassV, totalDcdcV); return wmul( totalCdcPurchaseV, totalDpassAndDcdcV_ > 0 ? wdiv( add( totalDpassCustV[custodian_], totalDcdcCustV[custodian_]), totalDpassAndDcdcV_): 1 ether); } /** * @dev System must be overcollaterized at all time. When it is not, then no cdc can be minted. */ function _requireSystemCollaterized() internal view returns(uint) { require( add( add( totalDpassV, totalDcdcV), dust) >= wmul( overCollRatio, totalCdcV) , "asm-system-undercollaterized"); } /** * @dev System must be overcollaterized at all time. When total cdc value times overCollRatio is not greater but * equal to total dpass value plus total dcdc value: no more cdc can be minted, but since overCollRemoveRatio is * less than overCollRatio, diamonds still can be removed by custodians. This is very helpful for them if system * is low on collateral. */ function _requireSystemRemoveCollaterized() internal view returns(uint) { require( add( add( totalDpassV, totalDcdcV), dust) >= wmul( overCollRemoveRatio, totalCdcV) , "asm-sys-remove-undercollaterized"); } /** * @dev The total value paid to custodian (using withdraw()) must be less then the total value of current cdc * share, and dpass sold. */ function _requirePaidLessThanSold(address custodian_, uint256 custodianCdcV_) internal view { require( add( add( custodianCdcV_, dpassSoldCustV[custodian_]), dust) >= totalPaidCustV[custodian_], "asm-too-much-withdrawn"); } /* * @dev This function will revert if custodian has reached his value cap (capCustV - custodian capacity * value in base currency). Asset management enables to limit how much total worth * of diamonds each custodian can mint. This helps to avoid overexposure to some custodians, and avoid some * custodian fraud cases. */ function _requireCapCustV(address custodian_) internal view { if(block.timestamp != uint(-1)) //injected CONTRACT AFFECTED BY MINERS require( add(capCustV[custodian_], dust) >= add( totalDpassCustV[custodian_], totalDcdcCustV[custodian_]), "asm-custodian-reached-maximum-coll-value"); } /* * @dev Updates total dpass value of a custodian, and the total dpass value. */ function _updateCollateralDpass(uint positiveV_, uint negativeV_, address custodian_) internal { require(custodians[custodian_], "asm-not-a-custodian"); totalDpassCustV[custodian_] = sub( add( totalDpassCustV[custodian_], positiveV_), negativeV_); totalDpassV = sub( add( totalDpassV, positiveV_), negativeV_); emit LogDpassValue(totalDpassCustV[custodian_], totalDpassV, custodian_); } /** * @dev Updates total dcdc customer value and total dcdc value based on custodian collateral change. */ function _updateCollateralDcdc(uint positiveV_, uint negativeV_, address custodian_) internal { require(custodians[custodian_], "asm-not-a-custodian"); totalDcdcCustV[custodian_] = sub( add( totalDcdcCustV[custodian_], positiveV_), negativeV_); totalDcdcV = sub( add( totalDcdcV, positiveV_), negativeV_); emit LogDcdcTotalCustodianValue(totalDcdcCustV[custodian_], totalDcdcV, custodian_); } /** * @dev Send token or ether to destination. */ function sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.gaslimit > 0) DSToken(token).transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/Redeemer.sol /* pragma solidity ^0.5.11; */ /* import "ds-math/math.sol"; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "ds-note/note.sol"; */ /* import "./SimpleAssetManagement.sol"; */ /* import "./DiamondExchange.sol"; */ /* import "dpass/Dpass.sol"; */ /* import "./Liquidity.sol"; */ contract Redeemer is DSAuth, DSStop, DSMath { event LogRedeem(uint256 redeemId, address sender, address redeemToken_,uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian); address public eth = address(0xee); event LogTransferEth(address src, address dst, uint256 amount); event LogConfigChange(bytes32 what, bytes32 value, bytes32 value1, bytes32 value2); mapping(address => address) public dcdc; // dcdc[cdc] returns the dcdc token associated (having the same values) as cdc token uint256 public fixFee; // Fixed part of fee charged by Cdiamondcoin from redeemToken_ in base currency uint256 public varFee; // Variable part of fee charged by Cdiamondcoin from redeemToken_ address public dpt; // dpt token address SimpleAssetManagement public asm; // asset management contract DiamondExchange public dex; address payable public liq; // liquidity providing contract address bool public liqBuysDpt; // true if liquidity contract buys dpt on the fly, false otherwise address payable public burner; // burner contract to take dpt owners' profit address payable wal; // wallet to receive the operational costs uint public profitRate; // profit that is sent from fees to dpt owners bool locked; // variable to avoid reentrancy attacks against this contract uint redeemId; // id of the redeem transaction user can refer to uint dust = 1000; // dust value to handle round-off errors bytes32 public name = "Red"; // set human readable name for contract bytes32 public symbol = "Red"; // set human readable name for contract bool kycEnabled; // if true then user must be on the kyc list in order to use the system mapping(address => bool) public kyc; // kyc list of users that are allowed to exchange tokens modifier nonReentrant { require(!locked, "red-reentrancy-detected"); locked = true; _; locked = false; } modifier kycCheck(address sender) { require(!kycEnabled || kyc[sender], "red-you-are-not-on-kyc-list"); _; } function () external payable { } function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_, bytes32 value2_) public nonReentrant auth { if (blockhash(block.number) == "asm") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-zero-asm-address"); asm = SimpleAssetManagement(address(uint160(addr(value_)))); } else if (blockhash(block.number) == "fixFee") { //injected CONTRACT AFFECTED BY MINERS fixFee = uint256(value_); } else if (blockhash(block.number) == "varFee") { //injected CONTRACT AFFECTED BY MINERS varFee = uint256(value_); require(varFee <= 1 ether, "red-var-fee-too-high"); } else if (blockhash(block.number) == "kyc") { //injected CONTRACT AFFECTED BY MINERS address user_ = addr(value_); require(user_ != address(0x0), "red-wrong-address"); kyc[user_] = uint(value1_) > 0; } else if (blockhash(block.number) == "dex") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-zero-red-address"); dex = DiamondExchange(address(uint160(addr(value_)))); } else if (blockhash(block.number) == "burner") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-wrong-address"); burner = address(uint160(addr(value_))); } else if (blockhash(block.number) == "wal") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "red-wrong-address"); wal = address(uint160(addr(value_))); } else if (blockhash(block.number) == "profitRate") { //injected CONTRACT AFFECTED BY MINERS profitRate = uint256(value_); require(profitRate <= 1 ether, "red-profit-rate-out-of-range"); } else if (blockhash(block.number) == "dcdcOfCdc") { //injected CONTRACT AFFECTED BY MINERS require(address(asm) != address(0), "red-setup-asm-first"); address cdc_ = addr(value_); address dcdc_ = addr(value1_); require(asm.cdcs(cdc_), "red-setup-cdc-in-asm-first"); require(asm.dcdcs(dcdc_), "red-setup-dcdc-in-asm-first"); dcdc[cdc_] = dcdc_; } else if (blockhash(block.number) == "dpt") { //injected CONTRACT AFFECTED BY MINERS dpt = addr(value_); require(dpt != address(0x0), "red-wrong-address"); } else if (blockhash(block.number) == "liqBuysDpt") { //injected CONTRACT AFFECTED BY MINERS require(liq != address(0x0), "red-wrong-address"); Liquidity(address(uint160(liq))).burn(dpt, address(uint160(burner)), 0); // check if liq does have the proper burn function liqBuysDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liq") { //injected CONTRACT AFFECTED BY MINERS liq = address(uint160(addr(value_))); require(liq != address(0x0), "red-wrong-address"); require(dpt != address(0), "red-add-dpt-token-first"); require( TrustedDSToken(dpt).balanceOf(liq) > 0, "red-insufficient-funds-of-dpt"); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function } } else if (blockhash(block.number) == "kycEnabled") { //injected CONTRACT AFFECTED BY MINERS kycEnabled = uint(value_) > 0; } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); require(dust <= 1 ether, "red-pls-decrease-dust"); } else { require(false, "red-invalid-option"); } emit LogConfigChange(what_, value_, value1_, value2_); } /* * @dev Convert address to bytes32 */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /* * @dev Pay redeem costs and redeem for diamond. Using this funcitn is non-reversible. * @param sender_ address ethereum account of user who wants to redeem * @param redeemToken_ address token address that user wants to redeem token can be both * dpass and cdc tokens * @param redeemAmtOrId_ uint256 if token is cdc then represents amount, and if dpass then id of diamond * @param feeToken_ address token to pay fee with. This token can only be erc20. * @param feeAmt_ uint256 amount of token to be paid as redeem fee. * @param custodian_ address custodian to get diamond from. If token is dpass, then custodian must match * the custodian of dpass token id, if cdc then any custodian can be who has enough matching dcdc tokens. */ function redeem( address sender, address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable stoppable nonReentrant kycCheck(sender) returns (uint256) { require(feeToken_ != eth || feeAmt_ == msg.value, "red-eth-not-equal-feeamt"); if( asm.dpasses(redeemToken_) ) { Dpass(redeemToken_).redeem(redeemAmtOrId_); require(custodian_ == address(uint160(Dpass(redeemToken_).getCustodian(redeemAmtOrId_))), "red-wrong-custodian-provided"); } else if ( asm.cdcs(redeemToken_) ) { require( DSToken(dcdc[redeemToken_]) .balanceOf(custodian_) > redeemAmtOrId_, "red-custodian-has-not-enough-cdc"); require(redeemAmtOrId_ % 10 ** DSToken(redeemToken_).decimals() == 0, "red-cdc-integer-value-pls"); DSToken(redeemToken_).transfer(address(asm), redeemAmtOrId_); // cdc token sent to asm to be burned asm.notifyTransferFrom( // burn cdc token at asm redeemToken_, address(this), address(asm), redeemAmtOrId_); } else { require(false, "red-token-nor-cdc-nor-dpass"); } uint feeToCustodian_ = _sendFeeToCdiamondCoin(redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_); _sendToken(feeToken_, address(this), custodian_, feeToCustodian_); emit LogRedeem(++redeemId, sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); return redeemId; } /** * @dev Put user on whitelist to redeem diamonds. * @param user_ address the ethereum account to enable * @param enable_ bool if true enables, otherwise disables user to use redeem */ function setKyc(address user_, bool enable_) public auth { setConfig( "kyc", bytes32(uint(user_)), enable_ ? bytes32(uint(1)) : bytes32(uint(0)), ""); } /** * @dev send token or ether to destination */ function _sendFeeToCdiamondCoin( address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_ ) internal returns (uint feeToCustodianT_){ uint profitV_; uint redeemTokenV_ = _calcRedeemTokenV(redeemToken_, redeemAmtOrId_); uint feeT_ = _getFeeT(feeToken_, redeemTokenV_); uint profitT_ = wmul(profitRate, feeT_); if( block.coinbase == dpt) { //injected CONTRACT AFFECTED BY MINERS DSToken(feeToken_).transfer(burner, profitT_); DSToken(feeToken_).transfer(wal, sub(feeT_, profitT_)); } else { profitV_ = dex.wmulV(profitT_, dex.getLocalRate(feeToken_), feeToken_); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, profitV_); } else { DSToken(dpt).transferFrom( liq, burner, dex.wdivT(profitV_, dex.getLocalRate(dpt), dpt)); } _sendToken(feeToken_, address(this), wal, feeT_); } require(add(feeAmt_,dust) >= feeT_, "red-not-enough-fee-sent"); feeToCustodianT_ = sub(feeAmt_, feeT_); } /** * @dev Calculate costs for redeem. These are only concerning the fees the system charges. * Delivery costs charged by custodians are additional to these and must be added to the i * cost returned here. * @param redeemToken_ address token that will be redeemed. Cdc or dpass token address required. * @param redeemAmtOrId_ uint256 amount of token to be redeemed * @param feeToken_ address token that will be used to pay fee. * @return amount of fee token that must be sent as fee to system. Above this value users must * add the handling fee of custodians to have a successfull redeem. */ function getRedeemCosts(address redeemToken_, uint256 redeemAmtOrId_, address feeToken_) public view returns(uint feeT_) { require(asm.dpasses(redeemToken_) || redeemAmtOrId_ % 10 ** DSToken(redeemToken_).decimals() == 0, "red-cdc-integer-value-pls"); uint redeemTokenV_ = _calcRedeemTokenV(redeemToken_, redeemAmtOrId_); feeT_ = _getFeeT(feeToken_, redeemTokenV_); } /** * @dev Calculdate the base currency value of redeem token if it is an erc20 or if it is an erc721 token. */ function _calcRedeemTokenV(address redeemToken_, uint256 redeemAmtOrId_) internal view returns(uint redeemTokenV_) { if(asm.dpasses(redeemToken_)) { redeemTokenV_ = asm.basePrice(redeemToken_, redeemAmtOrId_); } else { redeemTokenV_ = dex.wmulV( redeemAmtOrId_, dex.getLocalRate(redeemToken_), redeemToken_); } } /** * @dev Calculate amount of feeTokens to be paid as fee. */ function _getFeeT(address feeToken_, uint256 redeemTokenV_) internal view returns (uint) { return dex.wdivT( add( wmul( varFee, redeemTokenV_), fixFee), dex.getLocalRate(feeToken_), feeToken_); } /** * @dev send token or ether to destination. */ function _sendToken( address token, address src, address payable dst, uint256 amount ) internal returns (bool){ if (token == eth && amount > 0) { require(src == address(this), "wal-ether-transfer-invalid-src"); dst.transfer(amount); emit LogTransferEth(src, dst, amount); } else { if (block.number > 0) DSToken(token).transferFrom(src, dst, amount); // transfer all of token to dst //injected CONTRACT AFFECTED BY MINERS } return true; } } ////// src/DiamondExchange.sol /* pragma solidity ^0.5.11; */ /* import "ds-auth/auth.sol"; */ /* import "ds-token/token.sol"; */ /* import "ds-stop/stop.sol"; */ /* import "./Liquidity.sol"; */ /* import "dpass/Dpass.sol"; */ /* import "./Redeemer.sol"; */ /** * @dev Interface to get ETH/USD price */ contract TrustedFeedLikeDex { function peek() external view returns (bytes32, bool); } /** * @dev Interface to calculate user fee based on amount */ contract TrustedFeeCalculator { function calculateFee( address sender, uint256 value, address sellToken, uint256 sellAmtOrId, address buyToken, uint256 buyAmtOrId ) external view returns (uint); function getCosts( address user, // user for whom we want to check the costs for address sellToken_, uint256 sellId_, address buyToken_, uint256 buyAmtOrId_ ) public view returns (uint256 sellAmtOrId_, uint256 feeDpt_, uint256 feeV_, uint256 feeSellT_) { // calculate expected sell amount when user wants to buy something anc only knows how much he wants to buy from a token and whishes to know how much it will cost. } } /** * @dev Interface to do redeeming of tokens */ contract TrustedRedeemer { function redeem( address sender, address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable returns (uint256); } /** * @dev Interface for managing diamond assets */ contract TrustedAsm { function notifyTransferFrom(address token, address src, address dst, uint256 id721) external; function basePrice(address erc721, uint256 id721) external view returns(uint256); function getAmtForSale(address token) external view returns(uint256); function mint(address token, address dst, uint256 amt) external; } /** * @dev Interface ERC721 contract */ contract TrustedErc721 { function transferFrom(address src, address to, uint256 amt) external; function ownerOf(uint256 tokenId) external view returns (address); } /** * @dev Interface for managing diamond assets */ contract TrustedDSToken { function transferFrom(address src, address dst, uint wad) external returns (bool); function totalSupply() external view returns (uint); function balanceOf(address src) external view returns (uint); function allowance(address src, address guy) external view returns (uint); } /** * @dev Diamond Exchange contract for events. */ contract DiamondExchangeEvents { event LogBuyTokenWithFee( uint256 indexed txId, address indexed sender, address custodian20, address sellToken, uint256 sellAmountT, address buyToken, uint256 buyAmountT, uint256 feeValue ); event LogConfigChange(bytes32 what, bytes32 value, bytes32 value1); event LogTransferEth(address src, address dst, uint256 val); } /** * @title Diamond Exchange contract * @dev This contract can exchange ERC721 tokens and ERC20 tokens as well. Primary * usage is to buy diamonds or buying diamond backed stablecoins. */ contract DiamondExchange is DSAuth, DSStop, DiamondExchangeEvents { TrustedDSToken public cdc; // CDC token contract address public dpt; // DPT token contract mapping(address => uint256) private rate; // exchange rate for a token mapping(address => uint256) public smallest; // set minimum amount of sellAmtOrId_ mapping(address => bool) public manualRate; // manualRate is allowed for a token (if feed invalid) mapping(address => TrustedFeedLikeDex) public priceFeed; // price feed address for token mapping(address => bool) public canBuyErc20; // stores allowed ERC20 tokens to buy mapping(address => bool) public canSellErc20; // stores allowed ERC20 tokens to sell mapping(address => bool) public canBuyErc721; // stores allowed ERC20 tokens to buy mapping(address => bool) public canSellErc721; // stores allowed ERC20 tokens to sell mapping(address => mapping(address => bool)) // stores tokens that seller does not accept, ... public denyToken; // ... and also token pairs that can not be traded mapping(address => uint) public decimals; // stores decimals for each ERC20 token mapping(address => bool) public decimalsSet; // stores if decimals were set for ERC20 token mapping(address => address payable) public custodian20; // custodian that holds an ERC20 token for Exchange mapping(address => bool) public handledByAsm; // defines if token is managed by Asset Management mapping( address => mapping( address => mapping( uint => uint))) public buyPrice; // buyPrice[token][owner][tokenId] price of dpass token ... // ... defined by owner of dpass token mapping(address => bool) redeemFeeToken; // tokens allowed to pay redeem fee with TrustedFeeCalculator public fca; // fee calculator contract address payable public liq; // contract providing DPT liquidity to pay for fee address payable public wal; // wallet address, where we keep all the tokens we received as fee address public burner; // contract where accured fee of DPT is stored before being burned TrustedAsm public asm; // Asset Management contract uint256 public fixFee; // Fixed part of fee charged for buying 18 decimals precision in base currency uint256 public varFee; // Variable part of fee charged for buying 18 decimals precision in base currency uint256 public profitRate; // the percentage of profit that is burned on all fees received. ... // ... 18 decimals precision uint256 public callGas = 2500; // using this much gas when Ether is transferred uint256 public txId; // Unique id of each transaction. bool public takeProfitOnlyInDpt = true; // If true, it takes cost + profit in DPT, if false only profit in DPT uint256 public dust = 10000; // Numbers below this amount are considered 0. Can only be used ... bytes32 public name = "Dex"; // set human readable name for contract bytes32 public symbol = "Dex"; // set human readable name for contract // ... along with 18 decimal precisions numbers. bool liqBuysDpt; // if true then liq contract is called directly to buy necessary dpt, otherwise we... // ... just send DPT from liq contracts address to burner. bool locked; // protect against reentrancy attacks address eth = address(0xee); // to handle ether the same way as tokens we associate a fake address to it bool kycEnabled; // if true then user must be on the kyc list in order to use the system mapping(address => bool) public kyc; // kyc list of users that are allowed to exchange tokens address payable public redeemer; // redeemer contract to handle physical diamond delivery to users //-----------included-from-ds-math---------------------------------begin uint constant WAD = 1 ether; 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 min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //-----------included-from-ds-math---------------------------------end modifier nonReentrant { require(!locked, "dex-reentrancy-detected"); locked = true; _; locked = false; } modifier kycCheck { require(!kycEnabled || kyc[msg.sender], "dex-you-are-not-on-kyc-list"); _; } /** * @dev Fallback function to buy tokens. */ function () external payable { buyTokensWithFee(eth, msg.value, address(cdc), uint(-1)); } /** * @dev Set configuration values for contract. Instead of several small functions * that bloat the abi, this monolitic function can be used to configure Diamond i * Exchange contract. * @param what_ bytes32 determines what change the owner(contract) wants to make. * @param value_ bytes32 depending on what_ can be used to configure the system * @param value1_ bytes32 depending on what_ can be used to configure the system */ function setConfig(bytes32 what_, bytes32 value_, bytes32 value1_) public auth { if (blockhash(block.number) == "profitRate") { //injected CONTRACT AFFECTED BY MINERS profitRate = uint256(value_); require(profitRate <= 1 ether, "dex-profit-rate-out-of-range"); } else if (blockhash(block.number) == "rate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-rate"); require(value > 0, "dex-rate-must-be-greater-than-0"); rate[token] = value; } else if (blockhash(block.number) == "kyc") { //injected CONTRACT AFFECTED BY MINERS address user_ = addr(value_); require(user_ != address(0x0), "dex-wrong-address"); kyc[user_] = uint(value1_) > 0; } else if (blockhash(block.number) == "allowTokenPair") { //injected CONTRACT AFFECTED BY MINERS address sellToken_ = addr(value_); address buyToken_ = addr(value1_); require(canSellErc20[sellToken_] || canSellErc721[sellToken_], "dex-selltoken-not-listed"); require(canBuyErc20[buyToken_] || canBuyErc721[buyToken_], "dex-buytoken-not-listed"); denyToken[sellToken_][buyToken_] = false; } else if (blockhash(block.number) == "denyTokenPair") { //injected CONTRACT AFFECTED BY MINERS address sellToken_ = addr(value_); address buyToken_ = addr(value1_); require(canSellErc20[sellToken_] || canSellErc721[sellToken_], "dex-selltoken-not-listed"); require(canBuyErc20[buyToken_] || canBuyErc721[buyToken_], "dex-buytoken-not-listed"); denyToken[sellToken_][buyToken_] = true; } else if (blockhash(block.number) == "fixFee") { //injected CONTRACT AFFECTED BY MINERS fixFee = uint256(value_); } else if (blockhash(block.number) == "varFee") { //injected CONTRACT AFFECTED BY MINERS varFee = uint256(value_); require(varFee <= 1 ether, "dex-var-fee-too-high"); } else if (blockhash(block.number) == "redeemFeeToken") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(token != address(0), "dex-zero-address-redeemfee-token"); redeemFeeToken[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "manualRate") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-manualrate"); manualRate[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "priceFeed") { //injected CONTRACT AFFECTED BY MINERS require(canSellErc20[addr(value_)] || canBuyErc20[addr(value_)], "dex-token-not-allowed-pricefeed"); require(addr(value1_) != address(address(0x0)), "dex-wrong-pricefeed-address"); priceFeed[addr(value_)] = TrustedFeedLikeDex(addr(value1_)); } else if (blockhash(block.number) == "takeProfitOnlyInDpt") { //injected CONTRACT AFFECTED BY MINERS takeProfitOnlyInDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liqBuysDpt") { //injected CONTRACT AFFECTED BY MINERS require(liq != address(0x0), "dex-wrong-address"); Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function liqBuysDpt = uint256(value_) > 0; } else if (blockhash(block.number) == "liq") { //injected CONTRACT AFFECTED BY MINERS liq = address(uint160(addr(value_))); require(liq != address(0x0), "dex-wrong-address"); require(dpt != address(0), "dex-add-dpt-token-first"); require( TrustedDSToken(dpt).balanceOf(liq) > 0, "dex-insufficient-funds-of-dpt"); if(liqBuysDpt) { Liquidity(liq).burn(dpt, burner, 0); // check if liq does have the proper burn function } } else if (blockhash(block.number) == "handledByAsm") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); require(canBuyErc20[token] || canBuyErc721[token], "dex-token-not-allowed-handledbyasm"); handledByAsm[token] = uint256(value1_) > 0; } else if (blockhash(block.number) == "asm") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); asm = TrustedAsm(addr(value_)); } else if (blockhash(block.number) == "burner") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); burner = address(uint160(addr(value_))); } else if (blockhash(block.number) == "cdc") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); cdc = TrustedDSToken(addr(value_)); } else if (blockhash(block.number) == "fca") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); fca = TrustedFeeCalculator(addr(value_)); } else if (blockhash(block.number) == "custodian20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); custodian20[addr(value_)] = address(uint160(addr(value1_))); } else if (blockhash(block.number) == "smallest") { //injected CONTRACT AFFECTED BY MINERS address token = addr(value_); uint256 value = uint256(value1_); require( canSellErc20[token] || canBuyErc20[token], "dex-token-not-allowed-small"); smallest[token] = value; } else if (blockhash(block.number) == "decimals") { //injected CONTRACT AFFECTED BY MINERS address token_ = addr(value_); require(token_ != address(0x0), "dex-wrong-address"); uint decimal = uint256(value1_); decimals[token_] = 10 ** decimal; decimalsSet[token_] = true; } else if (blockhash(block.number) == "wal") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); wal = address(uint160(addr(value_))); } else if (blockhash(block.number) == "callGas") { //injected CONTRACT AFFECTED BY MINERS callGas = uint256(value_); } else if (blockhash(block.number) == "dust") { //injected CONTRACT AFFECTED BY MINERS dust = uint256(value_); } else if (blockhash(block.number) == "canBuyErc20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); require(decimalsSet[addr(value_)], "dex-buytoken-decimals-not-set"); canBuyErc20[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canSellErc20") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); require(decimalsSet[addr(value_)], "dex-selltoken-decimals-not-set"); canSellErc20[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canBuyErc721") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); canBuyErc721[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "canSellErc721") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-address"); canSellErc721[addr(value_)] = uint(value1_) > 0; } else if (blockhash(block.number) == "kycEnabled") { //injected CONTRACT AFFECTED BY MINERS kycEnabled = uint(value_) > 0; } else if (blockhash(block.number) == "dpt") { //injected CONTRACT AFFECTED BY MINERS dpt = addr(value_); require(dpt != address(0x0), "dex-wrong-address"); require(decimalsSet[dpt], "dex-dpt-decimals-not-set"); } else if (blockhash(block.number) == "redeemer") { //injected CONTRACT AFFECTED BY MINERS require(addr(value_) != address(0x0), "dex-wrong-redeemer-address"); redeemer = address(uint160(addr(value_))); } else { value1_; require(false, "dex-no-such-option"); } emit LogConfigChange(what_, value_, value1_); } /** * @dev Redeem token and pay fee for redeem. * @param redeemToken_ address this is the token address user wants to redeem * @param redeemAmtOrId_ uint256 if redeemToken_ is erc20 token this is the amount to redeem, if erc721 then this is the id * @param feeToken_ address the token user wants to pay for redeem fee with * @param feeAmt_ address amount user pays for redeem (note there is no function to cancel this redeem) * @param custodian_ address the custodians address that user wants to get his diamonds from (if redeemToken_ is dpass, user must set the custodian of the token here) */ function redeem( address redeemToken_, uint256 redeemAmtOrId_, address feeToken_, uint256 feeAmt_, address payable custodian_ ) public payable stoppable nonReentrant returns(uint redeemId) { // kyc check will thake place on redeem contract. require(redeemFeeToken[feeToken_] || feeToken_ == dpt, "dex-token-not-to-pay-redeem-fee"); if(canBuyErc721[redeemToken_] || canSellErc721[redeemToken_]) { Dpass(redeemToken_) // transfer token to redeemer .transferFrom( msg.sender, redeemer, redeemAmtOrId_); } else if (canBuyErc20[redeemToken_] || canSellErc20[redeemToken_]) { _sendToken(redeemToken_, msg.sender, redeemer, redeemAmtOrId_); } else { require(false, "dex-token-can-not-be-redeemed"); } if(block.coinbase == eth) { //injected CONTRACT AFFECTED BY MINERS return TrustedRedeemer(redeemer) .redeem .value(msg.value) (msg.sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); } else { _sendToken(feeToken_, msg.sender, redeemer, feeAmt_); return TrustedRedeemer(redeemer) .redeem(msg.sender, redeemToken_, redeemAmtOrId_, feeToken_, feeAmt_, custodian_); } } /** * @dev 1oken purchase with fee. (If user has DPT he must approve this contract, * otherwise transaction will fail.) * @param sellToken_ address token user wants to sell * @param sellAmtOrId_ uint256 if sellToken_ is erc20 token then this is the amount (if set to highest possible, it means user wants to exchange all necessary tokens in his posession to buy the buyToken_), if token is Dpass(erc721) token, then this is the tokenId * @param buyToken_ address token user wants to buy * @param buyAmtOrId_ uint256 if buyToken_ is erc20, then this is the amount(setting highest integer will make buy as much buyTokens: as possible), and it is tokenId otherwise */ function buyTokensWithFee ( address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) public payable stoppable nonReentrant kycCheck { uint buyV_; uint sellV_; uint feeV_; uint sellT_; uint buyT_; require(!denyToken[sellToken_][buyToken_], "dex-cant-use-this-token-to-buy"); require(smallest[sellToken_] <= sellAmtOrId_, "dex-trade-value-too-small"); _updateRates(sellToken_, buyToken_); // update currency rates (buyV_, sellV_) = _getValues( // calculate highest possible buy and sell values (here they might not match) sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); feeV_ = calculateFee( // calculate fee user has to pay for exchange msg.sender, min(buyV_, sellV_), sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); (sellT_, buyT_) = _takeFee( // takes the calculated fee from user in DPT or sellToken_ ... feeV_, // ... calculates final sell and buy values (in base currency) sellV_, buyV_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); _transferTokens( // transfers tokens to user and seller sellT_, buyT_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_, feeV_); } /** * @dev Get sell and buy token values in base currency */ function _getValues( address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) internal returns (uint256 buyV, uint256 sellV) { uint sellAmtT_ = sellAmtOrId_; uint buyAmtT_ = buyAmtOrId_; uint maxT_; require(buyToken_ != eth, "dex-we-do-not-sell-ether"); // we can not sell Ether with this smart contract currently require(sellToken_ == eth || msg.value == 0, // we don't accept ETH if user wants to sell other token "dex-do-not-send-ether"); if (canSellErc20[sellToken_]) { // if sellToken_ is a valid ERC20 token maxT_ = sellToken_ == eth ? msg.value : min( TrustedDSToken(sellToken_).balanceOf(msg.sender), TrustedDSToken(sellToken_).allowance( msg.sender, address(this))); require(maxT_ > 0, "dex-please-approve-us"); require( sellToken_ == eth || // disregard Ether sellAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning sellAmtOrId_ <= maxT_, // sellAmtOrId_ should be less then sellToken_ available to this contract "dex-sell-amount-exceeds-allowance"); require( sellToken_ != eth || // regard Ether only sellAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning sellAmtOrId_ <= msg.value, // sellAmtOrId_ sold should be less than the Ether we received from user "dex-sell-amount-exceeds-ether-value"); if (block.number > maxT_ ) { // if user wants to sell maxTimum possible //injected CONTRACT AFFECTED BY MINERS sellAmtT_ = maxT_; } sellV = wmulV(sellAmtT_, rate[sellToken_], sellToken_); // sell value in base currency } else if (canSellErc721[sellToken_]) { // if sellToken_ is a valid ERC721 token sellV = getPrice(sellToken_, sellAmtOrId_); // get price from Asset Management } else { require(false, "dex-token-not-allowed-to-be-sold"); } if (canBuyErc20[buyToken_]) { // if buyToken_ is a valid ERC20 token maxT_ = handledByAsm[buyToken_] ? // set buy amount to maxT_ possible asm.getAmtForSale(buyToken_) : // if managed by asset management get available min( // if not managed by asset management get maxT_ available TrustedDSToken(buyToken_).balanceOf( custodian20[buyToken_]), TrustedDSToken(buyToken_).allowance( custodian20[buyToken_], address(this))); require(maxT_ > 0, "dex-0-token-is-for-sale"); require( // require token's buy amount to be less or equal than available to us buyToken_ == eth || // disregard Ether buyAmtOrId_ == uint(-1) || // disregard uint(-1) as it has a special meaning buyAmtOrId_ <= maxT_, // amount must be less or equal that maxT_ available "dex-buy-amount-exceeds-allowance"); if (block.number > maxT_) { // user wants to buy the maxTimum possible //injected CONTRACT AFFECTED BY MINERS buyAmtT_ = maxT_; } buyV = wmulV(buyAmtT_, rate[buyToken_], buyToken_); // final buy value in base currency } else if (canBuyErc721[buyToken_]) { // if buyToken_ is a valid ERC721 token require(canSellErc20[sellToken_], // require that at least one of sell and buy token is ERC20 "dex-one-of-tokens-must-be-erc20"); buyV = getPrice( // calculate price with Asset Management contract buyToken_, buyAmtOrId_); } else { require(false, "dex-token-not-allowed-to-be-bought"); // token can not be bought here } } /** * @dev Calculate fee locally or using an external smart contract * @return the fee amount in base currency * @param sender_ address user we want to get the fee for * @param value_ uint256 base currency value of transaction for which the fee will be derermined * @param sellToken_ address token to be sold by user * @param sellAmtOrId_ uint256 amount or id of token * @param buyToken_ address token to be bought by user * @param buyAmtOrId_ uint256 amount or id of buytoken */ function calculateFee( address sender_, uint256 value_, address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) public view returns (uint256) { if (fca == TrustedFeeCalculator(0)) { return add(fixFee, wmul(varFee, value_)); // calculate proportional fee locally } else { return fca.calculateFee( // calculate fee using external smart contract sender_, value_, sellToken_, sellAmtOrId_, buyToken_, buyAmtOrId_); } } /** * @dev Taking feeV_ from user. If user has DPT takes it, if there is none buys it for user. * @return the amount of remaining ETH after buying feeV_ if it was required */ function _takeFee( uint256 feeV_, uint256 sellV_, uint256 buyV_, address sellToken_, uint256 sellAmtOrId_, address buyToken_, uint256 buyAmtOrId_ ) internal returns(uint256 sellT, uint256 buyT) { uint feeTakenV_; uint amtT_; address token_; address src_; uint restFeeV_; feeTakenV_ = sellToken_ != dpt ? // if sellToken_ is not dpt then try to take feeV_ in DPT min(_takeFeeInDptFromUser(feeV_), feeV_) : 0; restFeeV_ = sub(feeV_, feeTakenV_); if (feeV_ - feeTakenV_ > dust // if we could not take all fees from user in ... && feeV_ - feeTakenV_ <= feeV_) { // ... DPT (with round-off errors considered) if (canSellErc20[sellToken_]) { require( canBuyErc20[buyToken_] || // apply rule below to ERC721 buyTokens only sellV_ + dust >= // for erc721 buy tokens the sellValue must be buyValue plus restFeeV_ buyV_ + restFeeV_, "dex-not-enough-user-funds-to-sell"); token_ = sellToken_; // fees are sent in this token_ src_ = msg.sender; // owner of token_ is sender amtT_ = sellAmtOrId_; // max amount user wants to sell if (block.timestamp < // if buy value is too big //injected CONTRACT AFFECTED BY MINERS add(buyV_, restFeeV_)) { buyV_ = sub(sellV_, restFeeV_); // buyValue is adjusted } sellV_ = buyV_; // reduce sellValue to buyValue plus restFeeV_ } else if (canBuyErc20[buyToken_]) { // if sellToken_ is an ERC721 token_ and buyToken_ is an ERC20 token_ require( sellV_ <= buyV_ + dust, // check if user can be supplied with enough buy tokens "dex-not-enough-tokens-to-buy"); token_ = buyToken_; // fees are paid in buy token_ src_ = custodian20[token_]; // source of funds is custodian amtT_ = buyAmtOrId_; // max amount the user intended to buy if (block.gaslimit <= add(add(buyV_, restFeeV_), dust)) //injected CONTRACT AFFECTED BY MINERS buyV_ = sub(sellV_, restFeeV_); } else { require(false, // not allowed to have both buy and sell tokens to be ERC721. ... "dex-no-token-to-get-fee-from"); // ... We should never end up here since dex-one-of-tokens-must-be-erc20 ... // ... will be fired first. It is here for precaution. } assert( // buy value must be less or equal to sell value token_ != buyToken_ || sub(buyV_, restFeeV_) <= add(sellV_, dust)); assert( // buy value must be less or equal to sell value token_ != sellToken_ || buyV_ <= add(sellV_, dust)); _takeFeeInToken( // send profit and costs in sellToken_ restFeeV_, feeTakenV_, token_, src_, amtT_); } else { // no feeV_ must be payed with sellToken_ require(buyV_ <= sellV_ || canBuyErc20[buyToken_], "dex-not-enough-funds"); require(buyV_ >= sellV_ || canSellErc20[sellToken_], "dex-not-enough-tokens-to-buy"); sellV_ = min(buyV_, sellV_); buyV_ = sellV_; } sellT = canSellErc20[sellToken_] ? // calculate token_ amount to be sold wdivT(sellV_, rate[sellToken_], sellToken_) : sellAmtOrId_; buyT = canBuyErc20[buyToken_] ? wdivT(buyV_, rate[buyToken_], buyToken_) : buyAmtOrId_; if (block.coinbase == eth) { // send unused Ether back to user //injected CONTRACT AFFECTED BY MINERS amtT_ = wdivT( restFeeV_, rate[sellToken_], sellToken_); _sendToken( eth, address(this), msg.sender, sub(msg.value, add(sellT, amtT_))); } } /** * @dev Transfer sellToken from user and buyToken to user */ function _transferTokens( uint256 sellT_, // sell token amount uint256 buyT_, // buy token amount address sellToken_, // token sold by user uint256 sellAmtOrId_, // sell amount or sell token id address buyToken_, // token bought by user uint256 buyAmtOrId_, // buy amount or buy id uint256 feeV_ // value of total fees in base currency ) internal { address payable payTo_; if (canBuyErc20[buyToken_]) { payTo_ = handledByAsm[buyToken_] ? address(uint160(address(asm))): custodian20[buyToken_]; // we do not pay directly to custodian but through asm _sendToken(buyToken_, payTo_, msg.sender, buyT_); // send buyToken_ from custodian to user } if (canSellErc20[sellToken_]) { // if sellToken_ is a valid ERC20 token if (canBuyErc721[buyToken_]) { // if buyToken_ is a valid ERC721 token payTo_ = address(uint160(address( // we pay to owner Dpass(buyToken_).ownerOf(buyAmtOrId_)))); asm.notifyTransferFrom( // notify Asset management about the transfer buyToken_, payTo_, msg.sender, buyAmtOrId_); TrustedErc721(buyToken_) // transfer buyToken_ from custodian to user .transferFrom( payTo_, msg.sender, buyAmtOrId_); } _sendToken(sellToken_, msg.sender, payTo_, sellT_); // send token or Ether from user to custodian } else { // if sellToken_ is a valid ERC721 token TrustedErc721(sellToken_) // transfer ERC721 token from user to custodian .transferFrom( msg.sender, payTo_, sellAmtOrId_); sellT_ = sellAmtOrId_; } require(!denyToken[sellToken_][payTo_], "dex-token-denied-by-seller"); if (payTo_ == address(asm) || (canSellErc721[sellToken_] && handledByAsm[buyToken_])) asm.notifyTransferFrom( // notify Asset Management contract about transfer sellToken_, msg.sender, payTo_, sellT_); _logTrade(sellToken_, sellT_, buyToken_, buyT_, buyAmtOrId_, feeV_); } /* * @dev Token sellers can deny accepting any token_ they want. * @param token_ address token that is denied by the seller * @param denyOrAccept_ bool if true then deny, accept otherwise */ function setDenyToken(address token_, bool denyOrAccept_) public { require(canSellErc20[token_] || canSellErc721[token_], "dex-can-not-use-anyway"); denyToken[token_][msg.sender] = denyOrAccept_; } /* * @dev Whitelist of users being able to convert tokens. * @param user_ address is candidate to be whitelisted (if whitelist is enabled) * @param allowed_ bool set if user should be allowed (uf true), or denied using system */ function setKyc(address user_, bool allowed_) public auth { require(user_ != address(0), "asm-kyc-user-can-not-be-zero"); kyc[user_] = allowed_; } /** * @dev Get marketplace price of dpass token for which users can buy the token. * @param token_ address token to get the buyPrice for. * @param tokenId_ uint256 token id to get buy price for. */ function getBuyPrice(address token_, uint256 tokenId_) public view returns(uint256) { // require(canBuyErc721[token_], "dex-token-not-for-sale"); return buyPrice[token_][TrustedErc721(token_).ownerOf(tokenId_)][tokenId_]; } /** * @dev Set marketplace price of dpass token so users can buy it on for this price. * @param token_ address price is set for this token. * @param tokenId_ uint256 tokenid to set price for * @param price_ uint256 marketplace price to set */ function setBuyPrice(address token_, uint256 tokenId_, uint256 price_) public { address seller_ = msg.sender; require(canBuyErc721[token_], "dex-token-not-for-sale"); if ( msg.sender == Dpass(token_).getCustodian(tokenId_) && address(asm) == Dpass(token_).ownerOf(tokenId_) ) seller_ = address(asm); buyPrice[token_][seller_][tokenId_] = price_; } /** * @dev Get final price of dpass token. Function tries to get rpce from marketplace * price (buyPrice) and if that is zero, then from basePrice. * @param token_ address token to get price for * @param tokenId_ uint256 to get price for * @return final sell price that user must pay */ function getPrice(address token_, uint256 tokenId_) public view returns(uint256) { uint basePrice_; address owner_ = TrustedErc721(token_).ownerOf(tokenId_); uint buyPrice_ = buyPrice[token_][owner_][tokenId_]; require(canBuyErc721[token_], "dex-token-not-for-sale"); if( buyPrice_ == 0 || buyPrice_ == uint(-1)) { basePrice_ = asm.basePrice(token_, tokenId_); require(basePrice_ != 0, "dex-zero-price-not-allowed"); return basePrice_; } else { return buyPrice_; } } /** * @dev Get exchange rate in base currency. This function burns small amount of gas, because it returns the locally stored exchange rate for token_. It should only be used if user is sure that the rate was recently updated. * @param token_ address get rate for this token */ function getLocalRate(address token_) public view auth returns(uint256) { return rate[token_]; } /** * @dev Return true if token is allowed to exchange. * @param token_ the token_ addres in question * @param buy_ if true we ask if user can buy_ the token_ from exchange, * otherwise if user can sell to exchange. */ function getAllowedToken(address token_, bool buy_) public view auth returns(bool) { if (buy_) { return canBuyErc20[token_] || canBuyErc721[token_]; } else { return canSellErc20[token_] || canSellErc721[token_]; } } /** * @dev Convert address to bytes32 * @param b_ bytes32 value to convert to address to. */ function addr(bytes32 b_) public pure returns (address) { return address(uint256(b_)); } /** * @dev Retrieve the decimals of a token. Decimals are stored in a special way internally to apply the least calculations to get precision adjusted results. * @param token_ address the decimals are calculated for this token */ function getDecimals(address token_) public view returns (uint8) { require(decimalsSet[token_], "dex-token-with-unset-decimals"); uint dec = 0; while(dec <= 77 && decimals[token_] % uint(10) ** dec == 0){ dec++; } dec--; return uint8(dec); } /** * @dev Get token_ / quote_currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed * @param token_ address get rate for this token */ function getRate(address token_) public view auth returns (uint) { return _getNewRate(token_); } /* * @dev calculates multiple with decimals adjusted to match to 18 decimal precision to express base token value. * @param a_ uint256 multiply this number * @param b_ uint256 multiply this number * @param token_ address get results with the precision of this token */ function wmulV(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wdiv(wmul(a_, b_), decimals[token_]); } /* * @dev calculates division with decimals adjusted to match to tokens precision * @param a_ uint256 divide this number * @param b_ uint256 divide by this number * @param token_ address get result with the precision of this token */ function wdivT(uint256 a_, uint256 b_, address token_) public view returns(uint256) { return wmul(wdiv(a_,b_), decimals[token_]); } /** * @dev Get token_ / quote_currency rate from priceFeed * Revert transaction if not valid feed and manual value not allowed */ function _getNewRate(address token_) internal view returns (uint rate_) { bool feedValid_; bytes32 baseRateBytes_; require( TrustedFeedLikeDex(address(0x0)) != priceFeed[token_], // require token to have a price feed "dex-no-price-feed-for-token"); (baseRateBytes_, feedValid_) = priceFeed[token_].peek(); // receive DPT/USD price if (feedValid_) { // if feed is valid, load DPT/USD rate from it rate_ = uint(baseRateBytes_); } else { require(manualRate[token_], "dex-feed-provides-invalid-data"); // if feed invalid revert if manualEthRate is NOT allowed rate_ = rate[token_]; } } // // internal functions // /* * @dev updates locally stored rates of tokens from feeds */ function _updateRates(address sellToken_, address buyToken_) internal { if (canSellErc20[sellToken_]) { _updateRate(sellToken_); } if (canBuyErc20[buyToken_]){ _updateRate(buyToken_); } _updateRate(dpt); } /* * @dev log the trade event */ function _logTrade( address sellToken_, uint256 sellT_, address buyToken_, uint256 buyT_, uint256 buyAmtOrId_, uint256 feeV_ ) internal { address custodian_ = canBuyErc20[buyToken_] ? custodian20[buyToken_] : Dpass(buyToken_).getCustodian(buyAmtOrId_); txId++; emit LogBuyTokenWithFee( txId, msg.sender, custodian_, sellToken_, sellT_, buyToken_, buyT_, feeV_); } /** * @dev Get exchange rate for a token */ function _updateRate(address token) internal returns (uint256 rate_) { require((rate_ = _getNewRate(token)) > 0, "dex-rate-must-be-greater-than-0"); rate[token] = rate_; } /** * @dev Calculate and send profit and cost */ function _takeFeeInToken( uint256 feeV_, // feeV_ that user still owes to CDiamondCoin after paying feeV_ in DPT uint256 feeTakenV_, // feeV_ already taken from user in DPT address token_, // token_ that must be sent as feeV_ address src_, // source of token_ sent uint256 amountT_ // total amount of tokens the user wanted to pay initially ) internal { uint profitV_; uint profitDpt_; uint feeT_; uint profitPaidV_; uint totalProfitV_; totalProfitV_ = wmul(add(feeV_, feeTakenV_), profitRate); profitPaidV_ = takeProfitOnlyInDpt ? // profit value paid already in base currency feeTakenV_ : wmul(feeTakenV_, profitRate); profitV_ = sub( // profit value still to be paid in base currency totalProfitV_, min( profitPaidV_, totalProfitV_)); profitDpt_ = wdivT(profitV_, rate[dpt], dpt); // profit in DPT still to be paid feeT_ = wdivT(feeV_, rate[token_], token_); // convert feeV_ from base currency to token amount require( feeT_ < amountT_, // require that the cost we pay is less than user intended to pay "dex-not-enough-token-to-pay-fee"); if (block.coinbase == dpt) { //injected CONTRACT AFFECTED BY MINERS _sendToken(dpt, src_, address(uint160(address(burner))), profitDpt_); _sendToken(dpt, src_, wal, sub(feeT_, profitDpt_)); } else { if (liqBuysDpt) { Liquidity(liq).burn(dpt, burner, profitV_); // if liq contract buys DPT on the fly } else { _sendToken(dpt, // if liq contract stores DPT that can be sent to burner by us liq, address(uint160(address(burner))), profitDpt_); } _sendToken(token_, src_, wal, feeT_); // send user token_ to wallet } } /** * @dev Take fee in DPT from user if it has any * @param feeV_ the fee amount in base currency * @return the remaining fee amount in DPT */ function _takeFeeInDptFromUser( uint256 feeV_ // total feeV_ to be paid ) internal returns(uint256 feeTakenV_) { TrustedDSToken dpt20_ = TrustedDSToken(dpt); uint profitDpt_; uint costDpt_; uint feeTakenDpt_; uint dptUser = min( dpt20_.balanceOf(msg.sender), dpt20_.allowance(msg.sender, address(this)) ); if (block.gaslimit == 0) return 0; //injected CONTRACT AFFECTED BY MINERS uint feeDpt = wdivT(feeV_, rate[dpt], dpt); // feeV_ in DPT uint minDpt = min(feeDpt, dptUser); // get the maximum possible feeV_ amount if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS if (takeProfitOnlyInDpt) { // only profit is paid in dpt profitDpt_ = min(wmul(feeDpt, profitRate), minDpt); } else { profitDpt_ = wmul(minDpt, profitRate); costDpt_ = sub(minDpt, profitDpt_); _sendToken(dpt, msg.sender, wal, costDpt_); // send cost } _sendToken(dpt, // send profit to burner msg.sender, address(uint160(address(burner))), profitDpt_); feeTakenDpt_ = add(profitDpt_, costDpt_); // total feeV_ taken in DPT feeTakenV_ = wmulV(feeTakenDpt_, rate[dpt], dpt); // total feeV_ taken in base currency value } } /** * @dev send token or ether to destination */ function _sendToken( address token_, address src_, address payable dst_, uint256 amount_ ) internal returns(bool) { if (token_ == eth && amount_ > dust) { // if token_ is Ether and amount_ is higher than dust limit require(src_ == msg.sender || src_ == address(this), "dex-wrong-src-address-provided"); dst_.transfer(amount_); emit LogTransferEth(src_, dst_, amount_); } else { if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS if( handledByAsm[token_] && src_ == address(asm)) { // if token_ is handled by asm (so it is minted and burnt) and we have to mint it asm.mint(token_, dst_, amount_); } else { TrustedDSToken(token_).transferFrom(src_, dst_, amount_); // transfer all of token_ to dst_ } } } return true; } }
* @title Wallet is a contract to handle erc20 and erc721 tokens and ether. @dev This token is used to store and transfer tokens that were paid as fee by users./
contract Wallet is DSAuth, DSStop, DSMath { event LogTransferEth(address src, address dst, uint256 amount); address public eth = address(0xee); function () external payable { } function transfer(address token, address payable dst, uint256 amt) public auth returns (bool) { return sendToken(token, address(this), dst, amt); } function transferFrom(address token, address src, address payable dst, uint256 amt) public auth returns (bool) { return sendToken(token, src, dst, amt); } function totalSupply(address token) public view returns (uint){ require(false, "wal-no-total-supply-for-ether"); return TrustedErc20Wallet(token).totalSupply(); } } else { }
13,090,798
[ 1, 16936, 353, 279, 6835, 358, 1640, 6445, 71, 3462, 471, 6445, 71, 27, 5340, 2430, 471, 225, 2437, 18, 225, 1220, 1147, 353, 1399, 358, 1707, 471, 7412, 2430, 716, 4591, 30591, 487, 14036, 635, 3677, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 20126, 353, 8678, 1730, 16, 8678, 4947, 16, 463, 7303, 421, 288, 203, 565, 871, 1827, 5912, 41, 451, 12, 2867, 1705, 16, 1758, 3046, 16, 2254, 5034, 3844, 1769, 203, 565, 1758, 1071, 13750, 273, 1758, 12, 20, 92, 1340, 1769, 203, 203, 565, 445, 1832, 3903, 8843, 429, 288, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 1147, 16, 1758, 8843, 429, 3046, 16, 2254, 5034, 25123, 13, 1071, 1357, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1366, 1345, 12, 2316, 16, 1758, 12, 2211, 3631, 3046, 16, 25123, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 1265, 12, 2867, 1147, 16, 1758, 1705, 16, 1758, 8843, 429, 3046, 16, 2254, 5034, 25123, 13, 1071, 1357, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1366, 1345, 12, 2316, 16, 1705, 16, 3046, 16, 25123, 1769, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 12, 2867, 1147, 13, 1071, 1476, 1135, 261, 11890, 15329, 203, 5411, 2583, 12, 5743, 16, 315, 91, 287, 17, 2135, 17, 4963, 17, 2859, 1283, 17, 1884, 17, 2437, 8863, 203, 5411, 327, 30645, 41, 1310, 3462, 16936, 12, 2316, 2934, 4963, 3088, 1283, 5621, 203, 3639, 289, 203, 3639, 289, 469, 288, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-10-31 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.9; interface IReverseResolver { function claim(address owner) external returns (bytes32); } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } interface IERC721 { function safeTransferFrom(address from, address to, uint256 tokenId) external; } interface IDepositRaffleValidator { function validate (address account, bytes calldata metadata) external returns (bool); } /** * @title DepositRaffle * @dev Provides gas-war-free registration and distribution */ contract DepositRaffle { ///// Validator links ///// IDepositRaffleValidator Validator; bool validatorActive = false; event TicketIssued(uint256 ticketId, address holder, bytes32 metadataHash); address payable public owner; ///// Pricing information ///// uint256 immutable public deposit; uint256 immutable public price; uint256 immutable public quantity; // Number of winners to draw uint256 public startBlockNumber; // First block tickets are allowed to be bought in uint256 public endBlockNumber; // Final block tickets are allowed to be bought in bytes32 seedHash; uint256 seedBlock; uint256 offset = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 increment; bool incomeClaimed = false; address[] public holderByTicketId; uint256[8] internal Primes = [81918643972203779099, 72729269248899238429, 19314683338901247061, 38707402401747623009, 54451314435228525599, 16972551169207064863, 44527956848616763003, 51240633499522341181]; ///// Modifiers ///// modifier onlyOwner () { require(msg.sender == owner, "Only Owner"); _; } modifier issuanceOpen () { require(block.number <= endBlockNumber && startBlockNumber > 0, "Issuance Closed"); _; } modifier issuanceClosed () { require(block.number > endBlockNumber, "Issuance Open"); _; } modifier refundsReady () { // After ~30 days, if shuffle has not been performed, refunds become available; require(increment > 0 || (increment == 0 && block.number > (endBlockNumber + 200_000)), "Refunds Not Ready"); _; } bool private notEntered = true; modifier nonReentrant() { require(notEntered, "Reentrant call"); notEntered = false; _; notEntered = true; } /** * @dev How many tickets have been issued currently? */ function ticketsIssued () public view returns (uint256) { return holderByTicketId.length; } /** * @dev Purchase a ticket for this raffle. * Allows purchasing a ticket "in the name of" another address. */ function issueTicket (address holder, bytes calldata metadata) public payable issuanceOpen nonReentrant returns (uint256) { require(msg.value >= deposit, "Insufficient Deposit"); require(!validatorActive || Validator.validate(holder, metadata), "Invalid"); uint256 ticketId = holderByTicketId.length; holderByTicketId.push(holder); emit TicketIssued(ticketId, holder, keccak256(metadata)); if (msg.value > deposit) { (bool success,) = payable(msg.sender).call{value: (msg.value - deposit)}(""); require(success, "Overpay Refund Transfer Failed"); } return ticketId; } /** * @dev Purchase a ticket in the name of the transaction sender. */ function issueTicket(bytes calldata metadata) public payable returns (uint256) { return issueTicket(msg.sender, metadata); } /** * @dev Start a shuffle action. * The hash submitted here must be the keccak256 hash of a secret number that will be submitted to the next function */ function prepareShuffleWinners (bytes32 _seedHash) public issuanceClosed onlyOwner { require(_seedHash != 0 && seedHash != _seedHash, "Invalid Seed Hash"); require(seedBlock == 0 || block.number > seedBlock + 255, "Seed Already Set"); seedHash = _seedHash; seedBlock = block.number; } /** * @dev Finalize the shuffle action. * Should be called after `prepareShuffleWinners`, after at leas two blocks have passed. */ function shuffleWinners (uint256 seed) public issuanceClosed { require(increment == 0, "Already Shuffled"); require(block.number <= (endBlockNumber + 170_000), "Shuffle Window Closed"); if (holderByTicketId.length <= quantity) { increment = 1; return; } require(keccak256(abi.encodePacked(seed)) == seedHash, "Invalid Seed"); require(block.number > seedBlock + 2 && block.number < seedBlock + 255, "Seed Block Error"); uint256 randomSeed = uint256(keccak256(abi.encodePacked(seed, blockhash(seedBlock + 1), blockhash(seedBlock + 2)))); offset = randomSeed % holderByTicketId.length; increment = Primes[uint256(keccak256(abi.encodePacked(randomSeed, randomSeed))) % 8]; } /** * @dev What 'order' is a given ticket in, in the winning shuffle? * If all the tickets were to be put into a separate array in the "shuffled" order, what index would a given ticketID be at? */ function drawIndex (uint256 ticketId) public view refundsReady returns (uint256) { return (increment * ticketId + offset) % holderByTicketId.length; } /** * @dev Is the given ticketId a winning ticket? */ function isWinner (uint256 ticketId) public view refundsReady returns (bool) { if (increment == 0) { return false; } else if (holderByTicketId.length <= quantity) { require(ticketId < holderByTicketId.length, "Out of Range"); return true; } else { return (increment * ticketId + offset) % holderByTicketId.length < quantity; } } /** * @dev Are non-winners able to withdraw their deposits yet? */ function availableRefund (address holder, uint256[] calldata ticketIds) public view refundsReady returns (uint256) { uint256 refund = 0; for (uint i = 0; i < ticketIds.length; i++) { uint256 ticketId = ticketIds[i]; if (holder == holderByTicketId[ticketId]) { refund += deposit; if (isWinner(ticketId)) { refund -= price; } } } return refund; } /** * @dev Claim deposited funds after raffle is over. * For non-winning tickets, their entire deposit is refunded. * For winning tickets, the difference between the deposit price and the actual price is refunded. * In either case the ticket is destroyed after refunding. This refunds some gas to the ticket owner, making this operation less costly. */ function claimRefund (uint256[] calldata ticketIds) public refundsReady { uint256 refund = 0; for (uint i = 0; i < ticketIds.length; i++) { uint256 ticketId = ticketIds[i]; if (msg.sender == holderByTicketId[ticketId]) { refund += deposit; if (isWinner(ticketId)) { refund -= price; } delete holderByTicketId[ticketId]; } } if (refund > 0) { (bool success,) = payable(msg.sender).call{value: refund}(""); require(success, "Refund Transfer Failed"); } } /** * @dev Allow `owner` to claim remaining funds. * Losing raffle tickets have 90 days to claim their refunds. After that time the owner of the raffle is entitled to sweep the rest of the ETH. */ function claimBalance () public onlyOwner { // After ~90 days, contract owner can claim all funds require (block.number > (endBlockNumber + 600_000)); (bool success,) = owner.call{value: address(this).balance}(""); require(success, "Claim Failed"); } /** * @dev Allow `owner` to withdraw income from winning tickets after winners have been picked. */ function claimIncome () public onlyOwner { require(increment > 0, "Not Shuffled"); require(!incomeClaimed, "Income Claimed"); incomeClaimed = true; uint256 balance; if (holderByTicketId.length <= quantity) { balance = holderByTicketId.length * price; } else { balance = quantity * price; } (bool success,) = owner.call{value: balance}(""); require(success, "Claim Failed"); } ///// Administration ///// /** * @dev Start the raffle. */ function openMinting (uint256 durationInBlocks) public onlyOwner { require(startBlockNumber == 0, "Minting Started"); endBlockNumber = block.number + durationInBlocks; startBlockNumber = block.number; } /** * @dev Specify a contract to be used as a Validator of all ticket entries. */ function activateValidation (address validatorContractAddress) public onlyOwner { validatorActive = true; Validator = IDepositRaffleValidator(validatorContractAddress); } /** * @dev Disable any Validator for this raffle. */ function deactivateValidation () public onlyOwner { validatorActive = false; } /** * @dev Allow current `owner` to transfer ownership to another address */ function transferOwnership (address payable newOwner) public onlyOwner { owner = newOwner; } /** * @dev Rescue ERC20 assets sent directly to this contract. */ function withdrawForeignERC20 (address tokenContract) public onlyOwner { IERC20 token = IERC20(tokenContract); token.transfer(owner, token.balanceOf(address(this))); } /** * @dev Rescue ERC721 assets sent directly to this contract. */ function withdrawForeignERC721 (address tokenContract, uint256 tokenId) public onlyOwner { IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId); } constructor (uint256 depositWei, uint256 priceWei, uint256 totalQuantity) { require (depositWei >= priceWei, "Price > Deposit"); deposit = depositWei; price = priceWei; quantity = totalQuantity; owner = payable(msg.sender); // https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148).claim(msg.sender); } }
Number of winners to draw
uint256 immutable public quantity;
10,859,556
[ 1, 1854, 434, 5657, 9646, 358, 3724, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 11732, 1071, 10457, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Own { address public owner; function Own() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Pause is Own { bool public stopped; modifier stopInEmergency { if (stopped) { throw; } _; } modifier onlyInEmergency { if (!stopped) { throw; } _; } // owner call to trigger a stop state function emergencyStop() external onlyOwner { stopped = true; } // owner call to restart from the stop state function release() external onlyOwner onlyInEmergency { stopped = false; } } contract Puller { using SafeMath for uint; mapping(address => uint) public payments; event LogRefundETH(address to, uint value); function asyncSend(address dest, uint amount) internal { payments[dest] = payments[dest].add(amount); } // withdrwaw call for refunding balance acumilated by payee function withdrawPayments() { address payee = msg.sender; uint payment = payments[payee]; if (payment == 0) { throw; } if (this.balance < payment) { throw; } payments[payee] = 0; if (!payee.send(payment)) { throw; } LogRefundETH(payee,payment); } } contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } function approve(address _spender, uint _value) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract Token is StandardToken, Own { string public constant name = "TribeToken"; string public constant symbol = "TRIBE"; uint public constant decimals = 6; // Token constructor function Token() { totalSupply = 200000000000000; balances[msg.sender] = totalSupply; // send all created tokens to the owner/creator } // Burn function to burn a set amount of tokens function burner(uint _value) onlyOwner returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(msg.sender, 0x0, _value); return true; } } contract Crowdsale is Pause, Puller { using SafeMath for uint; struct Backer { uint weiReceived; // Amount of Ether given uint coinSent; } //CONSTANTS // Maximum number of TRIBE to sell uint public constant MAX_CAP = 160000000000000; // 160 000 000 TRIBE // Minimum amount to invest uint public constant MIN_INVEST_ETHER = 100 finney; // 0.1ETH // Crowdsale period uint private constant CROWDSALE_PERIOD = 22 days; // 22 days crowdsale run // Number of TRIBE per Ether uint public constant COIN_PER_ETHER = 3000000000; // 3 000 TRIBE //VARIABLES // TRIBE contract reference Token public coin; // Multisig contract that will receive the Ether address public multisigEther; // Number of Ether received uint public etherReceived; // Number of TRIBE sent to Ether contributors uint public coinSentToEther; // Number of TRIBE to burn uint public coinToBurn; // Crowdsale start time uint public startTime; // Crowdsale end time uint public endTime; // Is crowdsale still on going bool public crowdsaleClosed; // Refund open variable bool public refundsOpen; // Backers Ether indexed by their Ethereum address mapping(address => Backer) public backers; //MODIFIERS modifier respectTimeFrame() { if ((now < startTime) || (now > endTime )) throw; _; } modifier refundStatus() { if ((refundsOpen != true )) throw; _; } //EVENTS event LogReceivedETH(address addr, uint value); event LogCoinsEmited(address indexed from, uint amount); //Crowdsale Constructor function Crowdsale(address _TRIBEAddress, address _to) { coin = Token(_TRIBEAddress); multisigEther = _to; } // Default function to receive ether function() stopInEmergency respectTimeFrame payable { receiveETH(msg.sender); } // To call to start the crowdsale function start() onlyOwner { if (startTime != 0) throw; // Crowdsale was already started startTime = now ; endTime = now + CROWDSALE_PERIOD; } // Main function on ETH receive function receiveETH(address beneficiary) internal { if (msg.value < MIN_INVEST_ETHER) throw; // Do not accept investment if the amount is lower than the minimum allowed investment uint coinToSend = bonus(msg.value.mul(COIN_PER_ETHER).div(1 ether)); // Calculate the amount of tokens to send if (coinToSend.add(coinSentToEther) > MAX_CAP) throw; Backer backer = backers[beneficiary]; coin.transfer(beneficiary, coinToSend); // Transfer TRIBE backer.coinSent = backer.coinSent.add(coinToSend); backer.weiReceived = backer.weiReceived.add(msg.value); // Update the total wei collected during the crowdfunding for this backer etherReceived = etherReceived.add(msg.value); // Update the total wei collected during the crowdfunding coinSentToEther = coinSentToEther.add(coinToSend); // Send events LogCoinsEmited(msg.sender ,coinToSend); LogReceivedETH(beneficiary, etherReceived); } // Bonus function for the first week function bonus(uint amount) internal constant returns (uint) { if (now < startTime.add(7 days)) return amount.add(amount.div(5)); // bonus 20% return amount; } // Finalize function function finalize() onlyOwner public { // Check if the crowdsale has ended or if the old tokens have been sold if(coinSentToEther != MAX_CAP){ if (now < endTime) throw; // If Crowdsale still running } if (!multisigEther.send(this.balance)) throw; // Move the remaining Ether to the multisig address uint remains = coin.balanceOf(this); if (remains > 0) { coinToBurn = coinToBurn.add(remains); // Transfer remains to owner to burn coin.transfer(owner, remains); } crowdsaleClosed = true; } // Drain functions in case of unexpected issues with the smart contract. // ETH drain function drain() onlyOwner { if (!multisigEther.send(this.balance)) throw; //Transfer to team multisig wallet } // TOKEN drain function coinDrain() onlyOwner { uint remains = coin.balanceOf(this); coin.transfer(owner, remains); // Transfer to owner wallet } // Change multisig wallet in case its needed function changeMultisig(address addr) onlyOwner public { if (addr == address(0)) throw; multisigEther = addr; } // Change contract ownership function changeTribeOwner() onlyOwner public { coin.transferOwnership(owner); } // Toggle refund state on and off function setRefundState() onlyOwner public { if(refundsOpen == false){ refundsOpen = true; }else{ refundsOpen = false; } } //Refund function when minimum cap isnt reached, this is step is step 2, THIS FUNCTION ONLY AVAILABLE AFTER BEING ENABLED. //STEP1: From TRIBE token contract use "approve" function with the amount of TRIBE you got in total. //STEP2: From TRIBE crowdsale contract use "refund" function with the amount of TRIBE you got in total. //STEP3: From TRIBE crowdsale contract use "withdrawPayement" function to recieve the ETH. function refund(uint _value) refundStatus public { if (_value != backers[msg.sender].coinSent) throw; // compare value from backer balance coin.transferFrom(msg.sender, address(this), _value); // get the token back to the crowdsale contract uint ETHToSend = backers[msg.sender].weiReceived; backers[msg.sender].weiReceived=0; if (ETHToSend > 0) { asyncSend(msg.sender, ETHToSend); // pull payment to get refund in ETH } } } library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } }
Change multisig wallet in case its needed
function changeMultisig(address addr) onlyOwner public { if (addr == address(0)) throw; multisigEther = addr; }
12,689,692
[ 1, 3043, 22945, 360, 9230, 316, 648, 2097, 3577, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 2549, 5049, 291, 360, 12, 2867, 3091, 13, 1338, 5541, 1071, 288, 203, 202, 202, 430, 261, 4793, 422, 1758, 12, 20, 3719, 604, 31, 203, 202, 202, 23978, 360, 41, 1136, 273, 3091, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/40/0x76569fbe7B45Aa83723F590a95807BA94849a5c2/sources/omnidex/nft-marketplace/ERC721NFTMarketV1.sol
creator fee (100 = 1%, 500 = 5%, 5 = 0.05%)
uint256 creatorFee;
9,543,077
[ 1, 20394, 14036, 261, 6625, 273, 404, 9, 16, 6604, 273, 1381, 9, 16, 1381, 273, 374, 18, 6260, 9, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 4202, 2254, 5034, 11784, 14667, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.5.0 <0.6.0; /** * @title Ownable * @dev Provides a modifier that requires the caller to be the owner of the contract. */ contract Ownable { address payable public owner; address public ZERO_ADDRESS = address(0); event OwnerTransferred( address indexed oldOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } // Note: Do we need to be concerned with someone setting owner of a clone contract before we can? // Checks that msg.sender is the owner OR that owner is a ZER_ADDRESS (no contract owner) modifier onlyOwner() { require(msg.sender == owner || owner == ZERO_ADDRESS, "Owner account is required"); _; } /** * Allows the current owner to transfer control of the contract to newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwner(address payable newOwner) public onlyOwner { require(newOwner != owner, "New Owner cannot be the current owner"); require(newOwner != address(0), "New Owner cannot be zero address"); address payable prevOwner = owner; owner = newOwner; emit OwnerTransferred(prevOwner, newOwner); } }
* Allows the current owner to transfer control of the contract to newOwner. @param newOwner The address to transfer ownership to./
function transferOwner(address payable newOwner) public onlyOwner { require(newOwner != owner, "New Owner cannot be the current owner"); require(newOwner != address(0), "New Owner cannot be zero address"); address payable prevOwner = owner; owner = newOwner; emit OwnerTransferred(prevOwner, newOwner); }
1,040,486
[ 1, 19132, 326, 783, 3410, 358, 7412, 3325, 434, 326, 6835, 358, 394, 5541, 18, 225, 394, 5541, 1021, 1758, 358, 7412, 23178, 358, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 5541, 12, 2867, 8843, 429, 394, 5541, 13, 203, 565, 1071, 203, 565, 1338, 5541, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 3410, 16, 315, 1908, 16837, 2780, 506, 326, 783, 3410, 8863, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 315, 1908, 16837, 2780, 506, 3634, 1758, 8863, 203, 3639, 1758, 8843, 429, 2807, 5541, 273, 3410, 31, 203, 3639, 3410, 273, 394, 5541, 31, 203, 3639, 3626, 16837, 1429, 4193, 12, 10001, 5541, 16, 394, 5541, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /// @author David Li <[email protected]> /// @dev basic authentication contract /// @notice tracks list of all users contract Authentication { struct User { bytes32 name; uint256 created_at; } event UserCreated(address indexed _address, bytes32 _name, uint256 _created_at); event UserUpdated(address indexed _address, bytes32 _name); event UserDeleted(address indexed _address); mapping (address => User) private users; // public array that contains list of all users that have registered address[] public allUsers; modifier onlyExistingUser { // Check if user exists or terminate require(!(users[msg.sender].name == 0x0)); _; } modifier onlyValidName(bytes32 name) { // Only valid names allowed require(!(name == 0x0)); _; } /// @return username function login() public view onlyExistingUser returns (bytes32) { return (users[msg.sender].name); } /// @param name the username to be created. /// @dev checks if user exists /// If yes return user name /// If no, check if name was sent /// If yes, create and return user /// @return username of created user function signup(bytes32 name) public payable onlyValidName(name) returns (bytes32) { if (users[msg.sender].name == 0x0) { users[msg.sender].name = name; users[msg.sender].created_at = now; allUsers.push(msg.sender); emit UserCreated(msg.sender,name,now); return (users[msg.sender].name); } return (users[msg.sender].name); } /// @param name updating username /// @dev updating user name /// @return updated username function update(bytes32 name) public payable onlyValidName(name) onlyExistingUser returns (bytes32) { // Update user name. if (users[msg.sender].name != 0x0) { users[msg.sender].name = name; emit UserUpdated(msg.sender,name); return (users[msg.sender].name); } } /// @dev destroy existing username function destroy () public onlyExistingUser { delete users[msg.sender]; emit UserDeleted(msg.sender); } }
public array that contains list of all users that have registered
address[] public allUsers;
15,870,659
[ 1, 482, 526, 716, 1914, 666, 434, 777, 3677, 716, 1240, 4104, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 1758, 8526, 1071, 777, 6588, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-02-22 */ // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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) { return a + b; } /** * @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 a - b; } /** * @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) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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 a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting 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) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: contracts/Blimpie/IERC721Batch.sol pragma solidity ^0.8.0; interface IERC721Batch { function isOwnerOf( address account, uint[] calldata tokenIds ) external view returns( bool ); function transferBatch( address from, address to, uint[] calldata tokenIds, bytes calldata data ) external; function walletOfOwner( address account ) external view returns( uint[] memory ); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @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"); (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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @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 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. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/Blimpie/PaymentSplitterMod.sol pragma solidity ^0.8.0; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitterMod is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } function _addPayee(address account, uint256 shares_) internal { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } function _setPayee( uint index, address account, uint newShares ) internal { _totalShares = _totalShares - _shares[ account ] + newShares; _shares[ account ] = newShares; _payees[ index ] = account; } } // File: contracts/Blimpie/ERC721B.sol pragma solidity ^0.8.0; /**************************************** * @author: squeebo_nft * * @team: GoldenX * **************************************** * Blimpie-ERC721 provides low-gas * * mints + transfers * ****************************************/ abstract contract ERC721B is Context, ERC165, IERC721, IERC721Metadata { using Address for address; string private _name; string private _symbol; uint internal _burned; uint internal _offset; address[] internal _owners; mapping(uint => address) internal _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_, uint offset) { _name = name_; _symbol = symbol_; _offset = offset; for(uint i; i < _offset; ++i ){ _owners.push(address(0)); } } //public function balanceOf(address owner) public view virtual override returns (uint) { require(owner != address(0), "ERC721: balance query for the zero address"); uint count; for( uint i; i < _owners.length; ++i ){ if( owner == _owners[i] ) ++count; } return count; } function name() external view virtual override returns (string memory) { return _name; } function ownerOf(uint tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function symbol() external view virtual override returns (string memory) { return _symbol; } function totalSupply() public view virtual returns (uint) { return _owners.length - (_offset + _burned); } function approve(address to, uint tokenId) external virtual override { address owner = ERC721B.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function setApprovalForAll(address operator, bool approved) external virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function transferFrom( address from, address to, uint tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint tokenId ) external virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } //internal function _approve(address to, uint tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721B.ownerOf(tokenId), to, tokenId); } function _beforeTokenTransfer( address from, address to, uint tokenId ) internal virtual {} function _burn(uint tokenId) internal virtual { address owner = ERC721B.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } function _checkOnERC721Received( address from, address to, uint tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _exists(uint tokenId) internal view virtual returns (bool) { return tokenId < _owners.length && _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721B.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _mint(address to, uint tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners.push(to); emit Transfer(address(0), to, tokenId); } function _next() internal view virtual returns( uint ){ return _owners.length; } function _safeMint(address to, uint tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _safeTransfer( address from, address to, uint tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _transfer( address from, address to, uint tokenId ) internal virtual { require(ERC721B.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } } // File: contracts/Blimpie/ERC721EnumerableLite.sol pragma solidity ^0.8.0; /**************************************** * @author: squeebo_nft * **************************************** * Blimpie-ERC721 provides low-gas * * mints + transfers * ****************************************/ abstract contract ERC721EnumerableLite is ERC721B, IERC721Batch, IERC721Enumerable { mapping(address => uint) internal _balances; function isOwnerOf( address account, uint[] calldata tokenIds ) external view virtual override returns( bool ){ for(uint i; i < tokenIds.length; ++i ){ if( _owners[ tokenIds[i] ] != account ) return false; } return true; } function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721B) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function tokenOfOwnerByIndex(address owner, uint index) public view override returns (uint tokenId) { uint count; for( uint i; i < _owners.length; ++i ){ if( owner == _owners[i] ){ if( count == index ) return i; else ++count; } } revert("ERC721Enumerable: owner index out of bounds"); } function tokenByIndex(uint index) external view virtual override returns (uint) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return index; } function totalSupply() public view virtual override( ERC721B, IERC721Enumerable ) returns (uint) { return _owners.length - (_offset + _burned); } function transferBatch( address from, address to, uint[] calldata tokenIds, bytes calldata data ) external override{ for(uint i; i < tokenIds.length; ++i ){ safeTransferFrom( from, to, tokenIds[i], data ); } } function walletOfOwner( address account ) external view virtual override returns( uint[] memory ){ uint quantity = balanceOf( account ); uint[] memory wallet = new uint[]( quantity ); for( uint i; i < quantity; ++i ){ wallet[i] = tokenOfOwnerByIndex( account, i ); } return wallet; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @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. */ abstract 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() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual 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 virtual onlyOwner { _transferOwnership(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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/Blimpie/Delegated.sol pragma solidity ^0.8.0; /*********************** * @author: squeebo_nft * ************************/ contract Delegated is Ownable{ mapping(address => bool) internal _delegates; constructor(){ _delegates[owner()] = true; } modifier onlyDelegates { require(_delegates[msg.sender], "Invalid delegate" ); _; } //onlyOwner function isDelegate( address addr ) external view onlyOwner returns ( bool ){ return _delegates[addr]; } function setDelegate( address addr, bool isDelegate_ ) external onlyOwner{ _delegates[addr] = isDelegate_; } function transferOwnership(address newOwner) public virtual override onlyOwner { _delegates[newOwner] = true; super.transferOwnership( newOwner ); } } // File: contracts/goadgauds.sol pragma solidity ^0.8.0; contract _goatgauds is Delegated, ERC721EnumerableLite, PaymentSplitterMod { using Strings for uint; uint public MAX_ORDER = 2; uint public MAX_SUPPLY = 2222; uint public MAINSALE_PRICE = 0.125 ether; uint public PRESALE_PRICE = 0.1 ether; bool public isMintActive = false; bool public isPresaleActive = false; mapping(address=>uint) public accessList; string private _tokenURIPrefix = ''; string private _tokenURISuffix = ''; address[] private addressList = [ 0xF5c774b504C1D82fb59e3B826555D67033A13b01, 0x7Cf39e8D6F6f9F25E925Dad7EB371276231780d7, 0xC02Dd50b25364e747410730A1df9B72A92C3C68B, 0x286777D6ad08EbE395C377078a17a32c21564a8a, 0x00eCb19318d98ff57173Ac8EdFb7a5D90ba2005d, 0x2E169A7c3D8EBeC11D5b43Dade06Ac29FEf59cb3, 0x693B22BB92727Fb2a9a4D7e1b1D65B3E8168B774 ]; uint[] private shareList = [ 5, 5, 5, 5, 30, 25, 25 ]; constructor() Delegated() ERC721B("Goat Gauds", "GG", 0) PaymentSplitterMod( addressList, shareList ){ } //public view fallback() external payable {} function tokenURI(uint tokenId) external view override returns (string memory) { require(_exists(tokenId), "Query for nonexistent token"); return string(abi.encodePacked(_tokenURIPrefix, tokenId.toString(), _tokenURISuffix)); } //public payable function presale( uint quantity ) external payable { require( isPresaleActive, "Presale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); require( msg.value >= PRESALE_PRICE * quantity, "Ether sent is not correct" ); require( accessList[msg.sender] > 0, "Not authorized" ); uint supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Mint/order exceeds supply" ); accessList[msg.sender] -= quantity; for(uint i; i < quantity; ++i){ _mint( msg.sender, supply++ ); } } function mint( uint quantity ) external payable { require( isMintActive, "Sale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); require( msg.value >= MAINSALE_PRICE * quantity, "Ether sent is not correct" ); uint supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Mint/order exceeds supply" ); for(uint i; i < quantity; ++i){ _mint( msg.sender, supply++ ); } } //delegated payable function burnFrom( address owner, uint[] calldata tokenIds ) external payable onlyDelegates{ for(uint i; i < tokenIds.length; ++i ){ require( _exists( tokenIds[i] ), "Burn for nonexistent token" ); require( _owners[ tokenIds[i] ] == owner, "Owner mismatch" ); _burn( tokenIds[i] ); } } function mintTo(uint[] calldata quantity, address[] calldata recipient) external payable onlyDelegates{ require(quantity.length == recipient.length, "Must provide equal quantities and recipients" ); uint totalQuantity; uint supply = totalSupply(); for(uint i; i < quantity.length; ++i){ totalQuantity += quantity[i]; } require( supply + totalQuantity <= MAX_SUPPLY, "Mint/order exceeds supply" ); for(uint i; i < recipient.length; ++i){ for(uint j; j < quantity[i]; ++j){ _mint( recipient[i], supply++ ); } } } //delegated nonpayable function resurrect( uint[] calldata tokenIds, address[] calldata recipients ) external onlyDelegates{ require(tokenIds.length == recipients.length, "Must provide equal tokenIds and recipients" ); address to; uint tokenId; address zero = address(0); for(uint i; i < tokenIds.length; ++i ){ to = recipients[i]; require(recipients[i] != address(0), "resurrect to the zero address" ); tokenId = tokenIds[i]; require( !_exists( tokenId ), "can't resurrect existing token" ); _owners[tokenId] = to; // Clear approvals _approve(zero, tokenId); emit Transfer(zero, to, tokenId); } } function setAccessList(address[] calldata accounts, uint[] calldata quantities) external onlyDelegates{ require(accounts.length == quantities.length, "Must provide equal accounts and quantities" ); for(uint i; i < accounts.length; ++i){ accessList[ accounts[i] ] = quantities[i]; } } function setActive(bool isPresaleActive_, bool isMintActive_) external onlyDelegates{ require( isPresaleActive != isPresaleActive_ || isMintActive != isMintActive_, "New value matches old" ); isPresaleActive = isPresaleActive_; isMintActive = isMintActive_; } function setBaseURI(string calldata newPrefix, string calldata newSuffix) external onlyDelegates{ _tokenURIPrefix = newPrefix; _tokenURISuffix = newSuffix; } function setMax(uint maxOrder, uint maxSupply) external onlyDelegates{ require( MAX_ORDER != maxOrder || MAX_SUPPLY != maxSupply, "New value matches old" ); require(maxSupply >= totalSupply(), "Specified supply is lower than current balance" ); MAX_ORDER = maxOrder; MAX_SUPPLY = maxSupply; } function setPrice(uint presalePrice, uint mainsalePrice ) external onlyDelegates{ require( PRESALE_PRICE != presalePrice || MAINSALE_PRICE != mainsalePrice, "New value matches old" ); PRESALE_PRICE = presalePrice; MAINSALE_PRICE = mainsalePrice; } //owner function addPayee(address account, uint256 shares_) external onlyOwner { _addPayee(account, shares_); } function setPayee( uint index, address account, uint newShares ) external onlyOwner { _setPayee(index, account, newShares); } //internal function _burn(uint tokenId) internal override { address curOwner = ERC721B.ownerOf(tokenId); // Clear approvals _approve(owner(), tokenId); _owners[tokenId] = address(0); emit Transfer(curOwner, address(0), tokenId); } function _mint(address to, uint tokenId) internal override { _owners.push(to); emit Transfer(address(0), to, tokenId); } }
delegated nonpayable Clear approvals
function resurrect( uint[] calldata tokenIds, address[] calldata recipients ) external onlyDelegates{ require(tokenIds.length == recipients.length, "Must provide equal tokenIds and recipients" ); address to; uint tokenId; address zero = address(0); for(uint i; i < tokenIds.length; ++i ){ to = recipients[i]; require(recipients[i] != address(0), "resurrect to the zero address" ); tokenId = tokenIds[i]; require( !_exists( tokenId ), "can't resurrect existing token" ); _owners[tokenId] = to; _approve(zero, tokenId); emit Transfer(zero, to, tokenId); } }
2,149,010
[ 1, 3771, 1332, 690, 1661, 10239, 429, 10121, 6617, 4524, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 400, 295, 2607, 12, 2254, 8526, 745, 892, 1147, 2673, 16, 1758, 8526, 745, 892, 12045, 262, 3903, 1338, 15608, 815, 95, 203, 565, 2583, 12, 2316, 2673, 18, 2469, 422, 12045, 18, 2469, 16, 282, 315, 10136, 5615, 3959, 1147, 2673, 471, 12045, 6, 11272, 203, 203, 565, 1758, 358, 31, 203, 565, 2254, 1147, 548, 31, 203, 565, 1758, 3634, 273, 1758, 12, 20, 1769, 203, 565, 364, 12, 11890, 277, 31, 277, 411, 1147, 2673, 18, 2469, 31, 965, 77, 262, 95, 203, 1377, 358, 273, 12045, 63, 77, 15533, 203, 1377, 2583, 12, 27925, 63, 77, 65, 480, 1758, 12, 20, 3631, 315, 455, 295, 2607, 358, 326, 3634, 1758, 6, 11272, 203, 203, 1377, 1147, 548, 273, 1147, 2673, 63, 77, 15533, 203, 1377, 2583, 12, 401, 67, 1808, 12, 1147, 548, 262, 16, 315, 4169, 1404, 400, 295, 2607, 2062, 1147, 6, 11272, 203, 203, 4202, 203, 1377, 389, 995, 414, 63, 2316, 548, 65, 273, 358, 31, 203, 1377, 389, 12908, 537, 12, 7124, 16, 1147, 548, 1769, 203, 1377, 3626, 12279, 12, 7124, 16, 358, 16, 1147, 548, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 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 SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 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 * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 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' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _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(IERC20 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, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @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"); (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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 128 bits"); return uint192(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; interface IYearnTokenVault { function balanceOf(address user) external view returns (uint256); function pricePerShare() external view returns (uint256); function deposit(uint256 lp, address user) external; function withdraw( uint256 amount, address user, uint256 slippage ) external; function decimals() external view returns (uint8); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; import "./ISwapData.sol"; interface IBaseStrategy { function underlying() external view returns (IERC20); function getStrategyBalance() external view returns (uint128); function getStrategyUnderlyingWithRewards() external view returns(uint128); function process(uint256[] calldata, bool, SwapData[] calldata) external; function processReallocation(uint256[] calldata, ProcessReallocationData calldata) external returns(uint128); function processDeposit(uint256[] calldata) external; function fastWithdraw(uint128, uint256[] calldata, SwapData[] calldata) external returns(uint128); function claimRewards(SwapData[] calldata) external; function emergencyWithdraw(address recipient, uint256[] calldata data) external; function initialize() external; function disable() external; } struct ProcessReallocationData { uint128 sharesToWithdraw; uint128 optimizedShares; uint128 optimizedWithdrawnAmount; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; /** * @notice Strict holding information how to swap the asset * @member slippage minumum output amount * @member path swap path, first byte represents an action (e.g. Uniswap V2 custom swap), rest is swap specific path */ struct SwapData { uint256 slippage; // min amount out bytes path; // 1st byte is action, then path } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "../external/@openzeppelin/utils/SafeCast.sol"; /** * @notice A collection of custom math ustils used throughout the system */ library Math { function min(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? b : a; } function getProportion128(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) { return SafeCast.toUint128(((mul1 * mul2) / div)); } function getProportion128Unchecked(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) { unchecked { return uint128((mul1 * mul2) / div); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /** @notice Handle setting zero value in a storage word as uint128 max value. * * @dev * The purpose of this is to avoid resetting a storage word to the zero value; * the gas cost of re-initializing the value is the same as setting the word originally. * so instead, if word is to be set to zero, we set it to uint128 max. * * - anytime a word is loaded from storage: call "get" * - anytime a word is written to storage: call "set" * - common operations on uints are also bundled here. * * NOTE: This library should ONLY be used when reading or writing *directly* from storage. */ library Max128Bit { uint128 internal constant ZERO = type(uint128).max; function get(uint128 a) internal pure returns(uint128) { return (a == ZERO) ? 0 : a; } function set(uint128 a) internal pure returns(uint128){ return (a == 0) ? ZERO : a; } function add(uint128 a, uint128 b) internal pure returns(uint128 c){ a = get(a); c = set(a + b); } } // SPDX-License-Identifier: BUSL-1.1 import "../interfaces/ISwapData.sol"; pragma solidity 0.8.11; /// @notice Strategy struct for all strategies struct Strategy { uint128 totalShares; /// @notice Denotes strategy completed index uint24 index; /// @notice Denotes whether strategy is removed /// @dev after removing this value can never change, hence strategy cannot be added back again bool isRemoved; /// @notice Pending geposit amount and pending shares withdrawn by all users for next index Pending pendingUser; /// @notice Used if strategies "dohardwork" hasn't been executed yet in the current index Pending pendingUserNext; /// @dev Usually a temp variable when compounding mapping(address => uint256) pendingRewards; /// @dev Usually a temp variable when compounding uint128 pendingDepositReward; /// @notice Amount of lp tokens the strategy holds, NOTE: not all strategies use it uint256 lpTokens; // ----- REALLOCATION VARIABLES ----- bool isInDepositPhase; /// @notice Used to store amount of optimized shares, so they can be substracted at the end /// @dev Only for temporary use, should be reset to 0 in same transaction uint128 optimizedSharesWithdrawn; /// @dev Underlying amount pending to be deposited from other strategies at reallocation /// @dev resets after the strategy reallocation DHW is finished uint128 pendingReallocateDeposit; /// @notice Stores amount of optimized underlying amount when reallocating /// @dev resets after the strategy reallocation DHW is finished /// @dev This is "virtual" amount that was matched between this strategy and others when reallocating uint128 pendingReallocateOptimizedDeposit; // ------------------------------------ /// @notice Total underlying amoung at index mapping(uint256 => TotalUnderlying) totalUnderlying; /// @notice Batches stored after each DHW with index as a key /// @dev Holds information for vauls to redeem newly gained shares and withdrawn amounts belonging to users mapping(uint256 => Batch) batches; /// @notice Batches stored after each DHW reallocating (if strategy was set to reallocate) /// @dev Holds information for vauls to redeem newly gained shares and withdrawn shares to complete reallocation mapping(uint256 => BatchReallocation) reallocationBatches; /// @notice Vaults holding this strategy shares mapping(address => Vault) vaults; /// @notice Future proof storage mapping(bytes32 => AdditionalStorage) additionalStorage; /// @dev Make sure to reset it to 0 after emergency withdrawal uint256 emergencyPending; } /// @notice Unprocessed deposit underlying amount and strategy share amount from users struct Pending { uint128 deposit; uint128 sharesToWithdraw; } /// @notice Struct storing total underlying balance of a strategy for an index, along with total shares at same index struct TotalUnderlying { uint128 amount; uint128 totalShares; } /// @notice Stored after executing DHW for each index. /// @dev This is used for vaults to redeem their deposit. struct Batch { /// @notice total underlying deposited in index uint128 deposited; uint128 depositedReceived; uint128 depositedSharesReceived; uint128 withdrawnShares; uint128 withdrawnReceived; } /// @notice Stored after executing reallocation DHW each index. struct BatchReallocation { /// @notice Deposited amount received from reallocation uint128 depositedReallocation; /// @notice Received shares from reallocation uint128 depositedReallocationSharesReceived; /// @notice Used to know how much tokens was received for reallocating uint128 withdrawnReallocationReceived; /// @notice Amount of shares to withdraw for reallocation uint128 withdrawnReallocationShares; } /// @notice VaultBatches could be refactored so we only have 2 structs current and next (see how Pending is working) struct Vault { uint128 shares; /// @notice Withdrawn amount as part of the reallocation uint128 withdrawnReallocationShares; /// @notice Index to action mapping(uint256 => VaultBatch) vaultBatches; } /// @notice Stores deposited and withdrawn shares by the vault struct VaultBatch { /// @notice Vault index to deposited amount mapping uint128 deposited; /// @notice Vault index to withdrawn user shares mapping uint128 withdrawnShares; } /// @notice Used for reallocation calldata struct VaultData { address vault; uint8 strategiesCount; uint256 strategiesBitwise; uint256 newProportions; } /// @notice Calldata when executing reallocatin DHW /// @notice Used in the withdraw part of the reallocation DHW struct ReallocationWithdrawData { uint256[][] reallocationTable; StratUnderlyingSlippage[] priceSlippages; RewardSlippages[] rewardSlippages; uint256[] stratIndexes; uint256[][] slippages; } /// @notice Calldata when executing reallocatin DHW /// @notice Used in the deposit part of the reallocation DHW struct ReallocationData { uint256[] stratIndexes; uint256[][] slippages; } /// @notice In case some adapters need extra storage struct AdditionalStorage { uint256 value; address addressValue; uint96 value96; } /// @notice Strategy total underlying slippage, to verify validity of the strategy state struct StratUnderlyingSlippage { uint128 min; uint128 max; } /// @notice Containig information if and how to swap strategy rewards at the DHW /// @dev Passed in by the do-hard-worker struct RewardSlippages { bool doClaim; SwapData[] swapData; } /// @notice Helper struct to compare strategy share between eachother /// @dev Used for reallocation optimization of shares (strategy matching deposits and withdrawals between eachother when reallocating) struct PriceData { uint128 totalValue; uint128 totalShares; } /// @notice Strategy reallocation values after reallocation optimization of shares was calculated struct ReallocationShares { uint128[] optimizedWithdraws; uint128[] optimizedShares; uint128[] totalSharesWithdrawn; } /// @notice Shared storage for multiple strategies /// @dev This is used when strategies are part of the same proticil (e.g. Curve 3pool) struct StrategiesShared { uint184 value; uint32 lastClaimBlock; uint32 lastUpdateBlock; uint8 stratsCount; mapping(uint256 => address) stratAddresses; mapping(bytes32 => uint256) bytesValues; } /// @notice Base storage shared betweek Spool contract and Strategies /// @dev this way we can use same values when performing delegate call /// to strategy implementations from the Spool contract abstract contract BaseStorage { // ----- DHW VARIABLES ----- /// @notice Force while DHW (all strategies) to be executed in only one transaction /// @dev This is enforced to increase the gas efficiency of the system /// Can be removed by the DAO if gas gost of the strategies goes over the block limit bool internal forceOneTxDoHardWork; /// @notice Global index of the system /// @dev Insures the correct strategy DHW execution. /// Every strategy in the system must be equal or one less than global index value /// Global index increments by 1 on every do-hard-work uint24 public globalIndex; /// @notice number of strategies unprocessed (by the do-hard-work) in the current index to be completed uint8 internal doHardWorksLeft; // ----- REALLOCATION VARIABLES ----- /// @notice Used for offchain execution to get the new reallocation table. bool internal logReallocationTable; /// @notice number of withdrawal strategies unprocessed (by the do-hard-work) in the current index /// @dev only used when reallocating /// after it reaches 0, deposit phase of the reallocation can begin uint8 public withdrawalDoHardWorksLeft; /// @notice Index at which next reallocation is set uint24 public reallocationIndex; /// @notice 2D table hash containing information of how strategies should be reallocated between eachother /// @dev Created when allocation provider sets reallocation for the vaults /// This table is stored as a hash in the system and verified on reallocation DHW /// Resets to 0 after reallocation DHW is completed bytes32 internal reallocationTableHash; /// @notice Hash of all the strategies array in the system at the time when reallocation was set for index /// @dev this array is used for the whole reallocation period even if a strategy gets exploited when reallocating. /// This way we can remove the strategy from the system and not breaking the flow of the reallocaton /// Resets when DHW is completed bytes32 internal reallocationStrategiesHash; // ----------------------------------- /// @notice Denoting if an address is the do-hard-worker mapping(address => bool) public isDoHardWorker; /// @notice Denoting if an address is the allocation provider mapping(address => bool) public isAllocationProvider; /// @notice Strategies shared storage /// @dev used as a helper storage to save common inoramation mapping(bytes32 => StrategiesShared) internal strategiesShared; /// @notice Mapping of strategy implementation address to strategy system values mapping(address => Strategy) public strategies; /// @notice Flag showing if disable was skipped when a strategy has been removed /// @dev If true disable can still be run mapping(address => bool) internal _skippedDisable; /// @notice Flag showing if after removing a strategy emergency withdraw can still be executed /// @dev If true emergency withdraw can still be executed mapping(address => bool) internal _awaitingEmergencyWithdraw; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; /// @title Common Spool contracts constants abstract contract BaseConstants { /// @dev 2 digits precision uint256 internal constant FULL_PERCENT = 100_00; /// @dev Accuracy when doing shares arithmetics uint256 internal constant ACCURACY = 10**30; } /// @title Contains USDC token related values abstract contract USDC { /// @notice USDC token contract address IERC20 internal constant USDC_ADDRESS = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../interfaces/IBaseStrategy.sol"; import "../shared/BaseStorage.sol"; import "../shared/Constants.sol"; import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol"; import "../libraries/Math.sol"; import "../libraries/Max/128Bit.sol"; /** * @notice Implementation of the {IBaseStrategy} interface. * * @dev * This implementation of the {IBaseStrategy} is meant to operate * on single-collateral strategies and uses a delta system to calculate * whether a withdrawal or deposit needs to be performed for a particular * strategy. */ abstract contract BaseStrategy is IBaseStrategy, BaseStorage, BaseConstants { using SafeERC20 for IERC20; using Max128Bit for uint128; /* ========== CONSTANTS ========== */ /// @notice minimum shares size to avoid loss of share due to computation precision uint128 private constant MIN_SHARES = 10**8; /* ========== STATE VARIABLES ========== */ /// @notice The total slippage slots the strategy supports, used for validation of provided slippage uint256 internal immutable rewardSlippageSlots; /// @notice Slots for processing uint256 internal immutable processSlippageSlots; /// @notice Slots for reallocation uint256 internal immutable reallocationSlippageSlots; /// @notice Slots for deposit uint256 internal immutable depositSlippageSlots; /** * @notice do force claim of rewards. * * @dev * Some strategies auto claim on deposit/withdraw, * so execute the claim actions to store the reward amounts. */ bool internal immutable forceClaim; /// @notice flag to force balance validation before running process strategy /// @dev this is done so noone can manipulate the strategies before we interact with them and cause harm to the system bool internal immutable doValidateBalance; /// @notice The self address, set at initialization to allow proper share accounting address internal immutable self; /// @notice The underlying asset of the strategy IERC20 public immutable override underlying; /* ========== CONSTRUCTOR ========== */ /** * @notice Initializes the base strategy values. * * @dev * It performs certain pre-conditional validations to ensure the contract * has been initialized properly, such as that the address argument of the * underlying asset is valid. * * Slippage slots for certain strategies may be zero if there is no compounding * work to be done. * * @param _underlying token used for deposits * @param _rewardSlippageSlots slots for rewards * @param _processSlippageSlots slots for processing * @param _reallocationSlippageSlots slots for reallocation * @param _depositSlippageSlots slots for deposits * @param _forceClaim force claim of rewards * @param _doValidateBalance force balance validation */ constructor( IERC20 _underlying, uint256 _rewardSlippageSlots, uint256 _processSlippageSlots, uint256 _reallocationSlippageSlots, uint256 _depositSlippageSlots, bool _forceClaim, bool _doValidateBalance ) { require( _underlying != IERC20(address(0)), "BaseStrategy::constructor: Underlying address cannot be 0" ); self = address(this); underlying = _underlying; rewardSlippageSlots = _rewardSlippageSlots; processSlippageSlots = _processSlippageSlots; reallocationSlippageSlots = _reallocationSlippageSlots; depositSlippageSlots = _depositSlippageSlots; forceClaim = _forceClaim; doValidateBalance = _doValidateBalance; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Process the latest pending action of the strategy * * @dev * it yields amount of funds processed as well as the reward buffer of the strategy. * The function will auto-compound rewards if requested and supported. * * Requirements: * * - the slippages provided must be valid in length * - if the redeposit flag is set to true, the strategy must support * compounding of rewards * * @param slippages slippages to process * @param redeposit if redepositing is to occur * @param swapData swap data for processing */ function process(uint256[] calldata slippages, bool redeposit, SwapData[] calldata swapData) external override { slippages = _validateStrategyBalance(slippages); if (forceClaim || redeposit) { _validateRewardsSlippage(swapData); _processRewards(swapData); } if (processSlippageSlots != 0) _validateProcessSlippage(slippages); _process(slippages, 0); } /** * @notice Process first part of the reallocation DHW * @dev Withdraws for reallocation, depositn and withdraww for a user * * @param slippages Parameters to apply when performing a deposit or a withdraw * @param processReallocationData Data containing amuont of optimized and not optimized shares to withdraw * @return withdrawnReallocationReceived actual amount recieveed from peforming withdraw */ function processReallocation(uint256[] calldata slippages, ProcessReallocationData calldata processReallocationData) external override returns(uint128) { slippages = _validateStrategyBalance(slippages); if (reallocationSlippageSlots != 0) _validateReallocationSlippage(slippages); _process(slippages, processReallocationData.sharesToWithdraw); uint128 withdrawnReallocationReceived = _updateReallocationWithdraw(processReallocationData); return withdrawnReallocationReceived; } /** * @dev Update reallocation batch storage for index after withdrawing reallocated shares * @param processReallocationData Data containing amount of optimized and not optimized shares to withdraw * @return Withdrawn reallocation received */ function _updateReallocationWithdraw(ProcessReallocationData calldata processReallocationData) internal virtual returns(uint128) { Strategy storage strategy = strategies[self]; uint24 stratIndex = _getProcessingIndex(); BatchReallocation storage batch = strategy.reallocationBatches[stratIndex]; // save actual withdrawn amount, without optimized one uint128 withdrawnReallocationReceived = batch.withdrawnReallocationReceived; strategy.optimizedSharesWithdrawn += processReallocationData.optimizedShares; batch.withdrawnReallocationReceived += processReallocationData.optimizedWithdrawnAmount; batch.withdrawnReallocationShares = processReallocationData.optimizedShares + processReallocationData.sharesToWithdraw; return withdrawnReallocationReceived; } /** * @notice Process deposit * @param slippages Array of slippage parameters to apply when depositing */ function processDeposit(uint256[] calldata slippages) external override { slippages = _validateStrategyBalance(slippages); if (depositSlippageSlots != 0) _validateDepositSlippage(slippages); _processDeposit(slippages); } /** * @notice Returns total starategy balance includign pending rewards * @return strategyBalance total starategy balance includign pending rewards */ function getStrategyUnderlyingWithRewards() public view override returns(uint128) { return _getStrategyUnderlyingWithRewards(); } /** * @notice Fast withdraw * @param shares Shares to fast withdraw * @param slippages Array of slippage parameters to apply when withdrawing * @param swapData Swap slippage and path array * @return Withdrawn amount withdawn */ function fastWithdraw(uint128 shares, uint256[] calldata slippages, SwapData[] calldata swapData) external override returns(uint128) { slippages = _validateStrategyBalance(slippages); _validateRewardsSlippage(swapData); if (processSlippageSlots != 0) _validateProcessSlippage(slippages); uint128 withdrawnAmount = _processFastWithdraw(shares, slippages, swapData); strategies[self].totalShares -= shares; return withdrawnAmount; } /** * @notice Claims and possibly compounds strategy rewards. * * @param swapData swap data for processing */ function claimRewards(SwapData[] calldata swapData) external override { _validateRewardsSlippage(swapData); _processRewards(swapData); } /** * @notice Withdraws all actively deployed funds in the strategy, liquifying them in the process. * * @param recipient recipient of the withdrawn funds * @param data data necessary execute the emergency withdraw */ function emergencyWithdraw(address recipient, uint256[] calldata data) external virtual override { uint256 balanceBefore = underlying.balanceOf(address(this)); _emergencyWithdraw(recipient, data); uint256 balanceAfter = underlying.balanceOf(address(this)); uint256 withdrawnAmount = 0; if (balanceAfter > balanceBefore) { withdrawnAmount = balanceAfter - balanceBefore; } Strategy storage strategy = strategies[self]; if (strategy.emergencyPending > 0) { withdrawnAmount += strategy.emergencyPending; strategy.emergencyPending = 0; } // also withdraw all unprocessed deposit for a strategy if (strategy.pendingUser.deposit.get() > 0) { withdrawnAmount += strategy.pendingUser.deposit.get(); strategy.pendingUser.deposit = 0; } if (strategy.pendingUserNext.deposit.get() > 0) { withdrawnAmount += strategy.pendingUserNext.deposit.get(); strategy.pendingUserNext.deposit = 0; } // if strategy was already processed in the current index that hasn't finished yet, // transfer the withdrawn amount // reset total underlying to 0 if (strategy.index == globalIndex && doHardWorksLeft > 0) { uint256 withdrawnReceived = strategy.batches[strategy.index].withdrawnReceived; withdrawnAmount += withdrawnReceived; strategy.batches[strategy.index].withdrawnReceived = 0; strategy.totalUnderlying[strategy.index].amount = 0; } if (withdrawnAmount > 0) { // check if the balance is high enough to withdraw the total withdrawnAmount if (balanceAfter < withdrawnAmount) { // if not withdraw the current balance withdrawnAmount = balanceAfter; } underlying.safeTransfer(recipient, withdrawnAmount); } } /** * @notice Initialize a strategy. * @dev Execute strategy specific one-time actions if needed. */ function initialize() external virtual override {} /** * @notice Disables a strategy. * @dev Cleans strategy specific values if needed. */ function disable() external virtual override {} /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev Validate strategy balance * @param slippages Check if the strategy balance is within defined min and max values * @return slippages Same array without first 2 slippages */ function _validateStrategyBalance(uint256[] calldata slippages) internal virtual returns(uint256[] calldata) { if (doValidateBalance) { require(slippages.length >= 2, "BaseStrategy:: _validateStrategyBalance: Invalid number of slippages"); uint128 strategyBalance = getStrategyBalance(); require( slippages[0] <= strategyBalance && slippages[1] >= strategyBalance, "BaseStrategy::_validateStrategyBalance: Bad strategy balance" ); return slippages[2:]; } return slippages; } /** * @dev Validate reards slippage * @param swapData Swap slippage and path array */ function _validateRewardsSlippage(SwapData[] calldata swapData) internal view virtual { if (swapData.length > 0) { require( swapData.length == _getRewardSlippageSlots(), "BaseStrategy::_validateSlippage: Invalid Number of reward slippages Defined" ); } } /** * @dev Retrieve reward slippage slots * @return Reward slippage slots */ function _getRewardSlippageSlots() internal view virtual returns(uint256) { return rewardSlippageSlots; } /** * @dev Validate process slippage * @param slippages parameters to verify validity of the strategy state */ function _validateProcessSlippage(uint256[] calldata slippages) internal view virtual { _validateSlippage(slippages.length, processSlippageSlots); } /** * @dev Validate reallocation slippage * @param slippages parameters to verify validity of the strategy state */ function _validateReallocationSlippage(uint256[] calldata slippages) internal view virtual { _validateSlippage(slippages.length, reallocationSlippageSlots); } /** * @dev Validate deposit slippage * @param slippages parameters to verify validity of the strategy state */ function _validateDepositSlippage(uint256[] calldata slippages) internal view virtual { _validateSlippage(slippages.length, depositSlippageSlots); } /** * @dev Validates the provided slippage in length. * @param currentLength actual slippage array length * @param shouldBeLength expected slippages array length */ function _validateSlippage(uint256 currentLength, uint256 shouldBeLength) internal view virtual { require( currentLength == shouldBeLength, "BaseStrategy::_validateSlippage: Invalid Number of Slippages Defined" ); } /** * @dev Retrieve processing index * @return Processing index */ function _getProcessingIndex() internal view returns(uint24) { return strategies[self].index + 1; } /** * @dev Calculates shares before they are added to the total shares * @param strategyTotalShares Total shares for strategy * @param stratTotalUnderlying Total underlying for strategy * @return newShares New shares calculated */ function _getNewSharesAfterWithdraw(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares){ uint128 oldUnderlying; if (stratTotalUnderlying > depositAmount) { oldUnderlying = stratTotalUnderlying - depositAmount; } if (strategyTotalShares == 0 || oldUnderlying == 0) { // Enforce minimum shares size to avoid loss of share due to computation precision newShares = (0 < depositAmount && depositAmount < MIN_SHARES) ? MIN_SHARES : depositAmount; } else { newShares = Math.getProportion128(depositAmount, strategyTotalShares, oldUnderlying); } } /** * @dev Calculates shares when they are already part of the total shares * * @param strategyTotalShares Total shares * @param stratTotalUnderlying Total underlying * @return newShares New shares calculated */ function _getNewShares(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares){ if (strategyTotalShares == 0 || stratTotalUnderlying == 0) { // Enforce minimum shares size to avoid loss of share due to computation precision newShares = (0 < depositAmount && depositAmount < MIN_SHARES) ? MIN_SHARES : depositAmount; } else { newShares = Math.getProportion128(depositAmount, strategyTotalShares, stratTotalUnderlying); } } /** * @dev Reset allowance to zero if previously set to a higher value. * @param token Asset * @param spender Spender address */ function _resetAllowance(IERC20 token, address spender) internal { if (token.allowance(address(this), spender) > 0) { token.safeApprove(spender, 0); } } /* ========== VIRTUAL FUNCTIONS ========== */ function getStrategyBalance() public view virtual override returns (uint128); function _processRewards(SwapData[] calldata) internal virtual; function _emergencyWithdraw(address recipient, uint256[] calldata data) internal virtual; function _process(uint256[] memory, uint128 reallocateSharesToWithdraw) internal virtual; function _processDeposit(uint256[] memory) internal virtual; function _getStrategyUnderlyingWithRewards() internal view virtual returns(uint128); function _processFastWithdraw(uint128, uint256[] memory, SwapData[] calldata) internal virtual returns(uint128); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./ProcessStrategy.sol"; /** * @notice No reward strategy logic */ abstract contract NoRewardStrategy is ProcessStrategy { /* ========== CONSTRUCTOR ========== */ /** * @notice Set initial values * @param _underlying Underlying asset * @param _processSlippageSlots Slots for processing * @param _reallocationSlippageSlots Slots for reallocation * @param _depositSlippageSlots Slots for deposits * @param _doValidateBalance Force balance validation */ constructor( IERC20 _underlying, uint256 _processSlippageSlots, uint256 _reallocationSlippageSlots, uint256 _depositSlippageSlots, bool _doValidateBalance ) BaseStrategy( _underlying, 0, _processSlippageSlots, _reallocationSlippageSlots, _depositSlippageSlots, false, _doValidateBalance ) {} /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Returns total strategy balance including pending rewards * @return strategyBalance total strategy balance including pending rewards */ function _getStrategyUnderlyingWithRewards() internal view override virtual returns(uint128) { return getStrategyBalance(); } /** * @notice Process rewards - not supported */ function _processRewards(SwapData[] calldata) internal pure override { revert("NoRewardStrategy::_processRewards: Strategy does not have rewards"); } /** * @notice Process fast withdraw * @param shares Amount of shares * @param slippages Slippages array * @return withdrawnAmount Underlying withdrawn amount */ function _processFastWithdraw(uint128 shares, uint256[] memory slippages, SwapData[] calldata) internal virtual override returns(uint128) { return _withdraw(shares, slippages); } function _validateRewardsSlippage(SwapData[] calldata) internal view override {} } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./BaseStrategy.sol"; import "../libraries/Max/128Bit.sol"; import "../libraries/Math.sol"; struct ProcessInfo { uint128 totalWithdrawReceived; uint128 userDepositReceived; } /** * @notice Process strategy logic */ abstract contract ProcessStrategy is BaseStrategy { using Max128Bit for uint128; /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Process the strategy pending deposits, withdrawals, and collected strategy rewards * @dev * Deposit amount amd withdrawal shares are matched between eachother, effecively only one of * those 2 is called. Shares are converted to the dollar value, based on the current strategy * total balance. This ensures the minimum amount of assets are moved around to lower the price * drift and total fees paid to the protocols the strategy is interacting with (if there are any) * * @param slippages Strategy slippage values verifying the validity of the strategy state * @param reallocateSharesToWithdraw Reallocation shares to withdraw (non-zero only if reallocation DHW is in progress, otherwise 0) */ function _process(uint256[] memory slippages, uint128 reallocateSharesToWithdraw) internal override virtual { // PREPARE Strategy storage strategy = strategies[self]; uint24 processingIndex = _getProcessingIndex(); Batch storage batch = strategy.batches[processingIndex]; uint128 strategyTotalShares = strategy.totalShares; uint128 pendingSharesToWithdraw = strategy.pendingUser.sharesToWithdraw.get(); uint128 userDeposit = strategy.pendingUser.deposit.get(); // CALCULATE THE ACTION // if withdrawing for reallocating, add shares to total withdraw shares if (reallocateSharesToWithdraw > 0) { pendingSharesToWithdraw += reallocateSharesToWithdraw; } // total deposit received from users + compound reward (if there are any) uint128 totalPendingDeposit = userDeposit; // add compound reward (pendingDepositReward) to deposit uint128 withdrawalReward = 0; if (strategy.pendingDepositReward > 0) { uint128 pendingDepositReward = strategy.pendingDepositReward; totalPendingDeposit += pendingDepositReward; // calculate compound reward (withdrawalReward) for users withdrawing in this batch if (pendingSharesToWithdraw > 0 && strategyTotalShares > 0) { withdrawalReward = Math.getProportion128(pendingSharesToWithdraw, pendingDepositReward, strategyTotalShares); // substract withdrawal reward from total deposit totalPendingDeposit -= withdrawalReward; } // Reset pendingDepositReward strategy.pendingDepositReward = 0; } // if there is no pending deposit or withdrawals, return if (totalPendingDeposit == 0 && pendingSharesToWithdraw == 0) { return; } uint128 pendingWithdrawalAmount = 0; if (pendingSharesToWithdraw > 0) { pendingWithdrawalAmount = Math.getProportion128(getStrategyBalance(), pendingSharesToWithdraw, strategyTotalShares); } // ACTION: DEPOSIT OR WITHDRAW ProcessInfo memory processInfo; if (totalPendingDeposit > pendingWithdrawalAmount) { // DEPOSIT // uint128 amount = totalPendingDeposit - pendingWithdrawalAmount; uint128 depositReceived = _deposit(totalPendingDeposit - pendingWithdrawalAmount, slippages); processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward; // pendingWithdrawalAmount is optimized deposit: totalPendingDeposit - amount; uint128 totalDepositReceived = depositReceived + pendingWithdrawalAmount; // calculate user deposit received, excluding compound rewards processInfo.userDepositReceived = Math.getProportion128(totalDepositReceived, userDeposit, totalPendingDeposit); } else if (totalPendingDeposit < pendingWithdrawalAmount) { // WITHDRAW // uint128 amount = pendingWithdrawalAmount - totalPendingDeposit; uint128 withdrawReceived = _withdraw( // calculate back the shares from actual withdraw amount // NOTE: we can do unchecked calculation and casting as // the multiplier is always smaller than the divisor Math.getProportion128Unchecked( (pendingWithdrawalAmount - totalPendingDeposit), pendingSharesToWithdraw, pendingWithdrawalAmount ), slippages ); // optimized withdraw is total pending deposit: pendingWithdrawalAmount - amount = totalPendingDeposit; processInfo.totalWithdrawReceived = withdrawReceived + totalPendingDeposit + withdrawalReward; processInfo.userDepositReceived = userDeposit; } else { processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward; processInfo.userDepositReceived = userDeposit; } // UPDATE STORAGE AFTER { uint128 stratTotalUnderlying = getStrategyBalance(); // Update withdraw batch if (pendingSharesToWithdraw > 0) { batch.withdrawnReceived = processInfo.totalWithdrawReceived; batch.withdrawnShares = pendingSharesToWithdraw; strategyTotalShares -= pendingSharesToWithdraw; // update reallocation batch if (reallocateSharesToWithdraw > 0) { BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex]; uint128 withdrawnReallocationReceived = Math.getProportion128(processInfo.totalWithdrawReceived, reallocateSharesToWithdraw, pendingSharesToWithdraw); reallocationBatch.withdrawnReallocationReceived = withdrawnReallocationReceived; // substract reallocation values from user values batch.withdrawnReceived -= withdrawnReallocationReceived; batch.withdrawnShares -= reallocateSharesToWithdraw; } } // Update deposit batch if (userDeposit > 0) { uint128 newShares = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, processInfo.userDepositReceived); batch.deposited = userDeposit; batch.depositedReceived = processInfo.userDepositReceived; batch.depositedSharesReceived = newShares; strategyTotalShares += newShares; } // Update shares if (strategyTotalShares != strategy.totalShares) { strategy.totalShares = strategyTotalShares; } // Set underlying at index strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying; strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares; } } /** * @notice Process deposit * @param slippages Slippages array */ function _processDeposit(uint256[] memory slippages) internal override virtual { Strategy storage strategy = strategies[self]; uint128 depositOptimizedAmount = strategy.pendingReallocateOptimizedDeposit; uint128 optimizedSharesWithdrawn = strategy.optimizedSharesWithdrawn; uint128 depositAmount = strategy.pendingReallocateDeposit; // if a strategy is not part of reallocation return if ( depositOptimizedAmount == 0 && optimizedSharesWithdrawn == 0 && depositAmount == 0 ) { return; } uint24 processingIndex = _getProcessingIndex(); BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex]; uint128 strategyTotalShares = strategy.totalShares; // get shares from optimized deposit if (depositOptimizedAmount > 0) { uint128 stratTotalUnderlying = getStrategyBalance(); uint128 newShares = _getNewShares(strategyTotalShares, stratTotalUnderlying, depositOptimizedAmount); // add new shares strategyTotalShares += newShares; // update reallocation batch reallocationBatch.depositedReallocation = depositOptimizedAmount; reallocationBatch.depositedReallocationSharesReceived = newShares; strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying; // reset strategy.pendingReallocateOptimizedDeposit = 0; } // remove optimized withdraw shares if (optimizedSharesWithdrawn > 0) { strategyTotalShares -= optimizedSharesWithdrawn; // reset strategy.optimizedSharesWithdrawn = 0; } // get shares from actual deposit if (depositAmount > 0) { // deposit uint128 depositReceived = _deposit(depositAmount, slippages); // NOTE: might return it from _deposit (only certain strategies need it) uint128 stratTotalUnderlying = getStrategyBalance(); uint128 newShares = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, depositReceived); // add new shares strategyTotalShares += newShares; // update reallocation batch reallocationBatch.depositedReallocation += depositReceived; reallocationBatch.depositedReallocationSharesReceived += newShares; strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying; // reset strategy.pendingReallocateDeposit = 0; } // update share storage strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares; strategy.totalShares = strategyTotalShares; } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice get the value of the strategy shares in the underlying tokens * @param shares Number of shares * @return amount Underling amount representing the `share` value of the strategy */ function _getSharesToAmount(uint256 shares) internal virtual returns(uint128 amount) { amount = Math.getProportion128( getStrategyBalance(), shares, strategies[self].totalShares ); } /** * @notice get slippage amount, and action type (withdraw/deposit). * @dev * Most significant bit represents an action, 0 for a withdrawal and 1 for deposit. * * This ensures the slippage will be used for the action intended by the do-hard-worker, * otherwise the transavtion will revert. * * @param slippageAction number containing the slippage action and the actual slippage amount * @return isDeposit Flag showing if the slippage is for the deposit action * @return slippage the slippage value cleaned of the most significant bit */ function _getSlippageAction(uint256 slippageAction) internal pure returns (bool isDeposit, uint256 slippage) { // remove most significant bit slippage = (slippageAction << 1) >> 1; // if values are not the same (the removed bit was 1) set action to deposit if (slippageAction != slippage) { isDeposit = true; } } /* ========== VIRTUAL FUNCTIONS ========== */ function _deposit(uint128 amount, uint256[] memory slippages) internal virtual returns(uint128 depositReceived); function _withdraw(uint128 shares, uint256[] memory slippages) internal virtual returns(uint128 withdrawReceived); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol"; import "../NoRewardStrategy.sol"; import "../../external/interfaces/yearn/IYearnTokenVault.sol"; /** * @notice Yearn Strategy implementation */ contract YearnStrategy is NoRewardStrategy { using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ /// @notice Vault contract IYearnTokenVault public immutable vault; /// @notice One yearn vault share amount uint256 public immutable oneShare; /* ========== CONSTRUCTOR ========== */ /** * @notice Set initial values * @param _vault Vault contract * @param _underlying Underlying asset */ constructor( IYearnTokenVault _vault, IERC20 _underlying ) NoRewardStrategy(_underlying, 1, 1, 1, false) { require(address(_vault) != address(0), "YearnStrategy::constructor: Vault address cannot be 0"); vault = _vault; oneShare = 10**uint256(_vault.decimals()); } /* ========== VIEWS ========== */ /** * @notice Get strategy balance * @return Strategy balance */ function getStrategyBalance() public view override returns(uint128) { uint256 yearnTokenAmount = vault.balanceOf(address(this)); return SafeCast.toUint128(_getYearnTokenValue(yearnTokenAmount)); } /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Deposit * @param amount Amount to deposit * @param slippages Slippages array * @return Minted idle amount */ function _deposit(uint128 amount, uint256[] memory slippages) internal override returns(uint128) { (bool isDeposit, uint256 slippage) = _getSlippageAction(slippages[0]); require(isDeposit, "YearnStrategy::_deposit: Withdraw slippage provided"); // deposit underlying underlying.safeApprove(address(vault), amount); uint256 yearnTokenBefore = vault.balanceOf(address(this)); vault.deposit(amount, address(this)); uint256 yearnTokenNew = vault.balanceOf(address(this)) - yearnTokenBefore; _resetAllowance(underlying, address(vault)); require( yearnTokenNew >= slippage, "YearnStrategy::_deposit: Insufficient Yearn Amount Minted" ); return SafeCast.toUint128(_getYearnTokenValue(yearnTokenNew)); } /** * @notice Withdraw * @param shares Shares to withdraw * @param slippages Slippages array * @return Underlying withdrawn */ function _withdraw(uint128 shares, uint256[] memory slippages) internal override returns(uint128) { (bool isDeposit, uint256 slippage) = _getSlippageAction(slippages[0]); require(!isDeposit, "YearnStrategy::_withdraw: Deposit slippage provided"); uint256 yearnTokenBalance = vault.balanceOf(address(this)); uint256 yearnTokenWithdraw = (yearnTokenBalance * shares) / strategies[self].totalShares; // withdraw idle tokens from vault uint256 undelyingBefore = underlying.balanceOf(address(this)); vault.withdraw(yearnTokenWithdraw, address(this), slippage); uint256 undelyingWithdrawn = underlying.balanceOf(address(this)) - undelyingBefore; return SafeCast.toUint128(undelyingWithdrawn); } /** * @notice Emergency withdraw * @param recipient Address to withdraw to * @param data Data to perform emergency withdrawal */ function _emergencyWithdraw(address recipient, uint256[] calldata data) internal override { // if no data provided set max loss to 100% uint256 maxLoss = data.length > 0 ? data[0] : 100_00; vault.withdraw( type(uint256).max, recipient, maxLoss ); } /* ========== PRIVATE FUNCTIONS ========== */ function _getYearnTokenValue(uint256 yearnTokenAmount) private view returns(uint256) { if (yearnTokenAmount == 0) return 0; return (yearnTokenAmount * vault.pricePerShare()) / oneShare; } }
* @notice Process fast withdraw @param shares Amount of shares @param slippages Slippages array @return withdrawnAmount Underlying withdrawn amount/
function _processFastWithdraw(uint128 shares, uint256[] memory slippages, SwapData[] calldata) internal virtual override returns(uint128) { return _withdraw(shares, slippages); }
1,124,709
[ 1, 2227, 4797, 598, 9446, 225, 24123, 16811, 434, 24123, 225, 272, 3169, 7267, 348, 3169, 7267, 526, 327, 598, 9446, 82, 6275, 21140, 6291, 598, 9446, 82, 3844, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2567, 12305, 1190, 9446, 12, 11890, 10392, 24123, 16, 2254, 5034, 8526, 3778, 272, 3169, 7267, 16, 12738, 751, 8526, 745, 892, 13, 2713, 5024, 3849, 1135, 12, 11890, 10392, 13, 288, 203, 3639, 327, 389, 1918, 9446, 12, 30720, 16, 272, 3169, 7267, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x0AF971Bd8aae4EE3e29Acb3077B760e16D0D81FD/sources/contracts/dna.sol
set as marketing wallet
marketingWallet = address(0xE2d4c45310F2d02068A64333dbf98AA6794Ab473);
4,975,542
[ 1, 542, 487, 13667, 310, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 13667, 310, 16936, 273, 1758, 12, 20, 17432, 22, 72, 24, 71, 7950, 23, 2163, 42, 22, 72, 3103, 7677, 28, 37, 1105, 3707, 23, 1966, 74, 10689, 5284, 26, 7235, 24, 5895, 24, 9036, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xBA4F8bBEE30181678ECB14564D78Db39d223E960/sources/MaximusSniper.sol
If liquidity is over the treshold, convert 100% of Token to Marketing BNB to avoid overliquifying
function isOverLiquified() public view returns(bool){ return _balances[_pancakePairAddress]>_circulatingSupply*overLiquifyTreshold/1000; }
2,757,939
[ 1, 2047, 4501, 372, 24237, 353, 1879, 326, 268, 3444, 16, 1765, 2130, 9, 434, 3155, 358, 6622, 21747, 605, 20626, 358, 4543, 1879, 549, 372, 1164, 310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 4851, 48, 18988, 939, 1435, 1071, 1476, 1135, 12, 6430, 15329, 203, 3639, 327, 389, 70, 26488, 63, 67, 7355, 23780, 4154, 1887, 65, 34, 67, 11614, 1934, 1776, 3088, 1283, 14, 1643, 48, 18988, 1164, 56, 3444, 19, 18088, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.2; pragma experimental ABIEncoderV2; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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); } // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ // /** * @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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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; } } // /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @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"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { 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); } } } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 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 * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 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), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 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(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: 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(IERC20 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, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract DSMath { 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"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; //rounds to zero if x*y < WAD / 2 function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } library ProtocolAdapterTypes { enum OptionType {Invalid, Put, Call} // We have 2 types of purchase methods so far - by contract and by 0x. // Contract is simple because it involves just specifying the option terms you want to buy. // ZeroEx involves an off-chain API call which prepares a ZeroExOrder object to be passed into the tx. enum PurchaseMethod {Invalid, Contract, ZeroEx} /** * @notice Terms of an options contract * @param underlying is the underlying asset of the options. E.g. For ETH $800 CALL, ETH is the underlying. * @param strikeAsset is the asset used to denote the asset paid out when exercising the option. * E.g. For ETH $800 CALL, USDC is the strikeAsset. * @param collateralAsset is the asset used to collateralize a short position for the option. * @param expiry is the expiry of the option contract. Users can only exercise after expiry in Europeans. * @param strikePrice is the strike price of an optio contract. * E.g. For ETH $800 CALL, 800*10**18 is the USDC. * @param optionType is the type of option, can only be OptionType.Call or OptionType.Put * @param paymentToken is the token used to purchase the option. * E.g. Buy UNI/USDC CALL with WETH as the paymentToken. */ struct OptionTerms { address underlying; address strikeAsset; address collateralAsset; uint256 expiry; uint256 strikePrice; ProtocolAdapterTypes.OptionType optionType; address paymentToken; } /** * @notice 0x order for purchasing otokens * @param exchangeAddress [deprecated] is the address we call to conduct a 0x trade. * Slither flagged this as a potential vulnerability so we hardcoded it. * @param buyTokenAddress is the otoken address * @param sellTokenAddress is the token used to purchase USDC. This is USDC most of the time. * @param allowanceTarget is the address the adapter needs to provide sellToken allowance to so the swap happens * @param protocolFee is the fee paid (in ETH) when conducting the trade * @param makerAssetAmount is the buyToken amount * @param takerAssetAmount is the sellToken amount * @param swapData is the encoded msg.data passed by the 0x api response */ struct ZeroExOrder { address exchangeAddress; address buyTokenAddress; address sellTokenAddress; address allowanceTarget; uint256 protocolFee; uint256 makerAssetAmount; uint256 takerAssetAmount; bytes swapData; } } interface IProtocolAdapter { /** * @notice Emitted when a new option contract is purchased */ event Purchased( address indexed caller, string indexed protocolName, address indexed underlying, uint256 amount, uint256 optionID ); /** * @notice Emitted when an option contract is exercised */ event Exercised( address indexed caller, address indexed options, uint256 indexed optionID, uint256 amount, uint256 exerciseProfit ); /** * @notice Name of the adapter. E.g. "HEGIC", "OPYN_V1". Used as index key for adapter addresses */ function protocolName() external pure returns (string memory); /** * @notice Boolean flag to indicate whether to use option IDs or not. * Fungible protocols normally use tokens to represent option contracts. */ function nonFungible() external pure returns (bool); /** * @notice Returns the purchase method used to purchase options */ function purchaseMethod() external pure returns (ProtocolAdapterTypes.PurchaseMethod); /** * @notice Check if an options contract exist based on the passed parameters. * @param optionTerms is the terms of the option contract */ function optionsExist(ProtocolAdapterTypes.OptionTerms calldata optionTerms) external view returns (bool); /** * @notice Get the options contract's address based on the passed parameters * @param optionTerms is the terms of the option contract */ function getOptionsAddress( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (address); /** * @notice Gets the premium to buy `purchaseAmount` of the option contract in ETH terms. * @param optionTerms is the terms of the option contract * @param purchaseAmount is the number of options purchased */ function premium( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount ) external view returns (uint256 cost); /** * @notice Amount of profit made from exercising an option contract (current price - strike price). * 0 if exercising out-the-money. * @param options is the address of the options contract * @param optionID is the ID of the option position in non fungible protocols like Hegic. * @param amount is the amount of tokens or options contract to exercise. */ function exerciseProfit( address options, uint256 optionID, uint256 amount ) external view returns (uint256 profit); function canExercise( address options, uint256 optionID, uint256 amount ) external view returns (bool); /** * @notice Purchases the options contract. * @param optionTerms is the terms of the option contract * @param amount is the purchase amount in Wad units (10**18) */ function purchase( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount, uint256 maxCost ) external payable returns (uint256 optionID); /** * @notice Exercises the options contract. * @param options is the address of the options contract * @param optionID is the ID of the option position in non fungible protocols like Hegic. * @param amount is the amount of tokens or options contract to exercise. * @param recipient is the account that receives the exercised profits. * This is needed since the adapter holds all the positions */ function exercise( address options, uint256 optionID, uint256 amount, address recipient ) external payable; /** * @notice Opens a short position for a given `optionTerms`. * @param optionTerms is the terms of the option contract * @param amount is the short position amount */ function createShort( ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount ) external returns (uint256); /** * @notice Closes an existing short position. In the future, * we may want to open this up to specifying a particular short position to close. */ function closeShort() external returns (uint256); } library ProtocolAdapter { function delegateOptionsExist( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (bool) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "optionsExist((address,address,address,uint256,uint256,uint8,address))", optionTerms ) ); revertWhenFail(success, result); return abi.decode(result, (bool)); } function delegateGetOptionsAddress( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external view returns (address) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "getOptionsAddress((address,address,address,uint256,uint256,uint8,address))", optionTerms ) ); revertWhenFail(success, result); return abi.decode(result, (address)); } function delegatePremium( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "premium((address,address,address,uint256,uint256,uint8,address),uint256)", optionTerms, purchaseAmount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateExerciseProfit( IProtocolAdapter adapter, address options, uint256 optionID, uint256 amount ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "exerciseProfit(address,uint256,uint256)", options, optionID, amount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegatePurchase( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 purchaseAmount, uint256 maxCost ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "purchase((address,address,address,uint256,uint256,uint8,address),uint256,uint256)", optionTerms, purchaseAmount, maxCost ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegatePurchaseWithZeroEx( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, ProtocolAdapterTypes.ZeroExOrder calldata zeroExOrder ) external { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( // solhint-disable-next-line "purchaseWithZeroEx((address,address,address,uint256,uint256,uint8,address),(address,address,address,address,uint256,uint256,uint256,bytes))", optionTerms, zeroExOrder ) ); revertWhenFail(success, result); } function delegateExercise( IProtocolAdapter adapter, address options, uint256 optionID, uint256 amount, address recipient ) external { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "exercise(address,uint256,uint256,address)", options, optionID, amount, recipient ) ); revertWhenFail(success, result); } function delegateClaimRewards( IProtocolAdapter adapter, address rewardsAddress, uint256[] calldata optionIDs ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "claimRewards(address,uint256[])", rewardsAddress, optionIDs ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateRewardsClaimable( IProtocolAdapter adapter, address rewardsAddress, uint256[] calldata optionIDs ) external view returns (uint256) { (bool success, bytes memory result) = address(adapter).staticcall( abi.encodeWithSignature( "rewardsClaimable(address,uint256[])", rewardsAddress, optionIDs ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateCreateShort( IProtocolAdapter adapter, ProtocolAdapterTypes.OptionTerms calldata optionTerms, uint256 amount ) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature( "createShort((address,address,address,uint256,uint256,uint8,address),uint256)", optionTerms, amount ) ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function delegateCloseShort(IProtocolAdapter adapter) external returns (uint256) { (bool success, bytes memory result) = address(adapter).delegatecall( abi.encodeWithSignature("closeShort()") ); revertWhenFail(success, result); return abi.decode(result, (uint256)); } function revertWhenFail(bool success, bytes memory returnData) private pure { if (success) return; revert(getRevertMsg(returnData)); } function getRevertMsg(bytes memory _returnData) private pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "ProtocolAdapter: reverted"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } } interface IRibbonFactory { function isInstrument(address instrument) external returns (bool); function getAdapter(string calldata protocolName) external view returns (address); function getAdapters() external view returns (address[] memory adaptersArray); function burnGasTokens() external; } interface IRibbonV2Vault { function depositFor(uint256 amount, address creditor) external; } interface IRibbonV1Vault { function deposit(uint256 amount) external; } interface IVaultRegistry { function canWithdrawForFree(address fromVault, address toVault) external returns (bool); function canCrossTrade(address longVault, address shortVault) external returns (bool); } interface IWETH { function deposit() external payable; function withdraw(uint256) external; 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); function decimals() external view returns (uint256); } library Types { struct Order { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 Party signer; // Party to the trade that sets terms Party sender; // Party to the trade that accepts terms Party affiliate; // Party compensated for facilitating (optional) Signature signature; // Signature of the order } struct Party { bytes4 kind; // Interface ID of the token address wallet; // Wallet address of the party address token; // Contract address of the token uint256 amount; // Amount for ERC-20 or ERC-1155 uint256 id; // ID for ERC-721 or ERC-1155 } struct Signature { address signatory; // Address of the wallet used to sign address validator; // Address of the intended swap contract bytes1 version; // EIP-191 signature version uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature } } interface ISwap { event Swap( uint256 indexed nonce, uint256 timestamp, address indexed signerWallet, uint256 signerAmount, uint256 signerId, address signerToken, address indexed senderWallet, uint256 senderAmount, uint256 senderId, address senderToken, address affiliateWallet, uint256 affiliateAmount, uint256 affiliateId, address affiliateToken ); event Cancel(uint256 indexed nonce, address indexed signerWallet); event CancelUpTo(uint256 indexed nonce, address indexed signerWallet); event AuthorizeSender( address indexed authorizerAddress, address indexed authorizedSender ); event AuthorizeSigner( address indexed authorizerAddress, address indexed authorizedSigner ); event RevokeSender( address indexed authorizerAddress, address indexed revokedSender ); event RevokeSigner( address indexed authorizerAddress, address indexed revokedSigner ); /** * @notice Atomic Token Swap * @param order Types.Order */ function swap(Types.Order calldata order) external; /** * @notice Cancel one or more open orders by nonce * @param nonces uint256[] */ function cancel(uint256[] calldata nonces) external; /** * @notice Cancels all orders below a nonce value * @dev These orders can be made active by reducing the minimum nonce * @param minimumNonce uint256 */ function cancelUpTo(uint256 minimumNonce) external; /** * @notice Authorize a delegated sender * @param authorizedSender address */ function authorizeSender(address authorizedSender) external; /** * @notice Authorize a delegated signer * @param authorizedSigner address */ function authorizeSigner(address authorizedSigner) external; /** * @notice Revoke an authorization * @param authorizedSender address */ function revokeSender(address authorizedSender) external; /** * @notice Revoke an authorization * @param authorizedSigner address */ function revokeSigner(address authorizedSigner) external; function senderAuthorizations(address, address) external view returns (bool); function signerAuthorizations(address, address) external view returns (bool); function signerNonceStatus(address, uint256) external view returns (bytes1); function signerMinimumNonce(address) external view returns (uint256); function registry() external view returns (address); } interface OtokenInterface { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @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"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { 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); } } } } // // solhint-disable-next-line compiler-version /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } abstract contract ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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 make 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; } uint256[49] private __gap; } // /* * @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. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual 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 virtual 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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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); } // /** * @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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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; } } contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { 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); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } contract OptionsVaultStorageV1 is ReentrancyGuardUpgradeable, OwnableUpgradeable, ERC20Upgradeable { // DEPRECATED: This variable was originally used to store the asset address we are using as collateral // But due to gas optimization and upgradeability security concerns, // we removed it in favor of using immutable variables // This variable is left here to hold the storage slot for upgrades address private _oldAsset; // Privileged role that is able to select the option terms (strike price, expiry) to short address public manager; // Option that the vault is shorting in the next cycle address public nextOption; // The timestamp when the `nextOption` can be used by the vault uint256 public nextOptionReadyAt; // Option that the vault is currently shorting address public currentOption; // Amount that is currently locked for selling options uint256 public lockedAmount; // Cap for total amount deposited into vault uint256 public cap; // Fee incurred when withdrawing out of the vault, in the units of 10**18 // where 1 ether = 100%, so 0.005 means 0.5% fee uint256 public instantWithdrawalFee; // Recipient for withdrawal fees address public feeRecipient; } contract OptionsVaultStorageV2 { // DEPRECATED FOR V2 // Amount locked for scheduled withdrawals uint256 private queuedWithdrawShares; // DEPRECATED FOR V2 // Mapping to store the scheduled withdrawals (address => withdrawAmount) mapping(address => uint256) private scheduledWithdrawals; } contract OptionsVaultStorageV3 { // Contract address of replacement IRibbonV2Vault public replacementVault; } contract OptionsVaultStorage is OptionsVaultStorageV1, OptionsVaultStorageV2, OptionsVaultStorageV3 { } // contract RibbonThetaVault is DSMath, OptionsVaultStorage { using ProtocolAdapter for IProtocolAdapter; using SafeERC20 for IERC20; using SafeMath for uint256; string private constant _adapterName = "OPYN_GAMMA"; IProtocolAdapter public immutable adapter; IVaultRegistry public immutable registry; address public immutable asset; address public immutable underlying; address public immutable WETH; address public immutable USDC; bool public immutable isPut; uint8 private immutable _decimals; // AirSwap Swap contract // https://github.com/airswap/airswap-protocols/blob/master/source/swap/contracts/interfaces/ISwap.sol ISwap public immutable SWAP_CONTRACT; // 90% locked in options protocol, 10% of the pool reserved for withdrawals uint256 public constant lockedRatio = 0.9 ether; uint256 public constant delay = 1 hours; uint256 public immutable MINIMUM_SUPPLY; event ManagerChanged(address oldManager, address newManager); event Deposit(address indexed account, uint256 amount, uint256 share); event Withdraw( address indexed account, uint256 amount, uint256 share, uint256 fee ); event OpenShort( address indexed options, uint256 depositAmount, address manager ); event CloseShort( address indexed options, uint256 withdrawAmount, address manager ); event WithdrawalFeeSet(uint256 oldFee, uint256 newFee); event CapSet(uint256 oldCap, uint256 newCap, address manager); event VaultSunset(address replacement); event WithdrawToV1Vault( address account, uint256 oldShares, address to, uint256 newShares ); event Migrate( address account, address replacement, uint256 shares, uint256 amount ); /** * @notice Initializes the contract with immutable variables * @param _asset is the asset used for collateral and premiums * @param _weth is the Wrapped Ether contract * @param _usdc is the USDC contract * @param _swapContract is the Airswap Swap contract * @param _tokenDecimals is the decimals for the vault shares. Must match the decimals for _asset. * @param _minimumSupply is the minimum supply for the asset balance and the share supply. * It's important to bake the _factory variable into the contract with the constructor * If we do it in the `initialize` function, users get to set the factory variable and * subsequently the adapter, which allows them to make a delegatecall, then selfdestruct the contract. */ constructor( address _asset, address _factory, address _registry, address _weth, address _usdc, address _swapContract, uint8 _tokenDecimals, uint256 _minimumSupply, bool _isPut ) { require(_asset != address(0), "!_asset"); require(_factory != address(0), "!_factory"); require(_registry != address(0), "!_registry"); require(_weth != address(0), "!_weth"); require(_usdc != address(0), "!_usdc"); require(_swapContract != address(0), "!_swapContract"); require(_tokenDecimals > 0, "!_tokenDecimals"); require(_minimumSupply > 0, "!_minimumSupply"); IRibbonFactory factoryInstance = IRibbonFactory(_factory); address adapterAddr = factoryInstance.getAdapter(_adapterName); require(adapterAddr != address(0), "Adapter not set"); asset = _isPut ? _usdc : _asset; underlying = _asset; adapter = IProtocolAdapter(adapterAddr); registry = IVaultRegistry(_registry); WETH = _weth; USDC = _usdc; SWAP_CONTRACT = ISwap(_swapContract); _decimals = _tokenDecimals; MINIMUM_SUPPLY = _minimumSupply; isPut = _isPut; } /** * @notice Initializes the OptionVault contract with storage variables. * @param _owner is the owner of the contract who can set the manager * @param _feeRecipient is the recipient address for withdrawal fees. * @param _initCap is the initial vault's cap on deposits, the manager can increase this as necessary. * @param _tokenName is the name of the vault share token * @param _tokenSymbol is the symbol of the vault share token */ function initialize( address _owner, address _feeRecipient, uint256 _initCap, string calldata _tokenName, string calldata _tokenSymbol ) external initializer { require(_owner != address(0), "!_owner"); require(_feeRecipient != address(0), "!_feeRecipient"); require(_initCap > 0, "_initCap > 0"); require(bytes(_tokenName).length > 0, "_tokenName != 0x"); require(bytes(_tokenSymbol).length > 0, "_tokenSymbol != 0x"); __ReentrancyGuard_init(); __ERC20_init(_tokenName, _tokenSymbol); __Ownable_init(); transferOwnership(_owner); cap = _initCap; // hardcode the initial withdrawal fee instantWithdrawalFee = 0.005 ether; feeRecipient = _feeRecipient; } /** * @notice Closes the vault and makes it withdraw only. */ function sunset(address upgradeTo) external onlyOwner { require(address(replacementVault) == address(0), "Already sunset"); require(upgradeTo != address(0), "!upgradeTo"); replacementVault = IRibbonV2Vault(upgradeTo); emit VaultSunset(upgradeTo); } /** * @notice Sets the new manager of the vault. * @param newManager is the new manager of the vault */ function setManager(address newManager) external onlyOwner { require(newManager != address(0), "!newManager"); address oldManager = manager; manager = newManager; emit ManagerChanged(oldManager, newManager); } /** * @notice Sets the new fee recipient * @param newFeeRecipient is the address of the new fee recipient */ function setFeeRecipient(address newFeeRecipient) external onlyOwner { require(newFeeRecipient != address(0), "!newFeeRecipient"); feeRecipient = newFeeRecipient; } /** * @notice Sets the new withdrawal fee * @param newWithdrawalFee is the fee paid in tokens when withdrawing */ function setWithdrawalFee(uint256 newWithdrawalFee) external onlyManager { require(newWithdrawalFee > 0, "withdrawalFee != 0"); // cap max withdrawal fees to 30% of the withdrawal amount require(newWithdrawalFee < 0.3 ether, "withdrawalFee >= 30%"); uint256 oldFee = instantWithdrawalFee; emit WithdrawalFeeSet(oldFee, newWithdrawalFee); instantWithdrawalFee = newWithdrawalFee; } /** * @notice Deposits ETH into the contract and mint vault shares. Reverts if the underlying is not WETH. */ function depositETH() external payable nonReentrant { require(asset == WETH, "asset is not WETH"); require(msg.value > 0, "No value passed"); IWETH(WETH).deposit{value: msg.value}(); _deposit(msg.value); } /** * @notice Deposits the `asset` into the contract and mint vault shares. * @param amount is the amount of `asset` to deposit */ function deposit(uint256 amount) external nonReentrant { IERC20(asset).safeTransferFrom(msg.sender, address(this), amount); _deposit(amount); } /** * @notice Mints the vault shares to the msg.sender * @param amount is the amount of `asset` deposited */ function _deposit(uint256 amount) private { uint256 totalWithDepositedAmount = totalBalance(); require(totalWithDepositedAmount < cap, "Cap exceeded"); require( totalWithDepositedAmount >= MINIMUM_SUPPLY, "Insufficient asset balance" ); // amount needs to be subtracted from totalBalance because it has already been // added to it from either IWETH.deposit and IERC20.safeTransferFrom uint256 total = totalWithDepositedAmount.sub(amount); uint256 shareSupply = totalSupply(); // Following the pool share calculation from Alpha Homora: // solhint-disable-next-line // https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L104 uint256 share = shareSupply == 0 ? amount : amount.mul(shareSupply).div(total); require( shareSupply.add(share) >= MINIMUM_SUPPLY, "Insufficient share supply" ); emit Deposit(msg.sender, amount, share); _mint(msg.sender, share); } /** * @notice Withdraws ETH from vault using vault shares * @param share is the number of vault shares to be burned */ function withdrawETH(uint256 share) external nonReentrant { require(asset == WETH, "!WETH"); uint256 withdrawAmount = _withdraw(share, false); IWETH(WETH).withdraw(withdrawAmount); (bool success, ) = msg.sender.call{value: withdrawAmount}(""); require(success, "ETH transfer failed"); } /** * @notice Withdraws WETH from vault using vault shares * @param share is the number of vault shares to be burned */ function withdraw(uint256 share) external nonReentrant { uint256 withdrawAmount = _withdraw(share, false); IERC20(asset).safeTransfer(msg.sender, withdrawAmount); } /** * @notice Withdraw from V1 vault to V1 vault * @notice Waive fee if registered in vault registry * @param share is the number of vault shares to be burned * @param vault is the address of destination V1 vault */ function withdrawToV1Vault(uint256 share, address vault) external nonReentrant { require(vault != address(0), "!vault"); require(share > 0, "!share"); bool feeless = registry.canWithdrawForFree(address(this), vault); require(feeless, "Feeless withdraw to vault not allowed"); uint256 withdrawAmount = _withdraw(share, feeless); // Send assets to new vault rather than user IERC20(asset).safeApprove(vault, withdrawAmount); IRibbonV1Vault(vault).deposit(withdrawAmount); uint256 receivedShares = IERC20(vault).balanceOf(address(this)); IERC20(vault).safeTransfer(msg.sender, receivedShares); emit WithdrawToV1Vault(msg.sender, share, vault, receivedShares); } /** * @notice Burns vault shares and checks if eligible for withdrawal * @param share is the number of vault shares to be burned * @param feeless is whether a withdraw fee is charged */ function _withdraw(uint256 share, bool feeless) private returns (uint256) { (uint256 amountAfterFee, uint256 feeAmount) = withdrawAmountWithShares(share); if (feeless) { amountAfterFee = amountAfterFee.add(feeAmount); feeAmount = 0; } emit Withdraw(msg.sender, amountAfterFee, share, feeAmount); _burn(msg.sender, share); IERC20(asset).safeTransfer(feeRecipient, feeAmount); return amountAfterFee; } /* * @notice Moves msg.sender's deposited funds to new vault w/o fees */ function migrate() external nonReentrant { IRibbonV2Vault vault = replacementVault; require(address(vault) != address(0), "Not sunset"); uint256 allShares = maxWithdrawAmount(msg.sender); (uint256 withdrawAmount, uint256 feeAmount) = withdrawAmountWithShares(allShares); // Since we want to exclude fees, we add them both together withdrawAmount = withdrawAmount.add(feeAmount); emit Migrate(msg.sender, address(vault), allShares, withdrawAmount); _burn(msg.sender, allShares); IERC20(asset).safeApprove(address(vault), withdrawAmount); vault.depositFor(withdrawAmount, msg.sender); } /** * @notice Sets the next option the vault will be shorting, and closes the existing short. * This allows all the users to withdraw if the next option is malicious. */ function commitAndClose( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) external onlyManager nonReentrant { _setNextOption(optionTerms); _closeShort(); } function closeShort() external nonReentrant { _closeShort(); } /** * @notice Sets the next option address and the timestamp at which the * admin can call `rollToNextOption` to open a short for the option. * @param optionTerms is the terms of the option contract */ function _setNextOption( ProtocolAdapterTypes.OptionTerms calldata optionTerms ) private { if (isPut) { require( optionTerms.optionType == ProtocolAdapterTypes.OptionType.Put, "!put" ); } else { require( optionTerms.optionType == ProtocolAdapterTypes.OptionType.Call, "!call" ); } address option = adapter.getOptionsAddress(optionTerms); require(option != address(0), "!option"); OtokenInterface otoken = OtokenInterface(option); require(otoken.isPut() == isPut, "Option type does not match"); require( otoken.underlyingAsset() == underlying, "Wrong underlyingAsset" ); require(otoken.collateralAsset() == asset, "Wrong collateralAsset"); // we just assume all options use USDC as the strike require(otoken.strikeAsset() == USDC, "strikeAsset != USDC"); uint256 readyAt = block.timestamp.add(delay); require( otoken.expiryTimestamp() >= readyAt, "Option expiry cannot be before delay" ); nextOption = option; nextOptionReadyAt = readyAt; } /** * @notice Closes the existing short position for the vault. */ function _closeShort() private { address oldOption = currentOption; currentOption = address(0); lockedAmount = 0; if (oldOption != address(0)) { OtokenInterface otoken = OtokenInterface(oldOption); require( block.timestamp > otoken.expiryTimestamp(), "Cannot close short before expiry" ); uint256 withdrawAmount = adapter.delegateCloseShort(); emit CloseShort(oldOption, withdrawAmount, msg.sender); } } /* * @notice Rolls the vault's funds into a new short position. */ function rollToNextOption() external onlyManager nonReentrant { require( block.timestamp >= nextOptionReadyAt, "Cannot roll before delay" ); address newOption = nextOption; require(newOption != address(0), "No found option"); currentOption = newOption; nextOption = address(0); uint256 currentBalance = assetBalance(); uint256 shortAmount = wmul(currentBalance, lockedRatio); lockedAmount = shortAmount; OtokenInterface otoken = OtokenInterface(newOption); ProtocolAdapterTypes.OptionTerms memory optionTerms = ProtocolAdapterTypes.OptionTerms( otoken.underlyingAsset(), USDC, otoken.collateralAsset(), otoken.expiryTimestamp(), otoken.strikePrice().mul(10**10), // scale back to 10**18 isPut ? ProtocolAdapterTypes.OptionType.Put : ProtocolAdapterTypes.OptionType.Call, // isPut address(0) ); uint256 shortBalance = adapter.delegateCreateShort(optionTerms, shortAmount); IERC20 optionToken = IERC20(newOption); optionToken.safeApprove(address(SWAP_CONTRACT), shortBalance); emit OpenShort(newOption, shortAmount, msg.sender); } /** * @notice Withdraw from the options protocol by closing short in an event of a emergency */ function emergencyWithdrawFromShort() external onlyManager nonReentrant { address oldOption = currentOption; require(oldOption != address(0), "!currentOption"); currentOption = address(0); nextOption = address(0); lockedAmount = 0; uint256 withdrawAmount = adapter.delegateCloseShort(); emit CloseShort(oldOption, withdrawAmount, msg.sender); } /** * @notice Performs a swap of `currentOption` token to `asset` token with a counterparty * @param order is an Airswap order */ function sellOptions(Types.Order calldata order) external onlyManager { require( order.sender.wallet == address(this), "Sender can only be vault" ); require( order.sender.token == currentOption, "Can only sell currentOption" ); require(order.signer.token == asset, "Can only buy with asset token"); SWAP_CONTRACT.swap(order); } /** * @notice Sets a new cap for deposits * @param newCap is the new cap for deposits */ function setCap(uint256 newCap) external onlyManager { uint256 oldCap = cap; cap = newCap; emit CapSet(oldCap, newCap, msg.sender); } /** * @notice Returns the expiry of the current option the vault is shorting */ function currentOptionExpiry() external view returns (uint256) { address _currentOption = currentOption; if (_currentOption == address(0)) { return 0; } OtokenInterface oToken = OtokenInterface(currentOption); return oToken.expiryTimestamp(); } /** * @notice Returns the amount withdrawable (in `asset` tokens) using the `share` amount * @param share is the number of shares burned to withdraw asset from the vault * @return amountAfterFee is the amount of asset tokens withdrawable from the vault * @return feeAmount is the fee amount (in asset tokens) sent to the feeRecipient */ function withdrawAmountWithShares(uint256 share) public view returns (uint256 amountAfterFee, uint256 feeAmount) { uint256 currentAssetBalance = assetBalance(); ( uint256 withdrawAmount, uint256 newAssetBalance, uint256 newShareSupply ) = _withdrawAmountWithShares(share, currentAssetBalance); require( withdrawAmount <= currentAssetBalance, "Cannot withdraw more than available" ); require(newShareSupply >= MINIMUM_SUPPLY, "Insufficient share supply"); require( newAssetBalance >= MINIMUM_SUPPLY, "Insufficient asset balance" ); feeAmount = wmul(withdrawAmount, instantWithdrawalFee); amountAfterFee = withdrawAmount.sub(feeAmount); } /** * @notice Helper function to return the `asset` amount returned using the `share` amount * @param share is the number of shares used to withdraw * @param currentAssetBalance is the value returned by totalBalance(). This is passed in to save gas. */ function _withdrawAmountWithShares( uint256 share, uint256 currentAssetBalance ) private view returns ( uint256 withdrawAmount, uint256 newAssetBalance, uint256 newShareSupply ) { uint256 total = lockedAmount.add(currentAssetBalance); uint256 shareSupply = totalSupply(); // solhint-disable-next-line // Following the pool share calculation from Alpha Homora: https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L111 withdrawAmount = share.mul(total).div(shareSupply); newAssetBalance = total.sub(withdrawAmount); newShareSupply = shareSupply.sub(share); } /** * @notice Returns the max withdrawable shares for all users in the vault */ function maxWithdrawableShares() public view returns (uint256) { uint256 withdrawableBalance = assetBalance(); uint256 total = lockedAmount.add(withdrawableBalance); return withdrawableBalance.mul(totalSupply()).div(total).sub( MINIMUM_SUPPLY ); } /** * @notice Returns the max amount withdrawable by an account using the account's vault share balance * @param account is the address of the vault share holder * @return amount of `asset` withdrawable from vault, with fees accounted */ function maxWithdrawAmount(address account) public view returns (uint256) { uint256 maxShares = maxWithdrawableShares(); uint256 share = balanceOf(account); uint256 numShares = min(maxShares, share); (uint256 withdrawAmount, , ) = _withdrawAmountWithShares(numShares, assetBalance()); return withdrawAmount; } /** * @notice Returns the number of shares for a given `assetAmount`. * Used by the frontend to calculate withdraw amounts. * @param assetAmount is the asset amount to be withdrawn * @return share amount */ function assetAmountToShares(uint256 assetAmount) external view returns (uint256) { uint256 total = lockedAmount.add(assetBalance()); return assetAmount.mul(totalSupply()).div(total); } /** * @notice Returns an account's balance on the vault * @param account is the address of the user * @return vault balance of the user */ function accountVaultBalance(address account) external view returns (uint256) { (uint256 withdrawAmount, , ) = _withdrawAmountWithShares(balanceOf(account), assetBalance()); return withdrawAmount; } /** * @notice Returns the vault's total balance, including the amounts locked into a short position * @return total balance of the vault, including the amounts locked in third party protocols */ function totalBalance() public view returns (uint256) { return lockedAmount.add(IERC20(asset).balanceOf(address(this))); } /** * @notice Returns the asset balance on the vault. This balance is freely withdrawable by users. */ function assetBalance() public view returns (uint256) { return IERC20(asset).balanceOf(address(this)); } /** * @notice Returns the token decimals */ function decimals() public view override returns (uint8) { return _decimals; } /** * @notice Only allows manager to execute a function */ modifier onlyManager { require(msg.sender == manager, "Only manager"); _; } }
* @notice Closes the vault and makes it withdraw only./
function sunset(address upgradeTo) external onlyOwner { require(address(replacementVault) == address(0), "Already sunset"); require(upgradeTo != address(0), "!upgradeTo"); replacementVault = IRibbonV2Vault(upgradeTo); emit VaultSunset(upgradeTo); }
1,384,163
[ 1, 18545, 326, 9229, 471, 7297, 518, 598, 9446, 1338, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13887, 542, 12, 2867, 8400, 774, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 2867, 12, 24394, 12003, 13, 422, 1758, 12, 20, 3631, 315, 9430, 13887, 542, 8863, 203, 3639, 2583, 12, 15097, 774, 480, 1758, 12, 20, 3631, 17528, 15097, 774, 8863, 203, 203, 3639, 6060, 12003, 273, 15908, 495, 18688, 58, 22, 12003, 12, 15097, 774, 1769, 203, 203, 3639, 3626, 17329, 55, 18579, 12, 15097, 774, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {ERC721Full} from "../../.openzeppelin/0.8/token/ERC721/ERC721Full.sol"; import {Counters} from "../../.openzeppelin/0.8/drafts/Counters.sol"; import {IERC721} from "../../.openzeppelin/0.8/token/ERC721/IERC721.sol"; import {Address} from "../../.openzeppelin/0.8/utils/Address.sol"; import {Bytes32} from "../../lib/Bytes32.sol"; import {Adminable} from "../../lib/Adminable.sol"; import {Initializable} from "../../lib/Initializable.sol"; import {DefiPassportStorage} from "./DefiPassportStorage.sol"; import {ISapphirePassportScores} from "../../sapphire/ISapphirePassportScores.sol"; import {SapphireTypes} from "../../sapphire/SapphireTypes.sol"; contract DefiPassport is ERC721Full, Adminable, DefiPassportStorage, Initializable { /* ========== Libraries ========== */ using Counters for Counters.Counter; using Address for address; using Bytes32 for bytes32; /* ========== Events ========== */ event BaseURISet(string _baseURI); event ApprovedSkinStatusChanged( address _skin, uint256 _skinTokenId, bool _status ); event ApprovedSkinsStatusesChanged( SkinAndTokenIdStatusRecord[] _skinsRecords ); event DefaultSkinStatusChanged( address _skin, bool _status ); event DefaultActiveSkinChanged( address _skin, uint256 _skinTokenId ); event ActiveSkinSet( uint256 _tokenId, SkinRecord _skinRecord ); event SkinManagerSet(address _skinManager); event WhitelistSkinSet(address _skin, bool _status); /* ========== Public variables ========== */ string public override baseURI; /** * @dev Deprecated. Including this because this is a proxy implementation. */ bytes32 private _proofProtocol; /* ========== Modifier ========== */ modifier onlySkinManager () { require( msg.sender == skinManager, "DefiPassport: caller is not skin manager" ); _; } /* ========== Restricted Functions ========== */ function init( string calldata name_, string calldata symbol_, address _skinManager ) external onlyAdmin initializer { _name = name_; _symbol = symbol_; skinManager = _skinManager; } /** * @dev Sets the base URI that is appended as a prefix to the * token URI. */ function setBaseURI( string calldata _baseURI ) external onlyAdmin { baseURI = _baseURI; emit BaseURISet(_baseURI); } /** * @dev Sets the address of the skin manager role * * @param _skinManager The new skin manager */ function setSkinManager( address _skinManager ) external onlyAdmin { require ( _skinManager != skinManager, "DefiPassport: the same skin manager is already set" ); skinManager = _skinManager; emit SkinManagerSet(skinManager); } /** * @notice Registers/unregisters a default skin * * @param _skin Address of the skin NFT * @param _status Wether or not it should be considered as a default * skin or not */ function setDefaultSkin( address _skin, bool _status ) external onlySkinManager { if (!_status) { require( defaultActiveSkin.skin != _skin, "Defi Passport: cannot unregister the default active skin" ); } require( defaultSkins[_skin] != _status, "DefiPassport: skin already has the same status" ); require( _skin.isContract(), "DefiPassport: the given skin is not a contract" ); require ( IERC721(_skin).ownerOf(1) != address(0), "DefiPassport: default skin must at least have tokenId eq 1" ); if (defaultActiveSkin.skin == address(0)) { defaultActiveSkin = SkinRecord(address(0), _skin, 1); } defaultSkins[_skin] = _status; emit DefaultSkinStatusChanged(_skin, _status); } /** * @dev Set the default active skin, which will be used instead of * unavailable user's active one * @notice Skin should be used as default one (with setDefaultSkin function) * * @param _skin Address of the skin NFT * @param _skinTokenId The NFT token ID */ function setDefaultActiveSkin( address _skin, uint256 _skinTokenId ) external onlySkinManager { require( defaultSkins[_skin], "DefiPassport: the given skin is not registered as a default" ); require( defaultActiveSkin.skin != _skin || defaultActiveSkin.skinTokenId != _skinTokenId, "DefiPassport: the skin is already set as default active" ); defaultActiveSkin = SkinRecord(address(0), _skin, _skinTokenId); emit DefaultActiveSkinChanged(_skin, _skinTokenId); } /** * @notice Approves a passport skin. * Only callable by the skin manager */ function setApprovedSkin( address _skin, uint256 _skinTokenId, bool _status ) external onlySkinManager { approvedSkins[_skin][_skinTokenId] = _status; emit ApprovedSkinStatusChanged(_skin, _skinTokenId, _status); } /** * @notice Sets the approved status for all skin contracts and their * token IDs passed into this function. */ function setApprovedSkins( SkinAndTokenIdStatusRecord[] memory _skinsToApprove ) public onlySkinManager { for (uint256 i = 0; i < _skinsToApprove.length; i++) { TokenIdStatus[] memory tokensAndStatuses = _skinsToApprove[i].skinTokenIdStatuses; for (uint256 j = 0; j < tokensAndStatuses.length; j ++) { TokenIdStatus memory tokenStatusPair = tokensAndStatuses[j]; approvedSkins[_skinsToApprove[i].skin][tokenStatusPair.tokenId] = tokenStatusPair.status; } } emit ApprovedSkinsStatusesChanged(_skinsToApprove); } /** * @notice Adds or removes a skin contract to the whitelist. * The Defi Passport considers all skins minted by whitelisted contracts * to be valid skins for applying them on to the passport. * The user applying the skins must still be their owner though. */ function setWhitelistedSkin( address _skinContract, bool _status ) external onlySkinManager { require ( _skinContract.isContract(), "DefiPassport: address is not a contract" ); require ( whitelistedSkins[_skinContract] != _status, "DefiPassport: the skin already has the same whitelist status" ); whitelistedSkins[_skinContract] = _status; emit WhitelistSkinSet(_skinContract, _status); } /* ========== Public Functions ========== */ /** * @notice Mints a DeFi passport to the address specified by `_to`. Note: * - The `_passportSkin` must be an approved or default skin. * - The token URI will be composed by <baseURI> + `_to`, * without the "0x" in front * * @param _to The receiver of the defi passport * @param _passportSkin The address of the skin NFT to be applied to the passport * @param _skinTokenId The ID of the passport skin NFT, owned by the receiver */ function mint( address _to, address _passportSkin, uint256 _skinTokenId ) external returns (uint256) { require ( isSkinAvailable(_to, _passportSkin, _skinTokenId), "DefiPassport: invalid skin" ); // A user cannot have two passports require( balanceOf(_to) == 0, "DefiPassport: user already has a defi passport" ); _tokenIds.increment(); uint256 newTokenId = _tokenIds.current(); _mint(_to, newTokenId); _setActiveSkin(newTokenId, SkinRecord(_to, _passportSkin, _skinTokenId)); return newTokenId; } /** * @notice Changes the passport skin of the caller's passport * * @param _skin The contract address to the skin NFT * @param _skinTokenId The ID of the skin NFT */ function setActiveSkin( address _skin, uint256 _skinTokenId ) external { require( balanceOf(msg.sender) > 0, "DefiPassport: caller has no passport" ); require( isSkinAvailable(msg.sender, _skin, _skinTokenId), "DefiPassport: invalid skin" ); uint256 tokenId = tokenOfOwnerByIndex(msg.sender, 0); _setActiveSkin(tokenId, SkinRecord(msg.sender, _skin, _skinTokenId)); } function approve( address, uint256 ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } function setApprovalForAll( address, bool ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } function safeTransferFrom( address, address, uint256 ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } function safeTransferFrom( address, address, uint256, bytes memory ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } function transferFrom( address, address, uint256 ) public pure override { revert("DefiPassport: defi passports are not transferrable"); } /* ========== Public View Functions ========== */ function name() external override view returns (string memory) { return _name; } function symbol() external override view returns (string memory) { return _symbol; } /** * @notice Returns whether a certain skin can be applied to the specified * user's passport. * * @param _user The user for whom to check * @param _skinContract The address of the skin NFT * @param _skinTokenId The NFT token ID */ function isSkinAvailable( address _user, address _skinContract, uint256 _skinTokenId ) public view returns (bool) { if (defaultSkins[_skinContract]) { return IERC721(_skinContract).ownerOf(_skinTokenId) != address(0); } else if ( whitelistedSkins[_skinContract] || approvedSkins[_skinContract][_skinTokenId] ) { return _isSkinOwner(_user, _skinContract, _skinTokenId); } return false; } /** * @notice Returns the active skin of the given passport ID * * @param _tokenId Passport ID */ function getActiveSkin( uint256 _tokenId ) public view returns (SkinRecord memory) { SkinRecord memory _activeSkin = _activeSkins[_tokenId]; if (isSkinAvailable(_activeSkin.owner, _activeSkin.skin, _activeSkin.skinTokenId)) { return _activeSkin; } else { return defaultActiveSkin; } } /** * @dev Returns the URI for a given token ID. May return an empty string. * * Reverts if the token ID does not exist. */ function tokenURI( uint256 tokenId ) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); address owner = ownerOf(tokenId); return string(abi.encodePacked(baseURI, "0x", _toAsciiString(owner))); } /* ========== Private Functions ========== */ /** * @dev Converts the given address to string. Used when minting new * passports. */ function _toAsciiString( address _address ) private pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(_address)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = _char(hi); s[2*i+1] = _char(lo); } return string(s); } function _char( bytes1 b ) private pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } /** * @dev Ensures that the user is the owner of the skin NFT */ function _isSkinOwner( address _user, address _skin, uint256 _tokenId ) internal view returns (bool) { /** * It is not sure if the skin contract implements the ERC721 or ERC1155 standard, * so we must do the check. */ bytes memory payload = abi.encodeWithSignature("ownerOf(uint256)", _tokenId); (bool success, bytes memory returnData) = _skin.staticcall(payload); if (success) { (address owner) = abi.decode(returnData, (address)); return owner == _user; } else { // The skin contract might be an ERC1155 (like OpenSea) payload = abi.encodeWithSignature("balanceOf(address,uint256)", _user, _tokenId); (success, returnData) = _skin.staticcall(payload); if (success) { (uint256 balance) = abi.decode(returnData, (uint256)); return balance > 0; } } return false; } function _setActiveSkin( uint256 _tokenId, SkinRecord memory _skinRecord ) private { SkinRecord memory currentSkin = _activeSkins[_tokenId]; require( currentSkin.skin != _skinRecord.skin || currentSkin.skinTokenId != _skinRecord.skinTokenId, "DefiPassport: the same skin is already active" ); _activeSkins[_tokenId] = _skinRecord; emit ActiveSkinSet(_tokenId, _skinRecord); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721.sol"; import "./ERC721Enumerable.sol"; import "./ERC721Metadata.sol"; /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { function _transferFrom( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { ERC721Enumerable._transferFrom(from, to, tokenId); } function _mint( address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { ERC721Enumerable._mint(to, tokenId); } function _burn( address owner, uint256 tokenId ) internal override(ERC721, ERC721Enumerable, ERC721Metadata) { // Burn implementation of Metadata ERC721._burn(owner, tokenId); ERC721Metadata._burn(owner, tokenId); ERC721Enumerable._burn(owner, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; library Bytes32 { function toString( bytes32 _bytes ) internal pure returns (string memory) { uint8 i = 0; while (i < 32 && _bytes[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes[i] != 0; i++) { bytesArray[i] = _bytes[i]; } return string(bytesArray); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import { Storage } from "./Storage.sol"; /** * @title Adminable * @author dYdX * * @dev EIP-1967 Proxy Admin contract. */ contract Adminable { /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will revert. */ modifier onlyAdmin() { require( msg.sender == getAdmin(), "Adminable: caller is not admin" ); _; } /** * @return The EIP-1967 proxy admin */ function getAdmin() public view returns (address) { return address(uint160(uint256(Storage.load(ADMIN_SLOT)))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * Taken from OpenZeppelin */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {Counters} from "../../.openzeppelin/0.8/drafts/Counters.sol"; import {ISapphirePassportScores} from "../../sapphire/ISapphirePassportScores.sol"; contract DefiPassportStorage { /* ========== Structs ========== */ struct SkinRecord { address owner; address skin; uint256 skinTokenId; } struct TokenIdStatus { uint256 tokenId; bool status; } struct SkinAndTokenIdStatusRecord { address skin; TokenIdStatus[] skinTokenIdStatuses; } // Made these internal because the getters override these variables (because this is an upgrade) string internal _name; string internal _symbol; /** * @notice The credit score contract used by the passport */ ISapphirePassportScores private passportScoresContract; /* ========== Public Variables ========== */ /** * @notice Records the whitelisted skins. All tokens minted by these contracts * will be considered valid to apply on the passport, given they are * owned by the caller. */ mapping (address => bool) public whitelistedSkins; /** * @notice Records the approved skins of the passport */ mapping (address => mapping (uint256 => bool)) public approvedSkins; /** * @notice Records the default skins */ mapping (address => bool) public defaultSkins; /** * @notice Records the default skins */ SkinRecord public defaultActiveSkin; /** * @notice The skin manager appointed by the admin, who can * approve and revoke passport skins */ address public skinManager; /* ========== Internal Variables ========== */ /** * @notice Maps a passport (tokenId) to its active skin NFT */ mapping (uint256 => SkinRecord) internal _activeSkins; Counters.Counter internal _tokenIds; } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import {SapphireTypes} from "./SapphireTypes.sol"; interface ISapphirePassportScores { function updateMerkleRoot(bytes32 newRoot) external; function setMerkleRootUpdater(address merkleRootUpdater) external; /** * Reverts if proof is invalid */ function verify(SapphireTypes.ScoreProof calldata proof) external view returns(bool); function setMerkleRootDelay(uint256 delay) external; function setPause(bool status) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; library SapphireTypes { struct ScoreProof { address account; bytes32 protocol; uint256 score; bytes32[] merkleProof; } struct Vault { uint256 collateralAmount; uint256 borrowedAmount; } struct RootInfo { bytes32 merkleRoot; uint256 timestamp; } enum Operation { Deposit, Withdraw, Borrow, Repay, Liquidate } struct Action { uint256 amount; Operation operation; address userToLiquidate; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../GSN/Context.sol"; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../drafts/Counters.sol"; import "../../introspection/ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public override view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public override view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public override virtual { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public override view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public override virtual { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public override view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public override virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public override virtual { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override virtual { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This is an internal detail of the `ERC721` contract and its use is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../GSN/Context.sol"; import "./IERC721Enumerable.sol"; import "./ERC721.sol"; import "../../introspection/ERC165.sol"; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public override view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public override view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public override view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal override virtual { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal override virtual { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal override virtual { _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].pop(); // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.pop(); _allTokensIndex[tokenId] = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../GSN/Context.sol"; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "../../introspection/ERC165.sol"; contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Gets the token name. * @return string representing the token name */ function name() external override virtual view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external override virtual view returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. */ function tokenURI(uint256 tokenId) external override virtual view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_tokenURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_baseURI, _tokenURI)); } } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: if all token IDs share a prefix (e.g. if your URIs look like * `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}. * * _Available since v2.5.0._ */ function _setBaseURI(string memory baseURI_) internal { _baseURI = baseURI_; } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a preffix in {tokenURI} to each token's URI, when * they are non-empty. * * _Available since v2.5.0._ */ function baseURI() external virtual view returns (string memory) { return _baseURI; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address, uint256 tokenId) internal override virtual { // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @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. */ abstract contract Context { function _msgSender() internal view returns (address) { return 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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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. * * _Available since v2.4.0._ */ 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. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external override view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; library Storage { /** * @dev Performs an SLOAD and returns the data in the slot. */ function load( bytes32 slot ) internal view returns (bytes32) { bytes32 result; /* solhint-disable-next-line no-inline-assembly */ assembly { result := sload(slot) } return result; } /** * @dev Performs an SSTORE to save the value to the slot. */ function store( bytes32 slot, bytes32 value ) internal { /* solhint-disable-next-line no-inline-assembly */ assembly { sstore(slot, value) } } }
* @dev Sets the base URI that is appended as a prefix to the token URI./
function setBaseURI( string calldata _baseURI ) external onlyAdmin { baseURI = _baseURI; emit BaseURISet(_baseURI); }
11,896,543
[ 1, 2785, 326, 1026, 3699, 716, 353, 12317, 487, 279, 1633, 358, 326, 1377, 1147, 3699, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 26435, 3098, 12, 203, 3639, 533, 745, 892, 389, 1969, 3098, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1338, 4446, 203, 565, 288, 203, 3639, 1026, 3098, 273, 389, 1969, 3098, 31, 203, 3639, 3626, 3360, 3098, 694, 24899, 1969, 3098, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x8e149A994aD5265eAE3D114FA64C117BDac8956c/sources/BettingGame.sol
* Withdraw LINK from this contract (admin option)./
function withdrawLink(uint256 amount) external onlyAdmin { require(LINK.transfer(msg.sender, amount), "Error, unable to transfer"); }
786,079
[ 1, 1190, 9446, 22926, 628, 333, 6835, 261, 3666, 1456, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 598, 9446, 2098, 12, 11890, 5034, 3844, 13, 3903, 1338, 4446, 288, 203, 565, 2583, 12, 10554, 18, 13866, 12, 3576, 18, 15330, 16, 3844, 3631, 315, 668, 16, 13496, 358, 7412, 8863, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x8CB7b0BEF538d21b35EDf1251321495c11EAEBDd/sources/src/UniwarConfigImpl.sol
/ @dev glacialBind for bad actors, let us pray, in this time of war, we don't need to use it.
mapping (address => bool) public glacialBind;
16,477,057
[ 1, 19, 225, 5118, 1077, 649, 3357, 364, 5570, 27141, 16, 2231, 584, 293, 435, 16, 316, 333, 813, 434, 21983, 16, 732, 2727, 1404, 1608, 358, 999, 518, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 5118, 1077, 649, 3357, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x4555a54BF5aBBd4102C54C2ac2B8e47B9d2B1F26/sources/project_/contracts/ERC20tokenPresetModified.sol
* @dev Modified function. Two functions `__AccessControl_init_unchained` and `__ERC20PresetMinterPauser_init_unchained` have been moved to the {HManagementContract}/ __AccessControl_init_unchained(); MODIFIED __ERC20PresetMinterPauser_init_unchained(name, symbol); MODIFIED
function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __ERC20Burnable_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); }
11,616,848
[ 1, 4575, 445, 18, 16896, 4186, 1375, 972, 16541, 67, 2738, 67, 4384, 8707, 68, 471, 1375, 972, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 67, 2738, 67, 4384, 8707, 68, 1240, 2118, 10456, 358, 326, 288, 44, 10998, 8924, 4004, 1001, 16541, 67, 2738, 67, 4384, 8707, 5621, 7734, 8663, 13519, 1001, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 67, 2738, 67, 4384, 8707, 12, 529, 16, 3273, 1769, 225, 8663, 13519, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1001, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 67, 2738, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 2713, 12562, 288, 203, 3639, 1001, 1042, 67, 2738, 67, 4384, 8707, 5621, 203, 3639, 1001, 654, 39, 3462, 67, 2738, 67, 4384, 8707, 12, 529, 16, 3273, 1769, 203, 3639, 1001, 654, 39, 3462, 38, 321, 429, 67, 2738, 67, 4384, 8707, 5621, 203, 3639, 1001, 16507, 16665, 67, 2738, 67, 4384, 8707, 5621, 203, 3639, 1001, 654, 39, 3462, 16507, 16665, 67, 2738, 67, 4384, 8707, 5621, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.8; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/token/ERC721/ERC721Burnable.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; contract Shapes is ERC721, ERC721Burnable, Ownable { // structs struct ShapeType { uint id; bytes32 name; bytes32 symbol; uint supply; uint priceWei; bool active; } struct ShapeToken { uint id; uint shapeTypeId; } // arrays ShapeType[] public shapeTypes; ShapeToken[] public shapeTokens; // events event TokenMinted(address indexed _from, bytes32 indexed _symbol); event TokenBurned(address indexed _from, bytes32 indexed _symbol); event ShapeTypeAdded(address indexed _from, bytes32 indexed _symbol); event ShapeTypeDeactivated(address indexed _from, bytes32 indexed _symbol); event EtherCollected(address indexed _from, uint indexed _balance); constructor() ERC721("Shape", "SHAPE") public { ShapeType memory circle = ShapeType({ id: 1, name: "circle", symbol: "CRC", supply: 0, priceWei: 500000000000000000, // 0.5 ETH active: true }); shapeTypes.push(circle); ShapeType memory square = ShapeType({ id: 2, name: "square", symbol: "SQR", supply: 0, priceWei: 1200000000000000000, // 1.2 ETH active: true }); shapeTypes.push(square); ShapeType memory triangle = ShapeType({ id: 3, name: "cloud", symbol: "CLD", supply: 0, priceWei: 330000000000000000, // 0.33 ETH active: true }); shapeTypes.push(triangle); } // methods function addNewShapeType(bytes32 _name, bytes32 _symbol, uint _price) public onlyOwner { // check if shape type with that symbol already exists ShapeType memory someShape = getShapeTypeBySymbol(_symbol); if (someShape.id > 0) { // if shape type ID > 0, then shape type exists if (someShape.active) { // if the existing shape type is active, revert the whole tx revert("A ShapeType with this symbol already exists."); } else { // if the existing shape type is not active, re-activate it shapeTypes[someShape.id-1].active = true; return; } } // else create a new shape type ShapeType memory shape = ShapeType( shapeTypes.length+1, _name, _symbol, 0, // supply _price, true // active ); shapeTypes.push(shape); emit ShapeTypeAdded(msg.sender, shape.symbol); } function burnByTokenId(uint256 _tokenId) public { super.burn(_tokenId); // burn the token that belongs to the msg.sender shapeTypes[shapeTokens[_tokenId-1].shapeTypeId-1].supply -= 1; // decrease supply in shape type ShapeType memory thisShapeType = shapeTypes[shapeTokens[_tokenId-1].shapeTypeId-1]; // return the ETH (if possible) if (address(this).balance >= thisShapeType.priceWei) { (bool sent, bytes memory data) = msg.sender.call{value: thisShapeType.priceWei}(""); } emit TokenBurned(msg.sender, thisShapeType.symbol); } function deactivateShapeTypeById(uint _id) public onlyOwner { shapeTypes[_id-1].active = false; emit ShapeTypeDeactivated(msg.sender, shapeTypes[_id-1].symbol); } function getShapeTypeIdOfToken(uint _tokenId) public view returns (uint typeId) { return shapeTokens[_tokenId-1].shapeTypeId; } function getShapeTypeByIndex(uint _index) public view returns (uint typeId, bytes32 name, bytes32 symbol, uint supply, uint price, bool active) { return (shapeTypes[_index].id, shapeTypes[_index].name, shapeTypes[_index].symbol, shapeTypes[_index].supply, shapeTypes[_index].priceWei, shapeTypes[_index].active); } function getShapeTypeBySymbol(bytes32 _symbol) internal view returns (ShapeType memory) { for (uint i = 0; i < shapeTypes.length; i++) { if (shapeTypes[i].symbol == _symbol) { return shapeTypes[i]; } } } function getShapeTypesArrayLength() public view returns (uint256) { return shapeTypes.length; } function mintByShapeTypeId(uint256 _id, bytes memory _data) public payable returns (bool) { // check if the token price is correct require(msg.value == shapeTypes[_id-1].priceWei, "Wrong amount of ETH sent."); // check if the shape type is active require(shapeTypes[_id-1].active == true, "The selected shape type is deactivated."); // set a new token id uint tokenId = shapeTokens.length + 1; // create a shape token and store it in the tokens array shapeTokens.push(ShapeToken({ id: tokenId, // get the ID of the last token and add 1 shapeTypeId: _id })); // mint the ERC-721 token super._safeMint(msg.sender, tokenId, _data); // mint a token and assign it to msg.sender shapeTypes[_id-1].supply += 1; emit TokenMinted(msg.sender, shapeTypes[_id-1].symbol); return true; } function mintBySymbol(bytes32 _symbol, bytes memory _data) public payable returns (bool) { // Use this function, if you don't want people to confuse array index and token ID // Delete mintByTokenTypeId (or ignore it on front-end) and let them use mintBySymbol only // Note: this function is a bit more expensive in terms of gas, but safer to avoid errors ShapeType memory someShapeType = getShapeTypeBySymbol(_symbol); // user can buy only one Shape token at a time require(msg.value == someShapeType.priceWei, "Wrong amount of ETH sent."); // check if the shape is active require(someShapeType.active == true, "The selected shape is deactivated."); // set a new token id uint tokenId = shapeTokens.length + 1; // create a shape token and store it in the tokens array shapeTokens.push(ShapeToken({ id: tokenId, // get the ID of the last token and add 1 shapeTypeId: someShapeType.id })); super._safeMint(msg.sender, tokenId, _data); // mint 1 token and assign it to msg.sender shapeTypes[someShapeType.id-1].supply += 1; emit TokenMinted(msg.sender, someShapeType.symbol); return true; } function ownerCollectEther() public onlyOwner { uint balance = address(this).balance; (bool sent, bytes memory data) = owner().call{value: balance}(""); emit EtherCollected(msg.sender, balance); } }
mint a token and assign it to msg.sender
super._safeMint(msg.sender, tokenId, _data);
6,379,784
[ 1, 81, 474, 279, 1147, 471, 2683, 518, 358, 1234, 18, 15330, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2240, 6315, 4626, 49, 474, 12, 3576, 18, 15330, 16, 1147, 548, 16, 389, 892, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-01-16 */ pragma solidity 0.5.10; /** * @author @veronicaLC (Veronica Coutts) * @title The interface for the market factory */ interface IMarketFactory { /** * @notice Vyper cannot handle arrays of unknown length, * and thus the funding goals and durations will * only be stored in the vault, which is Solidity. * @dev This function allows for the creation of a * new market, consisting of a curve and vault * @param _fundingGoals This is the amount wanting to be * raised in each round, in collateral. * @param _phaseDurations The time for each round in * number of blocks. * @param _creator Address of the researcher. * @param _curveType Curve selected * @param _feeRate The pecentage of fee. e.g: 60 */ function deployMarket( uint256[] calldata _fundingGoals, uint256[] calldata _phaseDurations, address _creator, uint256 _curveType, uint256 _feeRate ) external; /** * @notice This function will only affect new markets, and will not update * already created markets. This can only be called by an admin */ function updateMoleculeVault(address _newMoleculeVault) external; /** * @return address: The address of the molecule vault */ function moleculeVault() external view returns(address); /** * @return address: The contract address of the market registry. */ function marketRegistry() external view returns(address); /** * @return address: The contract address of the curve registry */ function curveRegistry() external view returns(address); /** * @return address: The contract address of the collateral token */ function collateralToken() external view returns(address); } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title The interface for the market registry. */ interface IMarketRegistry { // Emitted when a market is created event MarketCreated( uint256 index, address indexed marketAddress, address indexed vault, address indexed creator ); // Emitted when a deployer is added event DeployerAdded(address deployer, string version); // Emitted when a deployer is removed event DeployerRemoved(address deployer, string reason); /** * @dev Adds a new market deployer to the registry. * @param _newDeployer: Address of the new market deployer. * @param _version: string - Log text for tracking purposes. */ function addMarketDeployer( address _newDeployer, string calldata _version ) external; /** * @dev Removes a market deployer from the registry. * @param _deployerToRemove: Address of the market deployer to remove. * @param _reason: Log text for tracking purposes. */ function removeMarketDeployer( address _deployerToRemove, string calldata _reason ) external; /** * @dev Logs the market into the registery. * @param _vault: Address of the vault. * @param _creator: Creator of the market. * @return uint256: Returns the index of market for looking up. */ function registerMarket( address _marketAddress, address _vault, address _creator ) external returns(uint256); /** * @dev Fetches all data and contract addresses of deployed * markets by index, kept as interface for later * intergration. * @param _index: Index of the market. * @return address: The address of the market. * @return address: The address of the vault. * @return address: The address of the creator. */ function getMarket(uint256 _index) external view returns( address, address, address ); /** * @dev Fetchs the current number of markets infering maximum * callable index. * @return uint256: The number of markets that have been deployed. */ function getIndex() external view returns(uint256); /** * @dev Used to check if the deployer is registered. * @param _deployer: The address of the deployer * @return bool: A simple bool to indicate state. */ function isMarketDeployer(address _deployer) external view returns(bool); /** * @dev In order to look up logs efficently, the published block is * available. * @return uint256: The block when the contract was published. */ function publishedBlocknumber() external view returns(uint256); } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title The interface for the curve registry. */ interface ICurveRegistry { // Emitted when a curve is registered event CurveRegisterd( uint256 index, address indexed libraryAddress, string curveFunction ); // Emitted when a curve is registered event CurveActivated(uint256 index, address indexed libraryAddress); // Emitted when a curve is deactivated event CurveDeactivated(uint256 index, address indexed libraryAddress); /** * @dev Logs the market into the registery. * @param _libraryAddress: Address of the library. * @param _curveFunction: Curve title/statement. * @return uint256: Returns the index of market for looking up */ function registerCurve( address _libraryAddress, string calldata _curveFunction) external returns(uint256); /** * @notice Allows an dmin to set a curves state to inactive. This function * is for the case of an incorect curve module, or vunrability. * @param _index: The index of the curve to be set as inactive. */ function deactivateCurve(uint256 _index) external; /** * @notice Allows an admin to set a curves state to active. * @param _index: The index of the curve to be set as active. */ function reactivateCurve(uint256 _index) external; /** * @dev Fetches all data and contract addresses of deployed curves by * index, kept as interface for later intergration. * @param _index: Index of the curve library * @return address: The address of the curve */ function getCurveAddress(uint256 _index) external view returns(address); /** * @dev Fetches all data and contract addresses of deployed curves by * index, kept as interface for later intergration. * @param _index: Index of the curve library. * @return address: The address of the math library. * @return string: The function of the curve. * @return bool: The curves active state. */ function getCurveData(uint256 _index) external view returns( address, string memory, bool ); /** * @dev Fetchs the current number of curves infering maximum callable * index. * @return uint256: Returns the total number of curves registered. */ function getIndex() external view returns(uint256); /** * @dev In order to look up logs efficently, the published block is * available. * @return uint256: The block when the contract was published */ function publishedBlocknumber() external view returns(uint256); } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title The interface for the molecule vault */ interface IMoleculeVault { /** * @notice Allows an admin to add another admin. * @param _moleculeAdmin: The address of the new admin. */ function addAdmin(address _moleculeAdmin) external; /** * @notice Allows an admin to transfer colalteral out of the molecule * vault and into another address. * @param _to: The address that the collateral will be transfered to. * @param _amount: The amount of collateral being transfered. */ function transfer(address _to, uint256 _amount) external; /** * @notice Allows an admin to approve a spender of the molecule vault * collateral. * @param _spender: The address that will be aproved as a spender. * @param _amount: The amount the spender will be approved to spend. */ function approve(address _spender, uint256 _amount) external; /** * @notice Allows the admin to update the fee rate charged by the * molecule vault. * @param _newFeeRate : The new fee rate. * @return bool: If the update was successful */ function updateFeeRate(uint256 _newFeeRate) external returns(bool); /** * @return address: The address of the collateral token. */ function collateralToken() external view returns(address); /** * @return uint256 : The fee rate the molecule vault has. */ function feeRate() external view returns(uint256); } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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. * * > 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); } /** * @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) { //require(b <= a, "SafeMath: subtraction overflow"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title Market */ interface IMarket { // Emitted when a spender is approved event Approval( address indexed owner, address indexed spender, uint256 value ); // Emitted when a transfer, mint or burn occurs event Transfer(address indexed from, address indexed to, uint value); // Emitted when tokens are minted event Mint( address indexed to, // The address reciving the tokens uint256 amountMinted, // The amount of tokens minted uint256 collateralAmount, // The amount of DAI spent uint256 researchContribution // The tax donatedd (in DAI) ); // Emitted when tokens are burnt event Burn( address indexed from, // The address burning the tokens uint256 amountBurnt, // The amount of tokens burnt uint256 collateralReturned // DAI being recived (in DAI) ); // Emitted when the market is terminated event MarketTerminated(); /** * @notice Approves transfers for a given address. * @param _spender : The account that will receive the funds. * @param _value : The value of funds accessed. * @return boolean : Indicating the action was successful. */ function approve(address _spender, uint256 _value) external returns (bool); /** * @dev Selling tokens back to the bonding curve for collateral. * @param _numTokens: The number of tokens that you want to burn. */ function burn(uint256 _numTokens) external returns(bool); /** * @dev We have modified the minting function to divert a portion of the * collateral for the purchased tokens to the vault. * @param _to : Address to mint tokens to. * @param _numTokens : The number of tokens you want to mint. */ function mint(address _to, uint256 _numTokens) external returns(bool); /** * @notice Transfer ownership token from msg.sender to a specified address. * @param _to : The address to transfer to. * @param _value : The amount to be transferred. */ function transfer(address _to, uint256 _value) external returns (bool); /** * @notice Transfer tokens from one address to another. * @param _from: The address which you want to send tokens from. * @param _to: The address which you want to transfer to. * @param _value: The amount of tokens to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) external returns(bool); /** * @notice Can only be called by this markets vault * @dev Allows the market to end once all funds have been raised. * Ends the market so that no more tokens can be bought or sold. * Tokens can still be transfered, or "withdrawn" for an enven * distribution of remaining collateral. */ function finaliseMarket() external returns(bool); /** * @dev Allows token holders to withdraw collateral in return for tokens * after the market has been finalised. * @param _amount: The amount of tokens they want to withdraw */ function withdraw(uint256 _amount) external returns(bool); /** * @dev Returns the required collateral amount for a volume of bonding * curve tokens * @param _numTokens: The number of tokens to calculate the price of * @return uint256 : The required collateral amount for a volume of bonding * curve tokens. */ function priceToMint(uint256 _numTokens) external view returns(uint256); /** * @dev Returns the required collateral amount for a volume of bonding * curve tokens * @param _numTokens: The number of tokens to work out the collateral * vaule of * @return uint256: The required collateral amount for a volume of bonding * curve tokens */ function rewardForBurn(uint256 _numTokens) external view returns(uint256); /** * @notice This function returns the amount of tokens one can receive for a * specified amount of collateral token. Including molecule & * market contributions * @param _collateralTokenOffered: Amount of reserve token offered for * purchase * @return uint256: The amount of tokens one can purchase with the * specified collateral */ function collateralToTokenBuying( uint256 _collateralTokenOffered ) external view returns(uint256); /** * @notice This function returns the amount of tokens needed to be burnt to * withdraw a specified amount of reserve token. * @param _collateralTokenNeeded: Amount of dai to be withdraw. * @return uint256: The amount of tokens needed to burn to reach goal * colalteral */ function collateralToTokenSelling( uint256 _collateralTokenNeeded ) external view returns(uint256); /** * @notice Gets the value of the current allowance specifed for that * account. * @param _owner: The account sending the funds. * @param _spender: The account that will receive the funds. * @return uint256: representing the amount the spender can spend */ function allowance( address _owner, address _spender ) external view returns(uint256); /** * @notice Gets the balance of the specified address. * @param _owner: The address to query the the balance of. * @return uint256: Represents the amount owned by the passed address. */ function balanceOf(address _owner) external view returns (uint256); /** * @notice Total collateral backing the curve. * @return uint256: Represents the total collateral backing the curve. */ function poolBalance() external view returns (uint256); /** * @notice Total number of tokens in existence * @return uint256: Represents the total supply of tokens in this market. */ function totalSupply() external view returns (uint256); /** * @dev The rate of fee (%) the market pays towards the vault on token * purchases. */ function feeRate() external view returns(uint256); /** * @return uint256: The decimals set for the market */ function decimals() external view returns(uint256); /** * @return bool: The active stat of the market. Inactive markets have * ended. */ function active() external view returns(bool); } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title Storage and collection of market tax. * @notice The vault stores the tax from the market until the funding goal is * reached, thereafter the creator may withdraw the funds. If the * funding is not reached within the stipulated time-frame, or the * creator terminates the market, the funding is sent back to the * market to be re-distributed. * @dev The vault pulls the mol tax directly from the molecule vault. */ interface IVault { // States for each funding round enum FundingState { NOT_STARTED, STARTED, ENDED, PAID } // Emitted when funding is withdrawn by the creator event FundingWithdrawn(uint256 phase, uint256 amount); // Emitted when a phase has been successfully filled event PhaseFinalised(uint256 phase, uint256 amount); /** * @dev Initialized the contract, sets up owners and gets the market * address. This function exists because the Vault does not have * an address until the constructor has finished running. The * cumulative funding threshold is set here because of gas issues * within the constructor. * @param _market: The market that will be sending this vault it's * collateral. */ function initialize(address _market) external returns(bool); /** * @notice AAllows the creator to withdraw the various phases as they are * completed. * @return bool: The funding has successfully been transferred. */ function withdraw() external returns(bool); /** * @notice Verifies that the phase passed in: has not been withdrawn, * funding goal has been reached, and that the phase has not * expired. Adds fee amount to the vault pool. * @param _receivedFunding: The amount of funding recived * @return bool: Wheather or not the funding is valid */ function validateFunding(uint256 _receivedFunding) external returns(bool); /** * @dev This function sends the vaults funds to the market, and sets the * outstanding withdraw to 0. * @notice If this function is called before the end of all phases, all * unclaimed (outstanding) funding will be sent to the market to be * redistributed. */ function terminateMarket() external; /** * @notice Returns all the details (relavant to external code) for a * specific phase. * @param _phase: The phase that you want the information of * @return uint256: The funding goal (including mol tax) of the round * @return uint256: The amount of funding currently raised for the round * @return uint256: The duration of the phase * @return uint256: The timestamp of the start date of the round * @return FundingState: The enum state of the round (see IVault) */ function fundingPhase( uint256 _phase ) external view returns( uint256, uint256, uint256, uint256, FundingState ); /** * @return uint256: The amount of funding that the creator has earned by * not withdrawn. */ function outstandingWithdraw() external view returns(uint256); /** * @dev The current active phase of funding * @return uint256: The current phase the project is in. */ function currentPhase() external view returns(uint256); /** * @return uint256: The total number of rounds for this project. */ function getTotalRounds() external view returns(uint256); /** * @return address: The address of the market that is funding this vault. */ function market() external view returns(address); /** * @return address: The address of the creator of this project. */ function creator() external view returns(address); } /** * @author @veronicaLC (Veronica Coutts) & @BenSchZA (Ben Scholtz) * @title The interface for the curve functions. */ interface ICurveFunctions { /** * @dev Calculates the definite integral of the curve * @param _x : Token value for upper limit of definite integral */ function curveIntegral(uint256 _x) external pure returns(uint256); /** * @dev Calculates the definite inverse integral of the curve * @param _x : collateral value for upper limit of definite integral */ function inverseCurveIntegral(uint256 _x) external pure returns(uint256); } // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.00 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. // // GNU Lesser General Public License 3.0 // https://www.gnu.org/licenses/lgpl-3.0.en.html // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_HOUR = 60 * 60; uint256 constant SECONDS_PER_MINUTE = 60; int256 constant OFFSET19700101 = 2440588; uint256 constant DOW_MON = 1; uint256 constant DOW_TUE = 2; uint256 constant DOW_WED = 3; uint256 constant DOW_THU = 4; uint256 constant DOW_FRI = 5; uint256 constant DOW_SAT = 6; uint256 constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 _days) { require(year >= 1970, "Epoch error"); int256 _year = int256(year); int256 _month = int256(month); int256 _day = int256(day); int256 __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint256 (__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int256 L = days + 68569 + offset // int256 N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint256 _days) internal pure returns (uint256 year, uint256 month, uint256 day) { int256 __days = int256(_days); int256 L = __days + 68569 + OFFSET19700101; int256 N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int256 _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int256 _month = 80 * L / 2447; int256 _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256 (_year); month = uint256 (_month); day = uint256 (_day); } function timestampFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint256 timestamp) internal pure returns (uint256 year, uint256 month, uint256 day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint256 timestamp) internal pure returns (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint256 year, uint256 month, uint256 day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint256 year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) { uint256 _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint256 timestamp) internal pure returns (uint256 year) { uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint256 timestamp) internal pure returns (uint256 month) { uint256 year; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint256 timestamp) internal pure returns (uint256 day) { uint256 year; uint256 month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint256 timestamp) internal pure returns (uint256 hour) { uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint256 timestamp) internal pure returns (uint256 minute) { uint256 secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint256 timestamp) internal pure returns (uint256 second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; assert(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; assert(newTimestamp >= timestamp); } function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; assert(newTimestamp >= timestamp); } function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; assert(newTimestamp >= timestamp); } function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _seconds; assert(newTimestamp >= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; assert(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; assert(newTimestamp <= timestamp); } function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; assert(newTimestamp <= timestamp); } function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; assert(newTimestamp <= timestamp); } function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; assert(newTimestamp <= timestamp); } function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _seconds; assert(newTimestamp <= timestamp); } function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) { require(fromTimestamp <= toTimestamp); uint256 fromYear; uint256 fromMonth; uint256 fromDay; uint256 toYear; uint256 toMonth; uint256 toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) { require(fromTimestamp <= toTimestamp); uint256 fromYear; uint256 fromMonth; uint256 fromDay; uint256 toYear; uint256 toMonth; uint256 toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title Creation and storage of project tokens, fills vault with fee. * @notice The market will send a portion of all collateral on mint to the * vault to fill the funding rounds. * @dev Checks with vault on every mint to ensure rounds are still active, * goal has not been met, and that the round has not expired. */ contract Market is IMarket, IERC20 { // For math functions with overflow & underflow checks using SafeMath for uint256; // Allows market to be deactivated after funding bool internal active_ = true; // Vault that recives fee IVault internal creatorVault_; // Percentage of vault fee e.g. 20 uint256 internal feeRate_; // Address of curve function ICurveFunctions internal curveLibrary_; // Underlying collateral token IERC20 internal collateralToken_; // Total minted tokens uint256 internal totalSupply_; // Decimal accuracy of token uint256 internal decimals_ = 18; // Allowances for spenders mapping(address => mapping (address => uint256)) internal allowed; // Balances of token holders mapping(address => uint256) internal balances; /** * @notice Sets the needed variables for the market * @param _feeRate : The percentage for the fee i.e 20 * @param _creatorVault : The vault for fee to go to * @param _curveLibrary : Math module. * @param _collateralToken : The ERC20 collateral tokem */ constructor( uint256 _feeRate, address _creatorVault, address _curveLibrary, address _collateralToken ) public { // Sets the storage variables feeRate_ = _feeRate; creatorVault_ = IVault(_creatorVault); curveLibrary_ = ICurveFunctions(_curveLibrary); collateralToken_ = IERC20(_collateralToken); } /** * @notice Ensures the market's key functionality is only available when * the market is active. */ modifier onlyActive(){ require(active_, "Market inactive"); _; } /** * @notice Enaures a function is only callable by the vault. */ modifier onlyVault(){ require(msg.sender == address(creatorVault_), "Invalid requestor"); _; } /** * @dev Selling tokens back to the bonding curve for collateral. * @param _numTokens: The number of tokens that you want to burn. */ function burn(uint256 _numTokens) external onlyActive() returns(bool) { require( balances[msg.sender] >= _numTokens, "Not enough tokens available" ); uint256 reward = rewardForBurn(_numTokens); totalSupply_ = totalSupply_.sub(_numTokens); //injected INTEGER OVERFLOW OR UNDERFLOW balances[msg.sender] = balances[msg.sender].sub(_numTokens); //injected INTEGER OVERFLOW OR UNDERFLOW require( collateralToken_.transfer( msg.sender, reward ), "Tokens not sent" ); emit Transfer(msg.sender, address(0), _numTokens); emit Burn(msg.sender, _numTokens, reward); return true; } /** * @dev We have modified the minting function to divert a portion of the * collateral for the purchased tokens to the vault. * @notice If a mint transaction exceeded the needed funding for the last * round, the excess funds WILL NOT BE RETURNED TO SENDER. The * Molecule Catalyst front end prevents this. * The curve intergral code will reject any values that are too * small or large, that could result in over/under flows. * @param _to : Address to mint tokens to. * @param _numTokens : The number of tokens you want to mint. */ function mint( address _to, uint256 _numTokens ) external onlyActive() returns(bool) { // Gets the price (in collateral) for the tokens uint256 priceForTokens = priceToMint(_numTokens); // Ensures there is no overflow require(priceForTokens > 0, "Tokens requested too low"); // Works out how much fee needs to be sent to the vault uint256 fee = priceForTokens.mul(feeRate_).div(100); // Sends the collateral from the buyer to this market require( collateralToken_.transferFrom( msg.sender, address(this), priceForTokens ), "Collateral transfer failed" ); // Sends the fee to the vault require( collateralToken_.transfer( address(creatorVault_), fee ), "Vault fee not transferred" ); // Adds the tokens to the total supply totalSupply_ = totalSupply_.add(_numTokens); //injected INTEGER OVERFLOW OR UNDERFLOW // Adds the tokens to the balance of the buyer balances[msg.sender] = balances[msg.sender].add(_numTokens); //injected INTEGER OVERFLOW OR UNDERFLOW // Validates the funding with the vault require( creatorVault_.validateFunding(fee), "Funding validation failed" ); // Works out the vaule of the tokens without the fee uint256 priceWithoutFee = priceForTokens.sub(fee); emit Transfer(address(0), _to, _numTokens); emit Mint(_to, _numTokens, priceWithoutFee, fee); return true; } /** * @notice This function returns the amount of tokens one can receive for a * specified amount of collateral token. * @param _collateralTokenOffered : Amount of reserve token offered for * purchase. * @return uint256 : The amount of tokens once can purchase with the * specified collateral. */ function collateralToTokenBuying( uint256 _collateralTokenOffered ) external view returns(uint256) { // Works out the amount of collateral for fee uint256 fee = _collateralTokenOffered.mul(feeRate_).div(100); // Removes the fee amount from the collateral offered uint256 amountLessFee = _collateralTokenOffered.sub(fee); // Works out the inverse curve of the pool with the fee removed amount return _inverseCurveIntegral( _curveIntegral(totalSupply_).add(amountLessFee) ).sub(totalSupply_); } /** * @notice This function returns the amount of tokens needed to be burnt to * withdraw a specified amount of reserve token. * @param _collateralTokenNeeded : Amount of dai to be withdraw. */ function collateralToTokenSelling( uint256 _collateralTokenNeeded ) external view returns(uint256) { return uint256( totalSupply_.sub( _inverseCurveIntegral( _curveIntegral(totalSupply_).sub(_collateralTokenNeeded) ) ) ); } /** * @notice Total collateral backing the curve. * @return uint256 : Represents the total collateral backing the curve. */ function poolBalance() external view returns (uint256){ return collateralToken_.balanceOf(address(this)); } /** * @dev The rate of fee the market pays towards the vault on token * purchases. */ function feeRate() external view returns(uint256) { return feeRate_; } /** * @return uint256 : The decimals set for the market */ function decimals() external view returns(uint256) { return decimals_; } /** * @return bool : The active stat of the market. Inactive markets have * ended. */ function active() external view returns(bool){ return active_; } /** * @notice Can only be called by this markets vault * @dev Allows the market to end once all funds have been raised. * Ends the market so that no more tokens can be bought or sold. * Tokens can still be transfered, or "withdrawn" for an enven * distribution of remaining collateral. */ function finaliseMarket() public onlyVault() returns(bool) { require(active_, "Market deactivated"); active_ = false; emit MarketTerminated(); return true; } /** * @dev Allows token holders to withdraw collateral in return for tokens * after the market has been finalised. * @param _amount: The amount of tokens they want to withdraw */ function withdraw(uint256 _amount) public returns(bool) { // Ensures withdraw can only be called in an inactive market require(!active_, "Market not finalised"); // Ensures the sender has enough tokens require(_amount <= balances[msg.sender], "Insufficient funds"); // Ensures there are no anomaly withdraws that might break calculations require(_amount > 0, "Cannot withdraw 0"); // Removes amount from user balance balances[msg.sender] = balances[msg.sender].sub(_amount); // Gets the balance of the market (vault may send excess funding) uint256 balance = collateralToken_.balanceOf(address(this)); // Performs a flat linear 100% collateralized sale uint256 collateralToTransfer = balance.mul(_amount).div(totalSupply_); // Removes token amount from the total supply totalSupply_ = totalSupply_.sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW // Ensures the sender is sent their collateral amount require( collateralToken_.transfer(msg.sender, collateralToTransfer), "Dai transfer failed" ); emit Transfer(msg.sender, address(0), _amount); emit Burn(msg.sender, _amount, collateralToTransfer); return true; } /** * @dev Returns the required collateral amount for a volume of bonding * curve tokens. * @notice The curve intergral code will reject any values that are too * small or large, that could result in over/under flows. * @param _numTokens: The number of tokens to calculate the price of * @return uint256 : The required collateral amount for a volume of bonding * curve tokens. */ function priceToMint(uint256 _numTokens) public view returns(uint256) { // Gets the balance of the market uint256 balance = collateralToken_.balanceOf(address(this)); // Performs the curve intergral with the relavant vaules uint256 collateral = _curveIntegral( totalSupply_.add(_numTokens) ).sub(balance); // Sets the base unit for decimal shift uint256 baseUnit = 100; // Adds the fee amount uint256 result = collateral.mul(100).div(baseUnit.sub(feeRate_)); return result; } /** * @dev Returns the required collateral amount for a volume of bonding * curve tokens * @param _numTokens: The number of tokens to work out the collateral * vaule of * @return uint256: The required collateral amount for a volume of bonding * curve tokens */ function rewardForBurn(uint256 _numTokens) public view returns(uint256) { // Gets the curent balance of the market uint256 poolBalanceFetched = collateralToken_.balanceOf(address(this)); // Returns the pool balance minus the curve intergral of the removed // tokens return poolBalanceFetched.sub( _curveIntegral(totalSupply_.sub(_numTokens)) ); } /** * @dev Calculate the integral from 0 to x tokens supply. Calls the * curve integral function on the math library. * @param _x : The number of tokens supply to integrate to. * @return he total supply in tokens, not wei. */ function _curveIntegral(uint256 _x) internal view returns (uint256) { return curveLibrary_.curveIntegral(_x); } /** * @dev Inverse integral to convert the incoming colateral value to * token volume. * @param _x : The volume to identify the root off */ function _inverseCurveIntegral(uint256 _x) internal view returns(uint256) { return curveLibrary_.inverseCurveIntegral(_x); } //-------------------------------------------------------------------------- // ERC20 functions //-------------------------------------------------------------------------- /** * @notice Total number of tokens in existence * @return uint256: Represents the total supply of tokens in this market. */ function totalSupply() external view returns (uint256) { return totalSupply_; } /** * @notice Gets the balance of the specified address. * @param _owner : The address to query the the balance of. * @return uint256 : Represents the amount owned by the passed address. */ function balanceOf(address _owner) external view returns (uint256) { return balances[_owner]; } /** * @notice Gets the value of the current allowance specifed for that * account. * @param _owner: The account sending the funds. * @param _spender: The account that will receive the funds. * @return uint256: representing the amount the spender can spend */ function allowance( address _owner, address _spender ) external view returns (uint256) { return allowed[_owner][_spender]; } /** * @notice Approves transfers for a given address. * @param _spender : The account that will receive the funds. * @param _value : The value of funds accessed. * @return boolean : Indicating the action was successful. */ function approve( address _spender, uint256 _value ) external returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the * caller. * @notice This is an alternative to {approve} that can be used as a * mitigation for problems described in {IERC20-approve}. */ function increaseAllowance( address _spender, uint256 _addedValue ) public returns(bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender] .add(_addedValue); //injected INTEGER OVERFLOW OR UNDERFLOW emit Approval(msg.sender, _spender, _addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the * caller. * @notice This is an alternative to {approve} that can be used as a * mitigation for problems described in {IERC20-approve}. */ function decreaseAllowance( address _spender, uint256 _subtractedValue ) public returns(bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender] .sub(_subtractedValue); //injected INTEGER OVERFLOW OR UNDERFLOW emit Approval(msg.sender, _spender, _subtractedValue); return true; } /** * @notice Transfer tokens from one address to another. * @param _from : The address which you want to send tokens from. * @param _to : The address which you want to transfer to. * @param _value : The amount of tokens to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from], "Requested amount exceeds balance"); require(_value <= allowed[_from][msg.sender], "Allowance exceeded"); require(_to != address(0), "Target account invalid"); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @notice Transfer ownership token from msg.sender to a specified address. * @param _to : The address to transfer to. * @param _value : The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender], "Insufficient funds"); require(_to != address(0), "Target account invalid"); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW emit Transfer(msg.sender, _to, _value); return true; } } /** * @title ModifiedWhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing * Whitelisted accounts. */ contract ModifiedWhitelistAdminRole { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; // this is a uint8 rather than a 256 for storage. uint8 internal noOfAdmins_; // Initial admin address address internal initialAdmin_; constructor () internal { _addWhitelistAdmin(msg.sender); initialAdmin_ = msg.sender; } modifier onlyWhitelistAdmin() { require( isWhitelistAdmin(msg.sender), "ModifiedWhitelistAdminRole: caller does not have the WhitelistAdmin role" ); _; } /** * @dev This allows for the initial admin added to have additional admin * rights, such as removing another admin. */ modifier onlyInitialAdmin() { require( msg.sender == initialAdmin_, "Only initial admin may remove another admin" ); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin() { _addWhitelistAdmin(account); } /** * @dev This allows the initial admin to replace themselves as the super * admin. * @param account: The address of the new super admin */ function addNewInitialAdmin(address account) public onlyInitialAdmin() { if(!isWhitelistAdmin(account)) { _addWhitelistAdmin(account); } initialAdmin_ = account; } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(msg.sender); } /** * @dev Allows the super admin to remover other admins * @param account: The address of the admin to be removed */ function removeWhitelistAdmin(address account) public onlyInitialAdmin() { _removeWhitelistAdmin(account); } function _addWhitelistAdmin(address account) internal { if(!isWhitelistAdmin(account)) { noOfAdmins_ += 1; } _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { noOfAdmins_ -= 1; require(noOfAdmins_ >= 1, "Cannot remove all admins"); _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } function getAdminCount() public view returns(uint8) { return noOfAdmins_; } } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title Storage and collection of market fee. * @notice The vault stores the fee from the market until the funding goal is * reached, thereafter the creator may withdraw the funds. If the * funding is not reached within the stipulated time-frame, or the * creator terminates the market, the funding is sent back to the * market to be re-distributed. * @dev The vault pulls the mol fee directly from the molecule vault. */ contract Vault is IVault, ModifiedWhitelistAdminRole { // For math functions with overflow & underflow checks using SafeMath for uint256; // For keep track of time in months using BokkyPooBahsDateTimeLibrary for uint256; // The vault benificiary address internal creator_; // Market feeds collateral to vault IMarket internal market_; // Underlying collateral token IERC20 internal collateralToken_; // Vault for molecule fee IMoleculeVault internal moleculeVault_; // Fee percentage for molecule fee, i.e 50 uint256 internal moleculeFeeRate_; // The funding round that is active uint256 internal currentPhase_; // Offset for checking funding threshold uint256 internal outstandingWithdraw_; // The total number of funding rounds uint256 internal totalRounds_; // The total cumulative fee received from market uint256 internal cumulativeReceivedFee_; // If the vault has been initialized and has not reached its funding goal bool internal _active; // All funding phases information to their position in mapping mapping(uint256 => FundPhase) internal fundingPhases_; // Information stored about each phase struct FundPhase{ uint256 fundingThreshold; // Collateral limit to trigger funding uint256 cumulativeFundingThreshold; // The cumulative funding goals uint256 fundingRaised; // The amount of funding raised uint256 phaseDuration; // Period of time for round (start to end) uint256 startDate; FundingState state; // State enum } /** * @dev Checks the range of funding rounds (1-9). Gets the Molecule fee * from the molecule vault directly. * @notice Any change in the fee rate in the Molecule Vault will not affect * already deployed vaults. This was done to ensure transparency * and trust in the fee rates. * @param _fundingGoals: The collateral goal for each funding round. * @param _phaseDurations: The time limit of each funding round. * @param _creator: The creator * @param _collateralToken: The ERC20 collateral token * @param _moleculeVault: The molecule vault */ constructor( uint256[] memory _fundingGoals, uint256[] memory _phaseDurations, address _creator, address _collateralToken, address _moleculeVault ) public ModifiedWhitelistAdminRole() { require(_fundingGoals.length > 0, "No funding goals specified"); require(_fundingGoals.length < 10, "Too many phases defined"); require( _fundingGoals.length == _phaseDurations.length, "Invalid phase configuration" ); // Storing variables in storage super.addNewInitialAdmin(_creator); outstandingWithdraw_ = 0; creator_ = _creator; collateralToken_ = IERC20(_collateralToken); moleculeVault_ = IMoleculeVault(_moleculeVault); moleculeFeeRate_ = moleculeVault_.feeRate(); // Saving the funding rounds into storage uint256 loopLength = _fundingGoals.length; for(uint8 i = 0; i < loopLength; i++) { if(moleculeFeeRate_ == 0) { fundingPhases_[i].fundingThreshold = _fundingGoals[i]; } else { // Works out the rounds fee uint256 withFee = _fundingGoals[i].add( _fundingGoals[i].mul(moleculeFeeRate_).div(100) ); // Saving the funding threshold with fee fundingPhases_[i].fundingThreshold = withFee; } // Setting the amount of funding raised so far fundingPhases_[i].fundingRaised = 0; // Setting the phase duration fundingPhases_[i].phaseDuration = _phaseDurations[i]; // Counter for the total number of rounds totalRounds_ = totalRounds_.add(1); } // Sets the start time to the current time fundingPhases_[0].startDate = block.timestamp; // Setting the state of the current phase to started fundingPhases_[0].state = FundingState.STARTED; // Setting the storage of the current phase currentPhase_ = 0; } /** * @notice Ensures that only the market may call the function. */ modifier onlyMarket() { require(msg.sender == address(market_), "Invalid requesting account"); _; } /** * @notice Ensures that the vault gets initialized before use. */ modifier isActive() { require(_active, "Vault has not been initialized."); _; } /** * @dev Initialized the contract, sets up owners and gets the market * address. This function exists because the Vault does not have * an address until the constructor has finished running. The * cumulative funding threshold is set here because of gas issues * within the constructor. * @param _market: The market that will be sending this vault it's * collateral. */ function initialize( address _market ) external onlyWhitelistAdmin() returns(bool) { require(_market != address(0), "Contracts initialized"); // Stores the market in storage market_ = IMarket(_market); // Removes the market factory contract as an admin super.renounceWhitelistAdmin(); // Adding all previous rounds funding goals to the cumulative goal for(uint8 i = 0; i < totalRounds_; i++) { if(i == 0) { fundingPhases_[i].cumulativeFundingThreshold.add( fundingPhases_[i].fundingThreshold ); } fundingPhases_[i].cumulativeFundingThreshold.add( fundingPhases_[i-1].cumulativeFundingThreshold ); } _active = true; return true; } /** * @notice Allows the creator to withdraw a round of funding. * @dev The withdraw function should be called after each funding round * has been successfully filled. If the withdraw is called after the * last round has ended, the market will terminate and any * remaining funds will be sent to the market. * @return bool : The funding has successfully been transferred. */ function withdraw() external isActive() onlyWhitelistAdmin() returns(bool) { require(outstandingWithdraw_ > 0, "No funds to withdraw"); for(uint8 i; i <= totalRounds_; i++) { if(fundingPhases_[i].state == FundingState.PAID) { continue; } else if(fundingPhases_[i].state == FundingState.ENDED) { // Removes this rounds funding from the outstanding withdraw outstandingWithdraw_ = outstandingWithdraw_.sub( fundingPhases_[i].fundingThreshold ); // Sets the rounds funding to be paid fundingPhases_[i].state = FundingState.PAID; uint256 molFee = fundingPhases_[i].fundingThreshold .mul(moleculeFeeRate_) .div(moleculeFeeRate_.add(100)); // Transfers the mol fee to the molecule vault require( collateralToken_.transfer(address(moleculeVault_), molFee), "Tokens not transfer" ); // Working out the original funding goal without the mol fee uint256 creatorAmount = fundingPhases_[i].fundingThreshold .sub(molFee); // Sending the creator their collateral amount require( collateralToken_.transfer(msg.sender, creatorAmount), "Tokens not transfer" ); emit FundingWithdrawn(i, creatorAmount); } else { break; } } // This checks if the current round is the last round, if it is, it // terminates the market and sends all remaining funds to the market. if( fundingPhases_[currentPhase_].state == FundingState.NOT_STARTED ) { if(market_.active() && outstandingWithdraw_ == 0) { // This will transfer any remaining funding to the market terminateMarket(); } } return true; } /** * @notice Allows the market to check that the funding round(s) have not * been completed, and that the market is still open. * @dev This function will terminate the market if the time for the * round is exceeded. This will loose any funding the creator has * not withdrawn. * @param _receivedFunding: The amount of funding received * @return bool: Whether or not the funding is valid */ function validateFunding( uint256 _receivedFunding ) external isActive() onlyMarket() returns(bool) { require( fundingPhases_[currentPhase_].state == FundingState.STARTED, "Funding inactive" ); // Works out the time the phase should end uint256 endOfPhase = fundingPhases_[currentPhase_].startDate .addMonths(fundingPhases_[currentPhase_].phaseDuration); // Invalidates mint in market if the rounds time has expired. if(endOfPhase <= block.timestamp) { terminateMarket(); return false; } // Gets the balance of the vault against the collateral token uint256 balance = collateralToken_.balanceOf(address(this)); // Adds the fee to the funding raised for this round fundingPhases_[currentPhase_] .fundingRaised = fundingPhases_[currentPhase_] .fundingRaised.add(_receivedFunding); //injected INTEGER OVERFLOW OR UNDERFLOW // Adds received funding to the cumulative record of fee received cumulativeReceivedFee_.add(_receivedFunding); // Ensures the total fee received finishes the current round if( fundingPhases_[currentPhase_].cumulativeFundingThreshold <= cumulativeReceivedFee_ && balance.sub(outstandingWithdraw_) >= fundingPhases_[currentPhase_].fundingThreshold ) { // Ensures that the round has been funded correctly assert( fundingPhases_[currentPhase_].fundingRaised >= fundingPhases_[currentPhase_].fundingThreshold ); // end current round will check if there is excess funding and add // it to the next round, as well as incrementing the current round _endCurrentRound(); // Checks if the funding raised is larger than this rounds goal if( fundingPhases_[currentPhase_].fundingRaised > fundingPhases_[currentPhase_].fundingThreshold ) { // Ends the round _endCurrentRound(); // Ensures the received funding does not finish any other rounds do { // checks if the next funding rounds cumulative funding goal // is completed if( fundingPhases_[currentPhase_] .cumulativeFundingThreshold <= cumulativeReceivedFee_ && balance.sub(outstandingWithdraw_) >= fundingPhases_[currentPhase_].fundingThreshold ) { _endCurrentRound(); } else { break; } } while(currentPhase_ < totalRounds_); } } return true; } /** * @dev This function sends the vaults funds to the market, and sets the * outstanding withdraw to 0. * @notice If this function is called before the end of all phases, all * unclaimed (outstanding) funding will be sent to the market to be * redistributed. */ function terminateMarket() public isActive() onlyWhitelistAdmin() { uint256 remainingBalance = collateralToken_.balanceOf(address(this)); // This ensures that if the creator has any outstanding funds, that // those funds do not get sent to the market. if(outstandingWithdraw_ > 0) { remainingBalance = remainingBalance.sub(outstandingWithdraw_); } // Transfers remaining balance to the market require( collateralToken_.transfer(address(market_), remainingBalance), "Transfering of funds failed" ); // Finalizes market (stops buys/sells distributes collateral evenly) require(market_.finaliseMarket(), "Market termination error"); } /** * @notice Returns all the details (relevant to external code) for a * specific phase. * @param _phase: The phase that you want the information of * @return uint256: The funding goal (including mol tax) of the round * @return uint256: The amount of funding currently raised for the round * @return uint256: The duration of the phase * @return uint256: The timestamp of the start date of the round * @return FundingState: The enum state of the round (see IVault) */ function fundingPhase( uint256 _phase ) public view returns( uint256, uint256, uint256, uint256, FundingState ) { return ( fundingPhases_[_phase].fundingThreshold, fundingPhases_[_phase].fundingRaised, fundingPhases_[_phase].phaseDuration, fundingPhases_[_phase].startDate, fundingPhases_[_phase].state ); } /** * @return uint256: The amount of funding that the creator has earned by * not withdrawn. */ function outstandingWithdraw() public view returns(uint256) { uint256 minusMolFee = outstandingWithdraw_ .sub(outstandingWithdraw_ .mul(moleculeFeeRate_) .div(moleculeFeeRate_.add(100)) ); return minusMolFee; } /** * @dev The current active phase of funding * @return uint256: The current phase the project is in. */ function currentPhase() public view returns(uint256) { return currentPhase_; } /** * @return uint256: The total number of rounds for this project. */ function getTotalRounds() public view returns(uint256) { return totalRounds_; } /** * @return address: The address of the market that is funding this vault. */ function market() public view returns(address) { return address(market_); } /** * @return address: The address of the creator of this project. */ function creator() external view returns(address) { return creator_; } /** * @dev Ends the round, increments to the next round, rolls-over excess * funding, sets the start date of the next round, if there is one. */ function _endCurrentRound() internal { // Setting active phase state to ended fundingPhases_[currentPhase_].state = FundingState.ENDED; // Works out the excess funding for the round uint256 excess = fundingPhases_[currentPhase_] .fundingRaised.sub(fundingPhases_[currentPhase_].fundingThreshold); // If there is excess, adds it to the next round if (excess > 0) { // Adds the excess funding into the next round. fundingPhases_[currentPhase_.add(1)] .fundingRaised = fundingPhases_[currentPhase_.add(1)] .fundingRaised.add(excess); // Setting the current rounds funding raised to the threshold fundingPhases_[currentPhase_] .fundingRaised = fundingPhases_[currentPhase_].fundingThreshold; } // Adding the funished rounds funding to the outstanding withdraw. outstandingWithdraw_ = outstandingWithdraw_ .add(fundingPhases_[currentPhase_].fundingThreshold); // Incrementing the current phase currentPhase_ = currentPhase_ + 1; // Set the states the start time, starts the next round if there is one. if(fundingPhases_[currentPhase_].fundingThreshold > 0) { // Setting active phase state to Started fundingPhases_[currentPhase_].state = FundingState.STARTED; // This works out the end time of the previous round uint256 endTime = fundingPhases_[currentPhase_ .sub(1)].startDate .addMonths(fundingPhases_[currentPhase_].phaseDuration); // This works out the remaining time uint256 remaining = endTime.sub(block.timestamp); // This sets the start date to the end date of the previous round fundingPhases_[currentPhase_].startDate = block.timestamp .add(remaining); } emit PhaseFinalised( currentPhase_.sub(1), fundingPhases_[currentPhase_.sub(1)].fundingThreshold ); } } // import { WhitelistedRole } from "openzeppelin-solidity/contracts/access/roles/WhitelistedRole.sol"; /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title The creation and co-ordinated storage of markets (a vault and * market). * @notice The market factory stores the addresses in the relevant registry. */ contract MarketFactory is IMarketFactory, ModifiedWhitelistAdminRole { //The molecule vault for molecule fee IMoleculeVault internal moleculeVault_; //The registry of all created markets IMarketRegistry internal marketRegistry_; //The registry of all curve types ICurveRegistry internal curveRegistry_; //The ERC20 collateral token contract address IERC20 internal collateralToken_; // Address of market deployer address internal marketCreator_; // The init function can only be called once bool internal isInitialized_ = false; event NewApiAddressAdded(address indexed oldAddress, address indexed newAddress); modifier onlyAnAdmin() { require(isInitialized_, "Market factory has not been activated"); require( isWhitelistAdmin(msg.sender) || msg.sender == marketCreator_, "Functionality restricted to whitelisted admin" ); _; } /** * @dev Sets variables for market deployments. * @param _collateralToken Address of the ERC20 collateral token * @param _moleculeVault The address of the molecule fee vault * @param _marketRegistry Address of the registry of all markets * @param _curveRegistry Address of the registry of all curve types * funding rounds. */ constructor( address _collateralToken, address _moleculeVault, address _marketRegistry, address _curveRegistry ) ModifiedWhitelistAdminRole() public { collateralToken_ = IERC20(_collateralToken); moleculeVault_ = IMoleculeVault(_moleculeVault); marketRegistry_ = IMarketRegistry(_marketRegistry); curveRegistry_ = ICurveRegistry(_curveRegistry); } /** * @notice Inits the market factory * @param _admin The address of the admin contract manager * @param _api The address of the backend market deployer */ function init( address _admin, address _api ) onlyWhitelistAdmin() public { super.addNewInitialAdmin(_admin); marketCreator_ = _api; super.renounceWhitelistAdmin(); isInitialized_ = true; } function updateApiAddress( address _newApiPublicKey ) onlyWhitelistAdmin() public returns(address) { address oldMarketCreator = marketCreator_; marketCreator_ = _newApiPublicKey; emit NewApiAddressAdded(oldMarketCreator, marketCreator_); return _newApiPublicKey; } /** * @notice This function allows for the creation of a new market, * consisting of a curve and vault. If the creator address is the * same as the deploying address the market the initialization of * the market will fail. * @dev Vyper cannot handle arrays of unknown length, and thus the * funding goals and durations will only be stored in the vault, * which is Solidity. * @param _fundingGoals This is the amount wanting to be raised in each * round, in collateral. * @param _phaseDurations The time for each round in months. This number * is covered into block time within the vault. * @param _creator Address of the researcher. * @param _curveType Curve selected. * @param _feeRate The percentage of fee. e.g: 60 */ function deployMarket( uint256[] calldata _fundingGoals, uint256[] calldata _phaseDurations, address _creator, uint256 _curveType, uint256 _feeRate ) external onlyAnAdmin() { // Breaks down the return of the curve data (address curveLibrary,, bool curveState) = curveRegistry_.getCurveData( _curveType ); require(_feeRate > 0, "Fee rate too low"); require(_feeRate < 100, "Fee rate too high"); require(_creator != address(0), "Creator address invalid"); require(curveState, "Curve inactive"); require(curveLibrary != address(0), "Curve library invalid"); address newVault = address(new Vault( _fundingGoals, _phaseDurations, _creator, address(collateralToken_), address(moleculeVault_) )); address newMarket = address(new Market( _feeRate, newVault, curveLibrary, address(collateralToken_) )); require(Vault(newVault).initialize(newMarket), "Vault not initialized"); marketRegistry_.registerMarket(newMarket, newVault, _creator); } /** * @notice This function will only affect new markets, and will not update * already created markets. This can only be called by an admin */ function updateMoleculeVault( address _newMoleculeVault ) public onlyWhitelistAdmin() { moleculeVault_ = IMoleculeVault(_newMoleculeVault); } /** * @return address: The address of the molecule vault */ function moleculeVault() public view returns(address) { return address(moleculeVault_); } /** * @return address: The contract address of the market registry. */ function marketRegistry() public view returns(address) { return address(marketRegistry_); } /** * @return address: The contract address of the curve registry */ function curveRegistry() public view returns(address) { return address(curveRegistry_); } /** * @return address: The contract address of the collateral token */ function collateralToken() public view returns(address) { return address(collateralToken_); } }
* @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) @title The interface for the market registry./ Emitted when a market is created Emitted when a deployer is added Emitted when a deployer is removed
interface IMarketRegistry { event MarketCreated( uint256 index, address indexed marketAddress, address indexed vault, address indexed creator ); event DeployerAdded(address deployer, string version); event DeployerRemoved(address deployer, string reason); function addMarketDeployer( address _newDeployer, string calldata _version ) external; function removeMarketDeployer( address _deployerToRemove, string calldata _reason ) external; function registerMarket( address _marketAddress, address _vault, address _creator ) external returns(uint256); function getMarket(uint256 _index) external view returns( address, address, address ); function getIndex() external view returns(uint256); function isMarketDeployer(address _deployer) external view returns(bool); function publishedBlocknumber() external view returns(uint256); } }
12,535,496
[ 1, 36, 502, 15506, 69, 13394, 261, 3945, 15506, 69, 385, 659, 3428, 13, 473, 632, 54, 93, 54, 93, 7235, 5558, 21, 261, 54, 93, 304, 423, 947, 292, 13, 282, 1021, 1560, 364, 326, 13667, 4023, 18, 19, 512, 7948, 1347, 279, 13667, 353, 2522, 512, 7948, 1347, 279, 7286, 264, 353, 3096, 512, 7948, 1347, 279, 7286, 264, 353, 3723, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 3882, 278, 4243, 288, 203, 565, 871, 6622, 278, 6119, 12, 203, 202, 202, 11890, 5034, 770, 16, 203, 202, 202, 2867, 8808, 13667, 1887, 16, 203, 202, 202, 2867, 8808, 9229, 16, 203, 202, 202, 2867, 8808, 11784, 203, 565, 11272, 203, 565, 871, 7406, 264, 8602, 12, 2867, 7286, 264, 16, 533, 1177, 1769, 203, 202, 2575, 7406, 264, 10026, 12, 2867, 7286, 264, 16, 533, 3971, 1769, 203, 203, 565, 445, 527, 3882, 278, 10015, 264, 12, 203, 1377, 1758, 389, 2704, 10015, 264, 16, 203, 1377, 533, 745, 892, 389, 1589, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 1206, 3882, 278, 10015, 264, 12, 203, 1377, 1758, 389, 12411, 264, 12765, 16, 203, 1377, 533, 745, 892, 389, 10579, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 1744, 3882, 278, 12, 203, 3639, 1758, 389, 27151, 1887, 16, 203, 3639, 1758, 389, 26983, 16, 203, 3639, 1758, 389, 20394, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1135, 12, 11890, 5034, 1769, 203, 203, 565, 445, 23232, 278, 12, 11890, 5034, 389, 1615, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 12, 203, 5411, 1758, 16, 203, 5411, 1758, 16, 203, 5411, 1758, 203, 3639, 11272, 203, 203, 565, 445, 8088, 1435, 3903, 1476, 1135, 12, 11890, 5034, 1769, 203, 203, 565, 445, 353, 3882, 278, 10015, 264, 12, 2867, 389, 12411, 264, 13, 3903, 1476, 1135, 12, 6430, 1769, 203, 203, 565, 445, 9487, 1768, 2696, 1435, 3903, 1476, 1135, 12, 11890, 2 ]
./full_match/1/0xF6bd736C4fd44fa4910775737008ECf648BAd657/sources/contracts/Zach Yacht Club.sol
* @notice Function queries and returns the URI for a NFT tokenId. Enter the tokenId of the NFT in tokenId field./
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (revealedStatus == false) { return notRevealedMetadataURL; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), metadataURLSuffix)) : ""; }
4,979,450
[ 1, 2083, 6218, 471, 1135, 326, 3699, 364, 279, 423, 4464, 1147, 548, 18, 15439, 326, 1147, 548, 434, 326, 423, 4464, 316, 1147, 548, 652, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 2277, 30, 3699, 843, 364, 1661, 19041, 1147, 8863, 203, 3639, 309, 261, 266, 537, 18931, 1482, 422, 629, 13, 288, 203, 5411, 327, 486, 426, 537, 18931, 2277, 1785, 31, 203, 3639, 289, 203, 3639, 533, 3778, 783, 2171, 3098, 273, 389, 1969, 3098, 5621, 203, 3639, 327, 1731, 12, 2972, 2171, 3098, 2934, 2469, 405, 374, 692, 533, 12, 21457, 18, 3015, 4420, 329, 12, 2972, 2171, 3098, 16, 1147, 548, 18, 10492, 9334, 1982, 1785, 5791, 3719, 294, 1408, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import "./RPS.sol"; import "./RandomGenerator.sol"; contract Game is RPS, RandomGenerator { address public immutable owner; // Game utilities mapping(address => bool ) private _userInitGame; mapping(uint => bytes32) private _options; mapping(uint => bytes32) private _playerSelectedOption; mapping(uint => uint) private _randomRequestsResult; // Valid Options bytes32 public constant ROCK = keccak256("ROCK"); bytes32 public constant PAPER = keccak256("PAPER"); bytes32 public constant SCISSORS = keccak256("SCISSORS"); // Game config uint public constant COST_PER_GAME = 10; uint public constant WIN_PAYING_AMOUNT = 30; uint private constant COURTESY_AMOUNT = 100; uint private constant MINTING_AMOUNT = 1000; // Outcomes bytes32 public constant PLAYER_WINS = keccak256("PLAYER WINS"); bytes32 public constant TIED_ROUND = keccak256("TIED ROUND"); bytes32 public constant PLAYER_LOSES = keccak256("PLAYER LOSES"); // Error constants uint private constant RANDOM_IN_PROGRESS = 8; // Random number is not available yet uint private constant ALREADY_VISITED = 9; // User has queried the result of the match before // Events event PlayerRoundStarted( uint indexed requestId, address indexed player ); event ContractChoiceReady( uint indexed requestId, uint indexed randomChoice ); event RoundOutcome( uint indexed requestId, bytes32 indexed contractChoice, bytes32 indexed result ); constructor() { owner = msg.sender; // Set options _options[0] = ROCK; _options[1] = PAPER; _options[2] = SCISSORS; // Initial RPS Balance _mint(msg.sender, MINTING_AMOUNT); } function joinGame() public { require( msg.sender != owner, "Owner cannot be the player." ); require( _userInitGame[msg.sender] != true, "You already have joined to the game." ); _userInitGame[msg.sender] = true; // Give some tokens to the player if(balanceOf(msg.sender) == 0){ _transfer(owner, msg.sender, COURTESY_AMOUNT); } } function play( bytes32 playerSelectedOption_ ) public payable { require( _userInitGame[msg.sender] == true, "You have not joined to the game." ); require( (playerSelectedOption_ == ROCK || playerSelectedOption_ == PAPER || playerSelectedOption_ == SCISSORS), "Invalid option." ); if(balanceOf(owner) <= WIN_PAYING_AMOUNT) { _mint(owner, MINTING_AMOUNT); } _transfer(msg.sender, owner, COST_PER_GAME); // Request a random number uint requestId = super.requestRandomWords(); _playerSelectedOption[requestId] = playerSelectedOption_; _randomRequestsResult[requestId] = RANDOM_IN_PROGRESS; emit PlayerRoundStarted(requestId, msg.sender); } function fulfillRandomWords( uint256 requestId, uint256[] memory randomWords ) internal override { uint randomOption = (randomWords[0] % 3) + 1; // Random can't be 0 _randomRequestsResult[requestId] = randomOption; emit ContractChoiceReady(requestId, randomOption); } function queryOutcome( uint256 requestId ) public { require( _randomRequestsResult[requestId] != RANDOM_IN_PROGRESS, "Outcome not available yet." ); require( _randomRequestsResult[requestId] != 0, "Request not found." ); require( _randomRequestsResult[requestId] != ALREADY_VISITED, "The outcome for this match was queried before." ); bytes32 playerSelectedOption_ = _playerSelectedOption[requestId]; bytes32 contractChoice = _options[_randomRequestsResult[requestId] - 1]; // Options start from 0 _randomRequestsResult[requestId] = ALREADY_VISITED; // Outcomes if(isAWinScenario(playerSelectedOption_, contractChoice)) { // User win _transfer(owner, msg.sender, WIN_PAYING_AMOUNT); emit RoundOutcome(requestId, contractChoice, PLAYER_WINS); }else if (playerSelectedOption_ == contractChoice){ // Tied match _transfer(owner, msg.sender, COST_PER_GAME); emit RoundOutcome(requestId, contractChoice, TIED_ROUND); }else { emit RoundOutcome(requestId, contractChoice, PLAYER_LOSES); } } function isAWinScenario( bytes32 playerSelectedOption_, bytes32 contractChoice ) private pure returns (bool){ if(playerSelectedOption_ == PAPER && contractChoice == ROCK){ return true; }else if(playerSelectedOption_ == SCISSORS && contractChoice == PAPER){ return true; }else if (playerSelectedOption_ == ROCK && contractChoice == SCISSORS){ return true; } return false; } function finishGame() public { require( _userInitGame[msg.sender] == true, "You have not joined to the game." ); // User is no longer playing _userInitGame[msg.sender] = false; } }
User has queried the result of the match before
uint private constant ALREADY_VISITED = 9;
7,219,640
[ 1, 1299, 711, 23264, 326, 563, 434, 326, 845, 1865, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 3238, 5381, 7981, 20305, 67, 26780, 1285, 2056, 273, 2468, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // 'SUSW' 'SUSWITZ' Smart Contract // // Symbol : SUSW // Name : SUSWITZ // Total supply: 777,777,777 // Decimals : 10 // // // //The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract SUSW is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "SUSW"; name = "SUSWITZ"; decimals = 10; _totalSupply = 777777777 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and a fixed supply ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract SUSW is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "SUSW"; name = "SUSWITZ"; decimals = 10; _totalSupply = 777777777 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function () external payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
13,878,265
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 279, 5499, 14467, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 3378, 59, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 55, 3378, 59, 14432, 203, 3639, 508, 273, 315, 55, 3378, 59, 1285, 62, 14432, 203, 3639, 15105, 273, 1728, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2371, 4700, 4700, 4700, 4700, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 3639, 324, 26488, 63, 8443, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 3410, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 18, 1717, 12, 70, 26488, 63, 2867, 12, 20, 13, 19226, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 1476, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 2316, 5541, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 324, 26488, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; /** * @dev Utility library of inline functions on addresses. */ library AddressUtils { /** * @dev Returns whether the target address is a contract. * @param _addr Address to check. */ function isContract( address _addr ) internal view returns (bool addressCheck) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // 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; assembly { codehash := extcodehash(_addr) } // solhint-disable-line addressCheck = (codehash != 0x0 && codehash != accountHash); } } /** * @dev ERC-721 non-fungible token standard. See https://goo.gl/pc9yoS. */ interface ERC721 { /** * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any * number of NFTs may be created and assigned without emitting Transfer. At the time of any * transfer, the approved address for that NFT (if any) is reset to none. */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /** * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero * address indicates there is no approved address. When a Transfer event emits, this also * indicates that the approved address for that NFT (if any) is reset to none. */ event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /** * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage * all NFTs of the owner. */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. */ function balanceOf( address _owner ) external view returns (uint256); /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. */ function ownerOf( uint256 _tokenId ) external view returns (address); /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received` * on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they mayb be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Set or reaffirm the approved address for an NFT. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved The new approved NFT controller. * @param _tokenId The NFT to approve. */ function approve( address _approved, uint256 _tokenId ) external; /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice The contract MUST allow multiple operators per owner. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external; /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for. */ function getApproved( uint256 _tokenId ) external view returns (address); /** * @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool); } /** * @dev Optional enumeration extension for ERC-721 non-fungible token standard. * See https://goo.gl/pc9yoS. */ interface ERC721Enumerable { /** * @dev Returns a count of valid NFTs tracked by this contract, where each one of them has an * assigned and queryable owner not equal to the zero address. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT. Sort order is not specified. * @param _index A counter less than `totalSupply()`. */ function tokenByIndex( uint256 _index ) external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT assigned to `_owner`. Sort order is * not specified. It throws if `_index` >= `balanceOf(_owner)` or if `_owner` is the zero address, * representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them. * @param _index A counter less than `balanceOf(_owner)`. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external view returns (uint256); } /** * @dev Optional metadata extension for ERC-721 non-fungible token standard. * See https://goo.gl/pc9yoS. */ interface ERC721Metadata { /** * @dev Returns a descriptive name for a collection of NFTs in this contract. */ function name() external view returns (string memory _name); /** * @dev Returns a abbreviated name for a collection of NFTs in this contract. */ function symbol() external view returns (string memory _symbol); /** * @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if * `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file * that conforms to the "ERC721 Metadata JSON Schema". */ function tokenURI(uint256 _tokenId) external view returns (string memory); } /** * @dev ERC-721 interface for accepting safe transfers. See https://goo.gl/pc9yoS. */ interface ERC721TokenReceiver { /** * @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the * recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return * of other than the magic value MUST result in the transaction being reverted. * Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing. * @notice The contract address is always the message sender. A wallet/broker/auction application * MUST implement the wallet interface if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function. * @param _from The address which previously owned the token. * @param _tokenId The NFT identifier which is being transferred. * @param _data Additional data with no specified format. */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external returns(bytes4); } /** * @dev A standard for detecting smart contract interfaces. See https://goo.gl/cxQCse. */ interface ERC165 { /** * @dev Checks if the smart contract includes a specific interface. * @notice This function uses less than 30,000 gas. * @param _interfaceID The interface identifier, as specified in ERC-165. */ function supportsInterface( bytes4 _interfaceID ) external view returns (bool); } contract BasicValidator { using AddressUtils for address; bytes4 constant ERC165ID = 0x01ffc9a7; bytes4 constant ERC721ID = 0x80ac58cd; bytes4 constant ERC721MetadataID = 0x5b5e139f; bytes4 constant ERC721EnumerableID = 0x780e9d63; constructor( uint256 _caseId, address _target ) { if (_caseId == 1) { sanityCheck(_target); return; } else if (_caseId == 2) { checkERC165Interface(_target); return; } else if (_caseId == 3) { checkERC721Interface(_target); return; } else if (_caseId == 4) { checkERC721MetadataInterface(_target); return; } else if (_caseId == 5) { checkERC721EnumerableInterface(_target); return; } else if (_caseId == 6){ checkBalanceOfZeroAddress(_target); return; } else if (_caseId == 7){ checkMetadataName(_target); return; } else if (_caseId == 8){ checkMetadataSymbol(_target); return; } else if (_caseId == 9){ checkTotalSupply(_target); return; } else if (_caseId == 10){ checkZeroTokenByIndex(_target); return; } assert(false); } /** * @dev Sanity checks * Find the amount of value (ether) assigned to CONTRACT_ADDRESS, it should be greater than or * equal to zero. Find the code_size of CONTRACT_ADDRESS, it should be greater than zero. */ function sanityCheck( address _target ) internal { require(_target.balance >= 0); assert(_target.isContract()); } /** * @dev Check interface 165. */ function checkERC165Interface( address _target ) internal { bool result = ERC165(_target).supportsInterface(ERC165ID); assert(result); } /** * @dev Check interface ERC721. */ function checkERC721Interface( address _target ) internal { bool result = ERC165(_target).supportsInterface(ERC721ID); assert(result); } /** * @dev Check interface ERC721Metadata. */ function checkERC721MetadataInterface( address _target ) internal { bool result = ERC165(_target).supportsInterface(ERC721MetadataID); assert(result); } /** * @dev Check interface ERC721Enumerable. */ function checkERC721EnumerableInterface( address _target ) internal { bool result = ERC165(_target).supportsInterface(ERC721EnumerableID); assert(result); } /** * @dev balanceOf(0) should throw. */ function checkBalanceOfZeroAddress( address _target ) internal { ERC721(_target).balanceOf(address(0)); } /** * @dev name() should not throw. */ function checkMetadataName( address _target ) internal { ERC721Metadata(_target).name(); } /** * @dev symbol() should not throw. */ function checkMetadataSymbol( address _target ) internal { ERC721Metadata(_target).symbol(); } /** * @dev totalSupply should be greater than 0. */ function checkTotalSupply( address _target ) internal { require(ERC721Enumerable(_target).totalSupply() > 0); } /** * @dev tokenByIndex(0) should not throw. */ function checkZeroTokenByIndex( address _target ) internal { ERC721Enumerable(_target).tokenByIndex(0); } } contract Stub1 is ERC721TokenReceiver { bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; constructor() {} /** * @dev Receive token and map id to contract address (which is parsed from data). */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) override external returns(bytes4) { require(StringUtils.compare2(_data, "") == 0); return MAGIC_ON_ERC721_RECEIVED; } function transferToken( address _contract, uint256 _tokenId, address _receiver ) external { ERC721(_contract).transferFrom(ERC721(_contract).ownerOf(_tokenId), _receiver, _tokenId); } } contract Stub2 is ERC721TokenReceiver { bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; /** * @dev Receive token and map id to contract address (which is parsed from data). */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) override external returns(bytes4) { require(StringUtils.compare2(_data, "ffff") == 0); // bytes memory temp = bytes(_data); //require(temp == bytes(0x0)); return MAGIC_ON_ERC721_RECEIVED; } } contract Stub3 is ERC721TokenReceiver { bytes4 constant MAGIC_ON_ERC721_RECEIVED_FALSE = 0x150b7a0b; /** * @dev Receive token and map id to contract address (which is parsed from data). */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) override external returns(bytes4) { return MAGIC_ON_ERC721_RECEIVED_FALSE; } } contract Stub4 { function test() public pure {} } contract TokenValidator { constructor( uint256 _caseId, address _target, uint256 _tokenId ) { if (_caseId == 1) { checkTokenUri(_target, _tokenId); return; } else if (_caseId == 2) { checkBalanceBasedOnToken(_target, _tokenId); return; } else if (_caseId == 3) { checkNotEmptyOwner(_target, _tokenId); return; } assert(false); } /** * @dev tokenURI(TEST_TOKEN_ID) should not throw. */ function checkTokenUri( address _target, uint256 _tokenId ) internal { ERC721Metadata(_target).tokenURI(_tokenId); } /** * @dev balanceOf(ownerOf(TEST_TOKEN_ID) should be > 0. */ function checkBalanceBasedOnToken( address _target, uint256 _tokenId ) internal { require(ERC721(_target).balanceOf(ERC721(_target).ownerOf(_tokenId)) > 0); } /** * @dev ownerOf(TEST_TOKEN_ID) should return an address > 0. */ function checkNotEmptyOwner( address _target, uint256 _tokenId ) internal { require(ERC721(_target).ownerOf(_tokenId) != address(0)); } } contract TransferValidator { bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; address constant stubAddress = 0x85A9916425960aA35B2a527D77C71855DC0215B3; constructor( uint256 _caseId, address _target, uint256 _tokenId, address _giver ) payable { if (_caseId == 1) { checkTransferFromGiver(_target, _tokenId, _giver); return; } else if (_caseId == 2) { getTokenFromGiver(_target, _giver, _tokenId); checkBalanceOnTransfer(_target, _tokenId); return; } else if (_caseId == 3) { getTokenFromGiver(_target, _giver, _tokenId); checkTransferToZeroAddress(_target, _tokenId); return; } else if (_caseId == 4) { getTokenFromGiver(_target, _giver, _tokenId); checkSafeTransferCallBackData(_target, _tokenId); return; } else if (_caseId == 5) { getTokenFromGiver(_target, _giver, _tokenId); checkSafeTransferCallBack(_target, _tokenId); return; } else if (_caseId == 6) { getTokenFromGiver(_target, _giver, _tokenId); checkSafeTransferNoCallBack(_target, _tokenId); return; } else if (_caseId == 7) { getTokenFromGiver(_target, _giver, _tokenId); checkSafeTransferWrongMagicValue(_target, _tokenId); return; } else if (_caseId == 8) { getTokenFromGiver(_target, _giver, _tokenId); checkGetApproved(_target, _tokenId); return; } else if (_caseId == 9) { getTokenFromGiver(_target, _giver, _tokenId); checkApproveAndTransfer(_target, _tokenId); return; } else if (_caseId == 10) { getTokenFromGiver(_target, _giver, _tokenId); checkApprovalForAll(_target, _tokenId); return; } else if (_caseId == 11) { getTokenFromGiver(_target, _giver, _tokenId); checkApproveForAllAndTransfer(_target, _tokenId); return; } else if (_caseId == 12) { getTokenFromGiver(_target, _giver, _tokenId); checkZeroTokenOfOwnerByIndex(_target); return; } else if (_caseId == 13) { getTokenFromGiver(_target, _giver, _tokenId); checkOverflowTokenOfOwnerByIndex(_target); return; } else if (_caseId == 14) { getTokenFromGiver(_target, _giver, _tokenId); return; } assert(false); } function getTokenFromGiver( address _target, address _giver, uint256 _tokenId ) internal { Giver(_giver).getToken{value:1000000 ether}(_target, _tokenId); } /** * @dev transferFrom giver to self, this should throw because giver does not authorize the * transaction. */ function checkTransferFromGiver( address _target, uint256 _tokenId, address _giver ) internal { ERC721(_target).transferFrom(_giver, address(this), _tokenId); } /** * @dev Get a token from giver, transferFrom self to a stub, check balanceOf() stub before and * after transfer, it should be one more. */ function checkBalanceOnTransfer( address _target, uint256 _tokenId ) internal { uint256 balance = ERC721(_target).balanceOf(stubAddress); ERC721(_target).transferFrom(address(this), stubAddress, _tokenId); require(ERC721(_target).balanceOf(stubAddress) == balance + 1); } /** * @dev Get a token from giver, transferFrom to zero address, should throw. */ function checkTransferToZeroAddress( address _target, uint256 _tokenId ) internal { ERC721(_target).transferFrom(address(this), address(0), _tokenId); } /** * @dev Get a token from giver, safe transfer to stub by sending data ffff. Stub throws in * callback if it does not receive ffff. */ function checkSafeTransferCallBackData( address _target, uint256 _tokenId ) internal { Stub2 stub = new Stub2(); ERC721(_target).safeTransferFrom(address(this), address(stub), _tokenId, "ffff"); } /** * @dev Get a token from giver, safe transfer to stub using the default argument. Stub throws in * callback if it does not receive "". */ function checkSafeTransferCallBack( address _target, uint256 _tokenId ) internal { Stub1 stub = new Stub1(); ERC721(_target).safeTransferFrom(address(this), address(stub), _tokenId); } /** * @dev Get a token from giver, safe transfer to contract stud that does not implement token * receiver, should throw. */ function checkSafeTransferNoCallBack( address _target, uint256 _tokenId ) internal { Stub4 stub = new Stub4(); ERC721(_target).safeTransferFrom(address(this), address(stub), _tokenId, "ffff"); } /** * @dev Get a token from giver, safe transfer to stub, the stub does not return the correct magic * value, the transfer must throw */ function checkSafeTransferWrongMagicValue( address _target, uint256 _tokenId ) internal { Stub3 stub = new Stub3(); ERC721(_target).safeTransferFrom(address(this), address(stub), _tokenId); } /** * @dev Get a token from giver, approve stub, then check getApproved stub; */ function checkGetApproved( address _target, uint256 _tokenId ) internal { ERC721(_target).approve(stubAddress, _tokenId); require(ERC721(_target).getApproved(_tokenId) == stubAddress); } /** * @dev Get a token from giver, approve stub, then have stub transferFrom to stub2. */ function checkApproveAndTransfer( address _target, uint256 _tokenId ) internal { Stub1 stub = new Stub1(); ERC721(_target).approve(address(stub), _tokenId); uint256 balance = ERC721(_target).balanceOf(stubAddress); stub.transferToken(_target, _tokenId, stubAddress); require(ERC721(_target).balanceOf(stubAddress) == balance + 1); } /** * @dev Get a token from giver, approveForAll to stub, then check isApprovedForAll. */ function checkApprovalForAll( address _target, uint256 _tokenId ) internal { ERC721(_target).setApprovalForAll(stubAddress, true); require(ERC721(_target).isApprovedForAll(address(this), stubAddress)); } /** * @dev Get a token from giver, approveFor All to stub, then have stub transferFrom to stub2. */ function checkApproveForAllAndTransfer( address _target, uint256 _tokenId ) internal { Stub1 stub = new Stub1(); ERC721(_target).setApprovalForAll(address(stub), true); uint256 balance = ERC721(_target).balanceOf(stubAddress); stub.transferToken(_target, _tokenId, stubAddress); require(ERC721(_target).balanceOf(stubAddress) == balance + 1); } /** * @dev Get token from giver, find balanceOf(self), tokenOfOwnerByIndex(0) should not throw. */ function checkZeroTokenOfOwnerByIndex( address _target ) internal { require(ERC721(_target).balanceOf(address(this)) > 0); ERC721Enumerable(_target).tokenOfOwnerByIndex(address(this), 0); } /** * @dev Get token from giver, find balanceOf(self), tokenOfOwnerByIndex(balanceOf(self)) should * throw. */ function checkOverflowTokenOfOwnerByIndex( address _target ) internal { uint256 balance = ERC721(_target).balanceOf(address(this)); ERC721Enumerable(_target).tokenOfOwnerByIndex(address(this), balance); } } library StringUtils { /// @dev Does a byte-by-byte lexicographical comparison of two strings. /// @return a negative number if `_a` is smaller, zero if they are equal /// and a positive numbe if `_b` is smaller. function compare(string memory _a, string memory _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; //@todo unroll the loop into increments of 32 and do full 32 byte comparisons for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function compare2(bytes memory _a, string memory _b) internal returns (int) { bytes memory a = _a; bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; //@todo unroll the loop into increments of 32 and do full 32 byte comparisons for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } /// @dev Compares two strings and returns true iff they are equal. function equal(string memory _a, string memory _b) internal returns (bool) { return compare(_a, _b) == 0; } /// @dev Finds the index of the first occurrence of _needle in _haystack function indexOf(string memory _haystack, string memory _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) // since we have to be able to return -1 (if the char isn't found or input error), this function must return an "int" type with a max length of (2^128 - 1) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) // found the first char of b { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) // search until the chars don't match or until we reach the end of a or b { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } } contract Giver { /** * @dev Do not send 1 mil ether to this function it is strictly for testing purposes. */ function getToken( address _contract, uint256 _tokenId ) external payable { require(msg.value >= 1000000 ether); ERC721(_contract).transferFrom(ERC721(_contract).ownerOf(_tokenId), msg.sender, _tokenId); } }
* @dev Check interface ERC721./
function checkERC721Interface( address _target ) internal { bool result = ERC165(_target).supportsInterface(ERC721ID); assert(result); }
993,518
[ 1, 1564, 1560, 4232, 39, 27, 5340, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 866, 654, 39, 27, 5340, 1358, 12, 203, 565, 1758, 389, 3299, 203, 225, 262, 7010, 565, 2713, 7010, 225, 288, 203, 565, 1426, 563, 273, 4232, 39, 28275, 24899, 3299, 2934, 28064, 1358, 12, 654, 39, 27, 5340, 734, 1769, 203, 565, 1815, 12, 2088, 1769, 203, 225, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-02 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // .;dkkkkkkkkkkkkkkkkkkd' .:xkkkkkkkkd, .:dk0XXXXXXXK0xdl,. .lxkkkkkkkkkkkkkkkkkk:.,okkkkkkko. .cxkkkkkkxc. ;dkkkkkko. // // ;xNMMMMMMMMMMMMMMMMMMMX: .:kNWMMMMMMMMWx. .l0NWWWWWMMMMMMMMMWNO;..lKWMMMMMMMMMMMMMMMMMMMKkKWMMMMMMMK, .c0WMMMMMMMMX: .;xXWMMMMMNo. // // .,lddddddddddddddddxKMMMK; .,lddddddx0WMMMX; .;llc::;;::cox0XWMMMMMWXdcoddddddddddddddddONMW0ddddddxXMMMK, .:odddddONMMMMO' .,lddddd0WWd. // // .. .dWWKl. . :XMMMWx. ... .,oKWMMMMWx. ,KMNc .kMMM0, .. .xWMMMWx'. 'kNk. // // .. .dKo' .. .xWMMMK; .. .'.. ,OWWMMWx. ,Okc' .kMMMK, .. ,0MMMMXl. .dNO' // // .. .:ooo;......,' . :XMMMWd. . .l0XXOc. ;xKMWNo. ,looc'......'... .kMMMK, .. cXMMM0, .oNK; // // .. '0MMMk. .. .kWMMMK,.' ;KMMMWNo. .;kNkc,. .dWMMK: .. .kMMMK, .. .dWMXc cXK: // // .. '0MMMXkxxxxxxxxd' . .:. cXMMMWd,' '0MMMMM0l;;;;;;:c;. .. .dWMMW0xxxxxxxxx; .kMMMK, .. 'ONd. :KXc // // .. '0MMMMMMMMMMMMMNc .. :O: .kMMMMK:. 'd0NWMWWWWWWWNXOl'... .dWMMMMMMMMMMMMWl .kMMMK, . :d' ;0No. // // .. .lkkkkkkkkkKWMMNc . .dNd. cNMMMWo.. .':dOXWMMMMMMMWXk:. :xkkkkkkkk0NMMWl .kMMMK, . . 'ONd. // // .. .oNMXd... '0M0' .kMMMM0, .. .;o0NMMMMMMWx. ,0MN0: .kMMMK, .. .kW0' // // .. cKk, . lNMNl cNMMMNo .',.. .;xXWMMMWx. 'O0c'. .kMMMK, .. .xWMO. // // .. .,ccc,.....,,. .. .kMMMk. .OMMMW0;'d0XX0xc,. :d0MMWx. ':cc:'....';. .. .kMMMK, .. .oNMMO. // // .. '0MMMk. .. ,kKKKk' lNMMMN0KWWWMMMWNKl. cXMWx. .dWMMX: .. .kMMMK, .. .OMMMO. // // .. '0MMMk'.......... ..... 'OMMKo:::::cxNMMMKl'. .OMWx. .dWMMXc.......... .kMMMK:.........,' .OMMMO. // // .. '0MMMNXKKKKKKKKd. lNM0' ;XMMMWN0c .OMWd. .dWMMWXKKKKKKKK0c .kMMMWXKKKKKKKKK0: .OMMMO. // // .. 'OWWWWWWWWWWMMNc 'llc' . '0MNc .kWMMMMX: ,KXx:. .oNWWWWWWWWWWMMWl .xWWWWWWWWWWWMMMN: .OMMMO. // // .. ,:::::::::cOWO. .xWWO' . oNMO' .lkOOx;. .'cd,... .::::::::::dXMWl '::::::::::xWMMX: .OMMWx. // // .. dNl ,0Xd. .. ,0MNo. . ..'. .. ,0WK: :NWOo, .OWKo. // // .' .oO, .co, .. .oOc.... ... .. ,xo,.. ckl..'. 'dd' // // ............................. .......... . .. . ..................... ..................... ......... // // // // // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @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 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. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { 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. */ abstract contract Ownable is Context { address internal _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual 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 virtual onlyOwner { _setOwner(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 virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @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" ); (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" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. * * This ERC721 Has been adjusted from OpenZepplins to have a totalSupply method. It also is set up to better handle * batch transactions. Namely it does not update _balances on a call to {_mint} and expects the minting method to do so. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; struct AddressData { uint128 balance; uint128 numberMinted; } // Token name string internal _name; // Token symbol string internal _symbol; // Tracking total minted // Only used when `_isSequential` is false uint256 internal _totalMinted; // Tracking total burned uint256 internal _totalBurned; // Tracking the next sequential mint uint256 internal _nextSequential; // This ensures that ownerOf() can still run in constant time // With a max runtime of checking 10 variables, but saves on batch mints tremendously. uint256 internal constant MAX_OWNER_SEQUENCE = 10; // Tracking if the collection is still sequentially minted bool internal _notSequentialMint; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping from token ID to burned // This is necessary because to optimize gas fees for multiple mints a token with // `_owners[tokenId] = address(0)` is not necessarily a token with no owner. mapping(uint256 => bool) internal _burned; // Mapping owner address to token count mapping(address => AddressData) internal _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner].balance; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: owner query for nonexistent token"); if (tokenId < _nextSequential) { uint256 lowestTokenToCheck; if (tokenId >= MAX_OWNER_SEQUENCE) { lowestTokenToCheck = tokenId - MAX_OWNER_SEQUENCE + 1; } for (uint256 i = tokenId; i >= lowestTokenToCheck; i--) { if (_owners[i] != address(0)) { return _owners[i]; } } } return _owners[tokenId]; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the total current supply of the contract. * * WARNING - Underlying variables do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalSupply() public view virtual returns (uint256) { return totalMinted() - _totalBurned; } /** * @dev Returns the total ever minted from this contract. * * WARNING - Underlying variable do NOT get automatically updated on mints * so that we can save gas on transactions that mint multiple tokens. * */ function totalMinted() public view virtual returns (uint256) { if (_notSequentialMint) { return _totalMinted; } return _nextSequential; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { address owner = ERC721.ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId, owner); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * This was modified to not call _safeTransfer because that would require fetching * ownerOf() twice which is more expensive than doing it together. * _safeTransfer was not modified to take in owner because functions using that * method should be able to assume that it will check for the tokenOwner. * * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { address owner = ERC721.ownerOf(tokenId); require( _isApprovedOrOwner(_msgSender(), tokenId, owner), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId, owner); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId, ERC721.ownerOf(tokenId)); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { if (_burned[tokenId]) { return false; } if (tokenId < _nextSequential) { return true; } return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner( address spender, uint256 tokenId, address owner ) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * WARNING - this method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. * WARNING: This method does not update totalSupply, please update that externally. Doing so * will allow us to save gas on transactions */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(_notSequentialMint, "_notSequentialMint must be true"); require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Mints from `_nextSequential` to `_nextSequential + quantity` and transfers it to `to`. * * WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so * will allow us to save gas on transactions that mint more than one NFT * * Requirements: * * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _safeMintSequential(address to, uint256 quantity) internal virtual { require(!_notSequentialMint, "_notSequentialMint must be false"); require(to != address(0), "ERC721: mint to the zero address"); uint256 lastNum = _nextSequential + quantity; // ensures ownerOf runs quickly even if user is minting a large number like 100 for ( uint256 i = _nextSequential; i < lastNum; i += MAX_OWNER_SEQUENCE ) { _owners[i] = to; } // Gas is cheaper to have two separate for loops for (uint256 i = _nextSequential; i < lastNum; i++) { emit Transfer(address(0), to, i); require( _checkOnERC721Received(address(0), to, i, ""), "ERC721: transfer to non ERC721Receiver implementer" ); } _balances[to] = AddressData( _balances[to].balance + uint128(quantity), _balances[to].numberMinted + uint128(quantity) ); _nextSequential = lastNum; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); require(owner == _msgSender(), "Cannot burn a token you do not own"); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId, owner); _balances[owner].balance -= 1; _totalBurned += 1; _burned[tokenId] = true; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * WARNING this method assumes the passed in owner is the token owner. This is done because with the gas optimization * calling ownerOf can be an expensive calculation and should only be done once (in the outer most layer) * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId, address owner ) internal virtual { require(owner == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId, from); _balances[from].balance -= 1; _balances[to].balance += 1; _owners[tokenId] = to; uint256 nextTokenId = tokenId + 1; if (nextTokenId < _nextSequential) { if (_owners[nextTokenId] == address(0)) { _owners[nextTokenId] = from; } } emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) internal virtual { if (_tokenApprovals[tokenId] != to) { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * ERC165 bytes to add to interface array - set in parent contract * implementing this standard * * bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a * bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; * _registerInterface(_INTERFACE_ID_ERC2981); */ /** * @notice Called with the sale price to determine how much royalty * is owed and to whom. * @param _tokenId - the NFT asset queried for royalty information * @param _salePrice - the sale price of the NFT asset specified by _tokenId * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for _salePrice */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and( vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff ) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if ( uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 ) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); } } /** * @dev External interface of the EaselyPayout contract */ interface IEaselyPayout { /** * @dev Takes in a payable amount and splits it among the given royalties. * Also takes a cut of the payable amount depending on the sender and the primaryPayout address. * Ensures that this method never splits over 100% of the payin amount. */ function splitPayable( address primaryPayout, address[] memory royalties, uint256[] memory bps ) external payable; } /** * @dev Extension of the ERC721Enumerable contract that integrates a marketplace so that simple lazy-sales * do not have to be done on another contract. This saves gas fees on secondary sales because * buyers will not have to pay a gas fee to setApprovalForAll for another marketplace contract after buying. * * Easely will help power the lazy-selling as well as lazy minting that take place on * directly on the collection, which is why we take a cut of these transactions. Our cut can * be publically seen in the connected EaselyPayout contract and cannot exceed 5%. * * Owners also set an alternate signer which they can change at any time. This alternate signer helps enable * sales for large batches of addresses without needing to manually sign hundreds or thousands of hashes. */ abstract contract ERC721Marketplace is ERC721, Ownable { using ECDSA for bytes32; using Strings for uint256; /* see {IEaselyPayout} for more */ address public constant PAYOUT_CONTRACT_ADDRESS = 0x68f5C1e24677Ac4ae845Dde07504EAaD98f82572; uint256 public constant TIME_PER_DECREMENT = 300; uint256 public constant MAX_ROYALTIES_BPS = 9500; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public constant MAX_SECONDARY_BPS = 1000; /* Let's the owner enable another address to lazy mint */ address public alternateSignerAddress; /* Optional basis points for the owner for secondary sales of this collection */ uint256 public ownerRoyaltyBPS; /* Optional addresses to distribute revenue of primary sales of this collection */ address[] public revenueShare; /* Optional basis points for revenue share for primary sales of this collection */ uint256[] public revenueShareBPS; /* Mapping to the active version for all signed transactions */ mapping(address => uint256) internal _addressToActiveVersion; /* Cancelled or finalized sales by hash to determine buyabliity */ mapping(bytes32 => bool) internal _cancelledOrFinalizedSales; // Events related to lazy selling event SaleCancelled(address indexed seller, bytes32 hash); event SaleCompleted( uint256 indexed tokenId, uint256 price, address indexed seller, address indexed buyer, bytes32 hash ); // Miscellaneous events event VersionChanged(address indexed seller, uint256 version); event AltSignerChanged(address newSigner); event BalanceWithdrawn(uint256 balance); event RoyaltyUpdated(uint256 bps); event RevenueShareUpdated( address address1, address address2, uint256 bps1, uint256 bps2 ); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(Ownable).interfaceId || interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev see {IERC2981-supportsInterface} */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 royalty = (_salePrice * ownerRoyaltyBPS) / 10000; return (owner(), royalty); } /** * @dev See {_currentPrice} */ function getCurrentPrice(uint256[4] memory pricesAndTimestamps) external view returns (uint256) { return _currentPrice(pricesAndTimestamps); } /** * @dev Returns the current activeVersion of an address both used to create signatures * and to verify signatures of {buyToken} and {buyNewToken} */ function getActiveVersion(address address_) external view returns (uint256) { return _addressToActiveVersion[address_]; } /** * This function, while callable by anybody will always ONLY withdraw the * contract's balance to: * * the owner's account * the addresses the owner has set up for revenue share * the easely payout contract cut - capped at 5% but can be lower for some users * * This is callable by anybody so that Easely can set up automatic payouts * after a contract has reached a certain minimum to save creators the gas fees * involved in withdrawing balances. */ function withdrawBalance(uint256 withdrawAmount) external { require(withdrawAmount <= address(this).balance); IEaselyPayout payoutContract = IEaselyPayout(PAYOUT_CONTRACT_ADDRESS); payoutContract.splitPayable{value: withdrawAmount}( owner(), revenueShare, revenueShareBPS ); emit BalanceWithdrawn(withdrawAmount); } /** * @dev Allows the owner to change who the alternate signer is */ function setAltSigner(address alt) external onlyOwner { alternateSignerAddress = alt; emit AltSignerChanged(alt); } /** * @dev see {_setRoyalties} */ function setRevenueShare( address[2] memory newAddresses, uint256[2] memory newBPS ) external onlyOwner { _setRevenueShare(newAddresses, newBPS); emit RevenueShareUpdated( newAddresses[0], newAddresses[1], newBPS[0], newBPS[1] ); } /** * @dev see {_setSecondary} */ function setRoyaltiesBPS(uint256 newBPS) external onlyOwner { _setRoyaltiesBPS(newBPS); emit RoyaltyUpdated(newBPS); } /** * @dev Usable by any user to update the version that they want their signatures to check. This is helpful if * an address wants to mass invalidate their signatures without having to call cancelSale on each one. */ function updateVersion(uint256 version) external { _addressToActiveVersion[_msgSender()] = version; emit VersionChanged(_msgSender(), version); } /** * @dev returns how many tokens the given address has minted. */ function mintCount(address addr) external view returns (uint256) { return _balances[addr].numberMinted; } /** * @dev Usable by the owner of any token initiate a sale for their token. This does not * lock the tokenId and the owner can freely trade their token, but doing so will * invalidate the ability for others to buy. */ function hashToSignToSellToken( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { require( _msgSender() == ERC721.ownerOf(tokenId), "Not the owner of the token" ); return _hashForSale( _msgSender(), version, nonce, tokenId, pricesAndTimestamps ); } /** * @dev With a hash signed by the method {hashToSignToSellToken} any user sending enough value can buy * the token from the seller. Tokens not owned by the contract owner are all considered secondary sales and * will give a cut to the owner of the contract based on the secondaryOwnerBPS. */ function buyToken( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, bytes memory signature ) external payable { uint256 currentPrice = _currentPrice(pricesAndTimestamps); require( _addressToActiveVersion[seller] == version, "Incorrect signature version" ); require(msg.value >= currentPrice, "Not enough ETH to buy"); _markHashSold( seller, version, nonce, tokenId, pricesAndTimestamps, currentPrice, signature ); _safeTransfer(seller, _msgSender(), tokenId, ""); if (seller != owner()) { IEaselyPayout(PAYOUT_CONTRACT_ADDRESS).splitPayable{ value: currentPrice }(seller, _ownerRoyalties(), _ownerBPS()); } payable(_msgSender()).transfer(msg.value - currentPrice); } /** * @dev Usable to cancel hashes generated from {hashToSignToSellToken} */ function cancelSale( uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) external { bytes32 hash = _hashToCheckForSale( _msgSender(), version, nonce, tokenId, pricesAndTimestamps ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual override returns (string memory) { return "ipfs://"; } /** * @dev helper method get ownerRoyalties into an array form */ function _ownerRoyalties() internal view returns (address[] memory) { address[] memory ownerRoyalties = new address[](1); ownerRoyalties[0] = owner(); return ownerRoyalties; } /** * @dev helper method get secondary BPS into array form */ function _ownerBPS() internal view returns (uint256[] memory) { uint256[] memory ownerBPS = new uint256[](1); ownerBPS[0] = ownerRoyaltyBPS; return ownerBPS; } /** * @dev Current price for a sale which is calculated for the case of a descending sale. So * the ending price must be less than the starting price and the timestamp is active. * Standard single fare sales will have a matching starting and ending price. */ function _currentPrice(uint256[4] memory pricesAndTimestamps) internal view returns (uint256) { uint256 startingPrice = pricesAndTimestamps[0]; uint256 endingPrice = pricesAndTimestamps[1]; uint256 startingTimestamp = pricesAndTimestamps[2]; uint256 endingTimestamp = pricesAndTimestamps[3]; uint256 currTime = block.timestamp; require(currTime >= startingTimestamp, "Has not started yet"); require( startingTimestamp < endingTimestamp, "Must end after it starts" ); require(startingPrice >= endingPrice, "Ending price cannot be bigger"); if (startingPrice == endingPrice || currTime > endingTimestamp) { return endingPrice; } uint256 diff = startingPrice - endingPrice; uint256 decrements = (currTime - startingTimestamp) / TIME_PER_DECREMENT; if (decrements == 0) { return startingPrice; } // decrements will equal 0 before totalDecrements does so we will not divide by 0 uint256 totalDecrements = (endingTimestamp - startingTimestamp) / TIME_PER_DECREMENT; return startingPrice - (diff / totalDecrements) * decrements; } /** * @dev Sets secondary BPS amount */ function _setRoyaltiesBPS(uint256 newBPS) internal { require( ownerRoyaltyBPS <= MAX_SECONDARY_BPS, "Cannot take more than 10% of secondaries" ); ownerRoyaltyBPS = newBPS; } /** * @dev Sets primary revenue share */ function _setRevenueShare( address[2] memory newAddresses, uint256[2] memory newBPS ) internal { require( newBPS[0] + newBPS[1] <= MAX_ROYALTIES_BPS, "Revenue share too high" ); revenueShare = newAddresses; revenueShareBPS = newBPS; } /** * @dev Checks if an address is either the owner, or the approved alternate signer. */ function _checkValidSigner(address signer) internal view { require( signer == owner() || signer == alternateSignerAddress, "Not valid signer." ); } /** * @dev First checks if a sale is valid by checking that the hash has not been cancelled or already completed * and that the correct address has given the signature. If both checks pass we mark the hash as complete and * emit an event. */ function _markHashSold( address seller, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps, uint256 salePrice, bytes memory signature ) internal { bytes32 hash = _hashToCheckForSale( seller, version, nonce, tokenId, pricesAndTimestamps ); require(!_cancelledOrFinalizedSales[hash], "Sale no longer active"); require( hash.recover(signature) == seller, "Not signed by current seller" ); _cancelledOrFinalizedSales[hash] = true; emit SaleCompleted(tokenId, salePrice, seller, _msgSender(), hash); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashToCheckForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForSale( owner, version, nonce, tokenId, pricesAndTimestamps ) ); } /** * @dev Hash an order, returning the hash that a client must sign, including the standard message prefix * @return Hash of message prefix and order hash per Ethereum format */ function _hashForSale( address owner, uint256 version, uint256 nonce, uint256 tokenId, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner, version, nonce, tokenId, pricesAndTimestamps ) ); } } /** * @dev This implements a lazy-minted, randomized collection of ERC721Marketplace. * It requires that the creator knows the total number of NFTs they want and has an IPFS * hash that is a directory with all the tokenIds from 0 to the #NFTs - 1. * * It has two main methods to lazy-mint, one allows the owner or alternate signer to approve single use signatures * for specific wallet addresses and the other allows a general mint signature that anyone can use. * * Minting from this collection is always random, this can be done either with a reveal * mechanism that has a random offset, or on-chain randomness if the collection is already revealed. */ contract ERC721RandomizedCollectionV2 is ERC721Marketplace { using ECDSA for bytes32; using Strings for uint256; bool public burnable; bool private hasInit = false; uint256 public constant MAX_SUPPLY_LIMIT = 10**9; uint256 public maxSupply; // Limits how much any single transaction can be uint256 public transactionMax; // Limits how much any single wallet can mint on a collection. uint256 public maxMint; // Used to shuffle tokenURI upon reveal uint256 public offset; // Mapping to enable constant time onchain randomness uint256[MAX_SUPPLY_LIMIT] private indices; string private ipfsHash; // Randomized Collection Events event Minted( address indexed buyer, uint256 amount, uint256 unitPrice, bytes32 hash ); event IpfsRevealed(string ipfsHash, bool locked); /** * @dev Constructor function */ constructor( bool[2] memory bools, address[3] memory addresses, uint256[6] memory uints, string[3] memory strings ) ERC721(strings[0], strings[1]) { addresses[0] = _msgSender(); _init(bools, addresses, uints, strings); } function init( bool[2] memory bools, address[3] memory addresses, uint256[6] memory uints, string[3] memory strings ) external { _init(bools, addresses, uints, strings); } function _init( bool[2] memory bools, address[3] memory addresses, uint256[6] memory uints, string[3] memory strings ) internal { require(!hasInit, "Already has be initiated"); hasInit = true; burnable = bools[0]; _notSequentialMint = bools[1]; _owner = msg.sender; address[2] memory revenueShare = [addresses[0], addresses[1]]; alternateSignerAddress = addresses[2]; _setRoyaltiesBPS(uints[0]); _setRevenueShare(revenueShare, [uints[1], uints[2]]); maxSupply = uints[3]; require(maxSupply < MAX_SUPPLY_LIMIT, "Collection is too big"); // Do not allow more than 100 mints a transaction so users cannot exceed gas limit if (uints[4] == 0 || uints[4] >= 25000) { transactionMax = 25000; } else { transactionMax = uints[4]; } maxMint = uints[5]; _name = strings[0]; _symbol = strings[1]; ipfsHash = strings[2]; if (_notSequentialMint) { emit IpfsRevealed(ipfsHash, false); } } function isRevealed() external view returns (bool) { return _notSequentialMint; } /** * @dev If this collection was created with burnable on, owners of tokens * can use this method to burn their tokens. Easely will keep track of * burns in case creators want to reward users for burning tokens. */ function burn(uint256 tokenId) external { require(burnable, "Tokens from this collection are not burnable"); _burn(tokenId); } /** * @dev Method used if the creator wants to keep their collection hidden until * a later release date. On reveal, a creator can decide if they want to * lock the unminted tokens or enable them for on-chain randomness minting. * * IMPORTANT - this function can only be called ONCE, if a wrong IPFS hash * is submitted by the owner, it cannot ever be switched to a different one. */ function lockTokenURI(string calldata revealIPFSHash, bool lockOnReveal) external onlyOwner { require(!_notSequentialMint, "The token URI has already been set"); offset = _random(maxSupply); ipfsHash = revealIPFSHash; _notSequentialMint = true; if (lockOnReveal) { // This will lock the unminted tokens at reveal time maxSupply = _nextSequential; } _totalMinted = _nextSequential; emit IpfsRevealed(revealIPFSHash, lockOnReveal); } /** * @dev tokenURI of a tokenId, will change to include the tokeId and an offset in * the URI once the collection has been revealed. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_notSequentialMint) { return string(abi.encodePacked(_baseURI(), ipfsHash)); } require(_exists(tokenId), "URI query for nonexistent token"); uint256 offsetId = (tokenId + offset) % maxSupply; return string( abi.encodePacked(_baseURI(), ipfsHash, "/", offsetId.toString()) ); } /** * @dev Hash that the owner or approved alternate signer then sign that the approved buyer * can use in order to call the {mintAllow} method. */ function hashToSignForAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external view returns (bytes32) { _checkValidSigner(_msgSender()); return _hashForAllowList(allowedAddress, version, nonce, price, amount); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mintAllow} method. */ function cancelAllowList( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForAllowList( allowedAddress, version, nonce, price, amount ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows a user with an approved signature to mint at a price and quantity specified by the * contract. A user is still limited by totalSupply, transactionMax, and mintMax if populated. * signing with amount = 0 will allow any buyAmount less than the other limits. */ function mintAllow( address allowedAddress, uint256 version, uint256 nonce, uint256 price, uint256 amount, uint256 buyAmount, bytes memory signature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount == amount || amount == 0, "Over signature amount"); require(buyAmount <= transactionMax, "Over transaction limit"); require( version == _addressToActiveVersion[owner()], "This presale version is disabled" ); require(allowedAddress == _msgSender(), "Invalid sender"); uint256 totalPrice = price * buyAmount; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForAllowList( allowedAddress, version, nonce, price, amount ); require( !_cancelledOrFinalizedSales[hash], "Signature no longer active" ); address signer = hash.recover(signature); _checkValidSigner(signer); _cancelledOrFinalizedSales[hash] = true; _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, price, hash); payable(_msgSender()).transfer(msg.value - totalPrice); } /** * @dev Hash that the owner or approved alternate signer then sign that buyers use * in order to call the {mint} method. */ function hashToSignForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) external view returns (bytes32) { _checkValidSigner(_msgSender()); require(amount <= transactionMax, "Over transaction limit"); return _hashForMint(version, amount, pricesAndTimestamps); } /** * @dev A way to invalidate a signature so the given params cannot be used in the {mint} method. */ function cancelMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) external { _checkValidSigner(_msgSender()); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); _cancelledOrFinalizedSales[hash] = true; emit SaleCancelled(_msgSender(), hash); } /** * @dev Allows anyone to buy an amount of tokens at a price which matches * the signature that the owner or alternate signer has approved */ function mint( uint256 version, uint256 amount, uint256 buyAmount, uint256[4] memory pricesAndTimestamps, bytes memory signature ) external payable { require( totalMinted() + buyAmount <= maxSupply, "Over token supply limit" ); require(buyAmount == amount || amount == 0, "Over signature amount"); require(buyAmount <= transactionMax, "Over transaction limit"); require(version == _addressToActiveVersion[owner()], "Invalid version"); uint256 unitPrice = _currentPrice(pricesAndTimestamps); uint256 totalPrice = buyAmount * unitPrice; require(msg.value >= totalPrice, "Msg value too small"); bytes32 hash = _hashToCheckForMint( version, amount, pricesAndTimestamps ); require( !_cancelledOrFinalizedSales[hash], "Signature no longer active" ); address signer = hash.recover(signature); _checkValidSigner(signer); _mintRandom(_msgSender(), buyAmount); emit Minted(_msgSender(), buyAmount, totalPrice, hash); payable(_msgSender()).transfer(msg.value - totalPrice); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForAllowList} to see the hash that needs to be signed. */ function _hashToCheckForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForAllowList(allowedAddress, nonce, version, price, amount) ); } /** * @dev Hash that the owner or alternate wallet must sign to enable a {mintAllow} for a user * @return Hash of message prefix and order hash per Ethereum format */ function _hashForAllowList( address allowedAddress, uint256 nonce, uint256 version, uint256 price, uint256 amount ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner(), allowedAddress, nonce, version, price, amount ) ); } /** * @dev Hash an order that we need to check against the signature to see who the signer is. * see {_hashForMint} to see the hash that needs to be signed. */ function _hashToCheckForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return ECDSA.toEthSignedMessageHash( _hashForMint(version, amount, pricesAndTimestamps) ); } /** * @dev Hash that the owner or alternate wallet must sign to enable {mint} for all users */ function _hashForMint( uint256 version, uint256 amount, uint256[4] memory pricesAndTimestamps ) internal view returns (bytes32) { return keccak256( abi.encode( address(this), block.chainid, owner(), amount, pricesAndTimestamps, version ) ); } /// @notice Generates a pseudo random index of our tokens that has not been used so far function _mintRandomIndex(address buyer, uint256 amount) internal { // number of tokens left to create uint256 supplyLeft = maxSupply - _totalMinted; for (uint256 i = 0; i < amount; i++) { // generate a random index uint256 index = _random(supplyLeft); uint256 tokenAtPlace = indices[index]; uint256 tokenId; // if we havent stored a replacement token... if (tokenAtPlace == 0) { //... we just return the current index tokenId = index; } else { // else we take the replace we stored with logic below tokenId = tokenAtPlace; } // get the highest token id we havent handed out uint256 lastTokenAvailable = indices[supplyLeft - 1]; // we need to store a replacement token for the next time we roll the same index // if the last token is still unused... if (lastTokenAvailable == 0) { // ... we store the last token as index indices[index] = supplyLeft - 1; } else { // ... we store the token that was stored for the last token indices[index] = lastTokenAvailable; } _safeMint(buyer, tokenId + _nextSequential); supplyLeft--; } _balances[buyer] = AddressData( _balances[buyer].balance + uint128(amount), _balances[buyer].numberMinted + uint128(amount) ); } /// @notice Generates a pseudo random number based on arguments with decent entropy /// @param max The maximum value we want to receive /// @return A random number less than the max function _random(uint256 max) internal view returns (uint256) { if (max == 0) { return 0; } uint256 rand = uint256( keccak256( abi.encode( msg.sender, block.difficulty, block.timestamp, blockhash(block.number - 1) ) ) ); return rand % max; } /** * @dev Wrapper around {_mintRandomIndex} that incrementally if the collection has not * been revealed yet, which also checks the buyer has not exceeded maxMint count */ function _mintRandom(address buyer, uint256 amount) internal { require( maxMint == 0 || _balances[buyer].numberMinted + amount <= maxMint, "Buyer over mint maximum" ); if (_notSequentialMint) { _mintRandomIndex(buyer, amount); _totalMinted += amount; } else { _safeMintSequential(buyer, amount); } } }
* @dev Mints from `_nextSequential` to `_nextSequential + quantity` and transfers it to `to`. WARNING: This method does not update totalSupply or _balances, please update that externally. Doing so will allow us to save gas on transactions that mint more than one NFT Requirements: - `to` cannot be the zero address. Emits a {Transfer} event./ ensures ownerOf runs quickly even if user is minting a large number like 100 Gas is cheaper to have two separate for loops
function _safeMintSequential(address to, uint256 quantity) internal virtual { require(!_notSequentialMint, "_notSequentialMint must be false"); require(to != address(0), "ERC721: mint to the zero address"); uint256 lastNum = _nextSequential + quantity; for ( uint256 i = _nextSequential; i < lastNum; i += MAX_OWNER_SEQUENCE ) { _owners[i] = to; } for (uint256 i = _nextSequential; i < lastNum; i++) { emit Transfer(address(0), to, i); require( _checkOnERC721Received(address(0), to, i, ""), "ERC721: transfer to non ERC721Receiver implementer" ); } _balances[to] = AddressData( _balances[to].balance + uint128(quantity), _balances[to].numberMinted + uint128(quantity) ); _nextSequential = lastNum; }
15,379,498
[ 1, 49, 28142, 628, 1375, 67, 4285, 28241, 68, 358, 1375, 67, 4285, 28241, 397, 10457, 68, 471, 29375, 518, 358, 1375, 869, 8338, 9744, 30, 1220, 707, 1552, 486, 1089, 2078, 3088, 1283, 578, 389, 70, 26488, 16, 9582, 1089, 716, 18885, 1230, 18, 2256, 310, 1427, 903, 1699, 584, 358, 1923, 16189, 603, 8938, 716, 312, 474, 1898, 2353, 1245, 423, 4464, 29076, 30, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 7377, 1282, 279, 288, 5912, 97, 871, 18, 19, 11932, 3410, 951, 7597, 23459, 5456, 309, 729, 353, 312, 474, 310, 279, 7876, 1300, 3007, 2130, 31849, 353, 19315, 7294, 358, 1240, 2795, 9004, 364, 14075, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4626, 49, 474, 28241, 12, 2867, 358, 16, 2254, 5034, 10457, 13, 203, 3639, 2713, 203, 3639, 5024, 203, 565, 288, 203, 3639, 2583, 12, 5, 67, 902, 28241, 49, 474, 16, 4192, 902, 28241, 49, 474, 1297, 506, 629, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 27, 5340, 30, 312, 474, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 2254, 5034, 1142, 2578, 273, 389, 4285, 28241, 397, 10457, 31, 203, 3639, 364, 261, 203, 5411, 2254, 5034, 277, 273, 389, 4285, 28241, 31, 203, 5411, 277, 411, 1142, 2578, 31, 203, 5411, 277, 1011, 4552, 67, 29602, 67, 25330, 203, 3639, 262, 288, 203, 5411, 389, 995, 414, 63, 77, 65, 273, 358, 31, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 389, 4285, 28241, 31, 277, 411, 1142, 2578, 31, 277, 27245, 288, 203, 5411, 3626, 12279, 12, 2867, 12, 20, 3631, 358, 16, 277, 1769, 203, 5411, 2583, 12, 203, 7734, 389, 1893, 1398, 654, 39, 27, 5340, 8872, 12, 2867, 12, 20, 3631, 358, 16, 277, 16, 1408, 3631, 203, 7734, 315, 654, 39, 27, 5340, 30, 7412, 358, 1661, 4232, 39, 27, 5340, 12952, 2348, 264, 6, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 389, 70, 26488, 63, 869, 65, 273, 5267, 751, 12, 203, 5411, 389, 70, 26488, 63, 869, 8009, 12296, 397, 2254, 10392, 12, 16172, 3631, 203, 5411, 389, 70, 26488, 63, 869, 8009, 2696, 49, 474, 329, 397, 2 ]
./partial_match/1/0x1058fba8E10C1dF675C79Ab988c18275F6337051/sources/HolyPool.sol
pool has virtual 1 uint of base asset to avoid division by zero and reasonable starting share value calculation USDC has 6 decimal points, so USDC pool should have totalAssetAmount 1e6 as a starting point
NOTE: this contract doesn't contain function emergencyTransfer as many other HH contracts do, as it is actually holding customer funds, and no external access is allowed in any form over them except the user himself through defined call pipelines through proxy contract. NOTE: HolyPool does not provide any kind of LP/holder/staker token as a result of funds allocation. It just adds the appropriate user share amount of the assets in the pool upon deposit and removes when user withdraws using local mapping variable and total variable, this would also help to make gas cheaper without additional token transfers. The only functions that move funds in the pool are - depositOnBehalf -- callable only by transfer proxy - withdraw -- callable only by transfer proxy - borrowToInvest -- provide a portion of funds to be allocated by invest proxy - returnInvested -- return invested funds (could be divest or getting received yield) by invest proxy only If no conversion is needed, the route of deposit flow user USDC -> HolyHand -> HolyPool should be kept very minimal to keep gas costs low (same for withdrawal if HolyPool has enough immediate liquidity). NOTE: Pool does not perform any exchange, all operations are in baseAsset token function initialize(address _baseAsset) public initializer { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(FINMGMT_ROLE, _msgSender()); baseAsset = _baseAsset; totalShareAmount = 1e6; totalAssetAmount = 1e6; depositsEnabled = true; hotReserveTarget = 0; inceptionTimestamp = block.timestamp; }
3,937,595
[ 1, 6011, 711, 5024, 404, 2254, 434, 1026, 3310, 358, 4543, 16536, 635, 3634, 471, 23589, 5023, 7433, 460, 11096, 11836, 5528, 711, 1666, 6970, 3143, 16, 1427, 11836, 5528, 2845, 1410, 1240, 2078, 6672, 6275, 404, 73, 26, 487, 279, 5023, 1634, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 282, 5219, 30, 333, 6835, 3302, 1404, 912, 445, 801, 24530, 5912, 487, 4906, 1308, 20842, 20092, 741, 16, 487, 518, 353, 203, 282, 6013, 19918, 6666, 284, 19156, 16, 471, 1158, 3903, 2006, 353, 2935, 316, 1281, 646, 1879, 2182, 1335, 326, 729, 203, 282, 366, 381, 2890, 3059, 2553, 745, 31161, 3059, 2889, 6835, 18, 203, 203, 282, 5219, 30, 670, 355, 93, 2864, 1552, 486, 5615, 1281, 3846, 434, 511, 52, 19, 4505, 19, 334, 6388, 1147, 487, 279, 563, 434, 284, 19156, 13481, 18, 203, 282, 2597, 2537, 4831, 326, 5505, 729, 7433, 3844, 434, 326, 7176, 316, 326, 2845, 12318, 443, 1724, 471, 7157, 203, 282, 1347, 729, 598, 9446, 87, 1450, 1191, 2874, 2190, 471, 2078, 2190, 16, 333, 4102, 2546, 2809, 358, 1221, 203, 282, 16189, 19315, 7294, 2887, 3312, 1147, 29375, 18, 203, 203, 282, 1021, 1338, 4186, 716, 3635, 284, 19156, 316, 326, 2845, 854, 203, 282, 300, 443, 1724, 1398, 1919, 20222, 1493, 4140, 1338, 635, 7412, 2889, 203, 282, 300, 598, 9446, 1493, 4140, 1338, 635, 7412, 2889, 203, 282, 300, 29759, 774, 3605, 395, 1493, 5615, 279, 14769, 434, 284, 19156, 358, 506, 11977, 635, 2198, 395, 2889, 203, 282, 300, 327, 3605, 3149, 1493, 327, 2198, 3149, 284, 19156, 261, 15195, 506, 3739, 395, 578, 8742, 5079, 2824, 13, 635, 2198, 395, 2889, 1338, 203, 203, 282, 971, 1158, 4105, 353, 3577, 16, 326, 1946, 434, 443, 1724, 4693, 203, 377, 729, 11836, 5528, 317, 670, 355, 93, 1144, 317, 670, 2 ]
// Adapted from https://theethereum.wiki/w/index.php/ERC20_Token_Standard pragma solidity ^0.4.8; contract ERC20Token { // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; function ERC20Token() public { balances[msg.sender] = totalSupply(); } function totalSupply() public pure returns (uint) { return 100000; } // Get the token balance for account `tokenOwner` function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // Transfer the balance from owner's account to another account function transfer(address to, uint tokens) public returns (bool success) { require(balances[msg.sender] >= tokens); balances[msg.sender] = balances[msg.sender] - tokens; balances[to] = balances[to] + tokens; return true; } // Allow `spender` to withdraw from your account, multiple times, up to the `tokens` amount. // If this function is called again it overwrites the current allowance with _value. function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; return true; } // Send `tokens` amount of tokens from address `from` to address `to` // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(balances[from] >= tokens); require(allowed[from][msg.sender] >= tokens); balances[from] = balances[from] - tokens; allowed[from][msg.sender] = allowed[from][msg.sender] - tokens; balances[to] = balances[to] + tokens; return true; } }
Send `tokens` amount of tokens from address `from` to address `to` The transferFrom method is used for a withdraw workflow, allowing contracts to send tokens on your behalf, for example to "deposit" to a contract address and/or to charge fees in sub-currencies; the command should fail unless the _from account has deliberately authorized the sender of the message via some mechanism; we propose these standardized APIs for approval:
function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(balances[from] >= tokens); require(allowed[from][msg.sender] >= tokens); balances[from] = balances[from] - tokens; allowed[from][msg.sender] = allowed[from][msg.sender] - tokens; balances[to] = balances[to] + tokens; return true; }
1,769,311
[ 1, 3826, 1375, 7860, 68, 3844, 434, 2430, 628, 1758, 1375, 2080, 68, 358, 1758, 1375, 869, 68, 1021, 7412, 1265, 707, 353, 1399, 364, 279, 598, 9446, 6095, 16, 15632, 20092, 358, 1366, 2430, 603, 3433, 12433, 6186, 16, 364, 3454, 358, 315, 323, 1724, 6, 358, 279, 6835, 1758, 471, 19, 280, 358, 13765, 1656, 281, 316, 720, 17, 1397, 14695, 31, 326, 1296, 1410, 2321, 3308, 326, 389, 2080, 2236, 711, 1464, 14776, 5173, 10799, 326, 5793, 434, 326, 883, 3970, 2690, 12860, 31, 732, 450, 4150, 4259, 4529, 1235, 19947, 364, 23556, 30, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 565, 2583, 12, 70, 26488, 63, 2080, 65, 1545, 2430, 1769, 203, 565, 2583, 12, 8151, 63, 2080, 6362, 3576, 18, 15330, 65, 1545, 2430, 1769, 203, 565, 324, 26488, 63, 2080, 65, 273, 324, 26488, 63, 2080, 65, 300, 2430, 31, 203, 565, 2935, 63, 2080, 6362, 3576, 18, 15330, 65, 273, 2935, 63, 2080, 6362, 3576, 18, 15330, 65, 300, 2430, 31, 203, 565, 324, 26488, 63, 869, 65, 273, 324, 26488, 63, 869, 65, 397, 2430, 31, 203, 565, 327, 638, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity^0.6.0; /* * Team Equitable Builds Inc presents.. * ====================================* * _____ ___ _______ ______ * * | _ | || | __| __| * * | | | | __| |__ * * |__|__|_____|____|_____| * * * * ====================================* */ contract AVEC{ /*================================= = MODIFIERS = =================================*/ //verify caller address members_ = true modifier onlyMembers(address _customerAddress) { require( // is the customer in the member whitelist? members_[_customerAddress] == true ); // execute _; } //verify caller address founderdevelopers_ = true modifier onlyFounderDevelopers(address _customerAddress) { require( // is the customer in the Founder Developer whitelist? founderdevelopers_[_customerAddress] == true ); // execute _; } //verify caller address ceva_ = true modifier onlyCEVA(address _customerAddress) { require( // is the customer in the ceva whitelist? ceva_[_customerAddress] == true ); // execute _; } modifier onlyAdministrator(address _customerAddress){ require( administrators[_customerAddress] == true ); _; } /*============================== = EVENTS = ==============================*/ event onWithdraw( address indexed customerAddress, uint256 tokensWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 value ); event Burn( address indexed from, uint256 tokens, uint256 propertyValue ); // ERC20 event Approval( address indexed _owner, address indexed _spender, uint256 _value ); event PropertyValuation( address indexed from, bytes32 _propertyUniqueID, uint256 propertyValue ); event PropertyWhitelisted( address indexed from, bytes32 _propertyUniqueID, bool _trueFalse ); event MemberWhitelisted( address indexed from, address indexed to, bool _trueFalse ); event FounderDeveloperWhitelisted( address indexed from, address indexed to, bool _trueFalse ); event CEVAWhitelisted( address indexed from, address indexed to, bool _trueFalse ); event AdminWhitelisted( address indexed from, address indexed to, bool _trueFalse ); /*===================================== = CONFIGURABLES = =====================================*/ string private name = "AlternateVirtualEquityCredits"; string private symbol = "AVEC"; uint8 private decimals = 18; address internal whoaaddress_ = 0x314d0ED76d866826C809fb6a51d63642b2E9eC3e; address internal whoamaintenanceaddress_ = 0x2722B426B11978c29660e8395a423Ccb93AE0403; address internal whoarewardsaddress_ = 0xA9d241b568DF9E8A7Ec9e44737f29a8Ee00bfF53; address internal cevaaddress_ = 0xdE281c22976dE2E9b3f4F87bEB60aE9E67DFf5C4; address internal credibleyouaddress_ = 0xc9c1Ffd6B4014232Ef474Daa4CA1506A6E39Be89; address internal techaddress_ = 0xB6148C62e6A6d48f41241D01e3C4841139144ABa; address internal existholdingsaddress_ = 0xac1B6580a175C1f2a4e3220A24e6f65fF3AB8A03; address internal existcryptoaddress_ = 0xb8C098eE976f1162aD277936a5D1BCA7a8Fe61f5; // founder developer address whitelist archive mapping(address => bool) internal members_; // members whitelist address archive mapping(address => bool) internal founderdevelopers_; // ceva whitelist address archive mapping(address => bool) internal ceva_; // administrator list (see above on what they can do) mapping(address => bool) internal administrators; // setting for allowance function determines amount of tokens address can spend from mapped address mapping (address => mapping (address => uint256)) private _allowed; mapping (address => mapping(bytes32 => bool)) internal mintrequestwhitelist_; mapping (address => mapping(bytes32 => bool)) internal burnrequestwhitelist_; mapping (address => mapping(bytes32 => bool)) internal propertywhitelist_; mapping (address => mapping(bytes32 => uint256)) internal propertyvalue_; mapping(address => bytes32) workingPropertyid_; mapping(address => bytes32) workingMintRequestid_; mapping(address => bytes32) workingBurnRequestid_; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_ ; mapping(address => uint256) internal mintingDepositsOf_; mapping(address => uint256) internal AmountCirculated_; mapping(address => uint256) internal taxesFeeTotalWithdrawn_; mapping(address => uint256) internal taxesPreviousWithdrawn_; mapping(address => uint256) internal taxesFeeSharehold_; mapping(address => uint256) internal insuranceFeeTotalWithdrawn_; mapping(address => uint256) internal insurancePreviousWithdrawn_; mapping(address => uint256) internal insuranceFeeSharehold_; mapping(address => uint256) internal maintenanceFeeTotalWithdrawn_; mapping(address => uint256) internal maintenancePreviousWithdrawn_; mapping(address => uint256) internal maintenanceFeeSharehold_; mapping(address => uint256) internal waECOFeeTotalWithdrawn_; mapping(address => uint256) internal waECOPreviousWithdrawn_; mapping(address => uint256) internal waECOFeeSharehold_; mapping(address => uint256) internal holdoneTotalWithdrawn_; mapping(address => uint256) internal holdonePreviousWithdrawn_; mapping(address => uint256) internal holdoneSharehold_; mapping(address => uint256) internal holdtwoTotalWithdrawn_; mapping(address => uint256) internal holdtwoPreviousWithdrawn_; mapping(address => uint256) internal holdtwoSharehold_; mapping(address => uint256) internal holdthreeTotalWithdrawn_; mapping(address => uint256) internal holdthreePreviousWithdrawn_; mapping(address => uint256) internal holdthreeSharehold_; mapping(address => uint256) internal rewardsTotalWithdrawn_; mapping(address => uint256) internal rewardsPreviousWithdrawn_; mapping(address => uint256) internal rewardsSharehold_; mapping(address => uint256) internal techTotalWithdrawn_; mapping(address => uint256) internal techPreviousWithdrawn_; mapping(address => uint256) internal techSharehold_; mapping(address => uint256) internal existholdingsTotalWithdrawn_; mapping(address => uint256) internal existholdingsPreviousWithdrawn_; mapping(address => uint256) internal existholdingsSharehold_; mapping(address => uint256) internal existcryptoTotalWithdrawn_; mapping(address => uint256) internal existcryptoPreviousWithdrawn_; mapping(address => uint256) internal existcryptoSharehold_; mapping(address => uint256) internal whoaTotalWithdrawn_; mapping(address => uint256) internal whoaPreviousWithdrawn_; mapping(address => uint256) internal whoaSharehold_; mapping(address => uint256) internal credibleyouTotalWithdrawn_; mapping(address => uint256) internal credibleyouPreviousWithdrawn_; mapping(address => uint256) internal credibleyouSharehold_; mapping(address => uint256) internal numberofmintingrequestswhitelisted_; mapping(address => uint256) internal numberofpropertieswhitelisted_; mapping(address => uint256) internal numberofburnrequestswhitelisted_; mapping(address => uint256) internal transferingFromWallet_; uint256 public tokenSupply_ = 0; uint256 public feeTotalHolds_ = 0; uint256 internal cevaBurnerStockpile_ = 0; uint256 internal cevaBurnerStockpileWithdrawn_ = 0; uint256 internal taxesfeeTotalHolds_ = 0; uint256 internal taxesfeeBalanceLedger_ = 0; uint256 internal insurancefeeTotalHolds_ = 0; uint256 internal insurancefeeBalanceLedger_ = 0; uint256 internal maintencancefeeTotalHolds_ = 0; uint256 internal maintenancefeeBalanceLedger_ = 0; uint256 internal waECOfeeTotalHolds_ = 0; uint256 internal waECOfeeBalanceLedger_ = 0; uint256 internal holdonefeeTotalHolds_ = 0; uint256 internal holdonefeeBalanceLedger_ = 0; uint256 internal holdtwofeeTotalHolds_ = 0; uint256 internal holdtwofeeBalanceLedger_ = 0; uint256 internal holdthreefeeTotalHolds_ = 0; uint256 internal holdthreefeeBalanceLedger_ = 0; uint256 internal RewardsfeeTotalHolds_ = 0; uint256 internal RewardsfeeBalanceLedger_ = 0; uint256 internal techfeeTotalHolds_ = 0; uint256 internal techfeeBalanceLedger_ = 0; uint256 internal existholdingsfeeTotalHolds_ = 0; uint256 internal existholdingsfeeBalanceLedger_ = 0; uint256 internal existcryptofeeTotalHolds_ = 0; uint256 internal existcryptofeeBalanceLedger_ = 0; uint256 internal whoafeeTotalHolds_ = 0; uint256 internal whoafeeBalanceLedger_ = 0; uint256 internal credibleyoufeeTotalHolds_ = 0; uint256 internal credibleyoufeeBalanceLedger_ = 0; /*======================================= = MEMBER FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { } /* * -- APPLICATION ENTRY POINTS -- */ function InitialSet() public { // add the first users //James Admin administrators[0x27851761A8fBC03f57965b42528B39af07cdC42b] = true; //Brenden Admin administrators[0xA9873d93db3BCA9F68aDfEAb226Fa9189641069A] = true; members_[0x314d0ED76d866826C809fb6a51d63642b2E9eC3e] = true; members_[0x2722B426B11978c29660e8395a423Ccb93AE0403] = true; members_[0xdE281c22976dE2E9b3f4F87bEB60aE9E67DFf5C4] = true; members_[0xc9c1Ffd6B4014232Ef474Daa4CA1506A6E39Be89] = true; members_[0xac1B6580a175C1f2a4e3220A24e6f65fF3AB8A03] = true; members_[0xb8C098eE976f1162aD277936a5D1BCA7a8Fe61f5] = true; members_[0xB6148C62e6A6d48f41241D01e3C4841139144ABa] = true; members_[0xA9d241b568DF9E8A7Ec9e44737f29a8Ee00bfF53] = true; members_[0x314d0ED76d866826C809fb6a51d63642b2E9eC3e] = true; members_[0x314d0ED76d866826C809fb6a51d63642b2E9eC3e] = true; } /* * -- APPLICATION ENTRY POINTS -- */ function genesis(address _existcryptoaddress, address _existhooldingsaddress, address _techaddress, address _credibleyouaddress, address _cevaaddress, address _whoaddress, address _whoarewardsaddress, address _whoamaintenanceaddress) public onlyAdministrator(msg.sender) { require(administrators[msg.sender]); // adds the first founder developer here. founderdevelopers_[msg.sender] = true; // adds the _whoaddress input as the current whoa address whoaaddress_ = _whoaddress; // adds the _whoamaintenanceaddress input as the current whoa maintenence address whoamaintenanceaddress_ = _whoamaintenanceaddress; // adds the _whoarewardsaddress input as the current whoa rewards address whoarewardsaddress_ = _whoarewardsaddress; // adds the )cevaaddress_ input as the current ceva address cevaaddress_ = _cevaaddress; // adds the _credibleyouaddress input as the current credible you address credibleyouaddress_ = _credibleyouaddress; // adds the _techaddress input as the current tech address techaddress_ = _techaddress; // adds the __existhooldingsaddress input as the current exist holdings address existholdingsaddress_ = _existhooldingsaddress; // adds the _existcryptoaddress input as the current exist crypto address existcryptoaddress_ = _existcryptoaddress; // adds the first ceva qualified founder developers here. ceva_[msg.sender] = true; numberofburnrequestswhitelisted_[msg.sender] = 0; numberofpropertieswhitelisted_[msg.sender] = 0; numberofmintingrequestswhitelisted_[msg.sender] = 0; // adds the first member here. members_[msg.sender] = true; } /** * Withdraws all of the callers taxes earnings. */ function buyFounderDeveloperLicense(address _FounderDeveloperOne, address _FounderDeveloperTwo, address _CEVA) onlyMembers(msg.sender) public returns(bool _success) { require(founderdevelopers_[_FounderDeveloperOne] == true && ceva_[_CEVA] == true && founderdevelopers_[_FounderDeveloperTwo] == true); // setup data address _customerAddress = msg.sender; uint256 _licenseprice = (1000 * 1e18); if(tokenBalanceLedger_[_customerAddress] > _licenseprice){ tokenBalanceLedger_[_CEVA] = (_licenseprice / 5) + tokenBalanceLedger_[_CEVA]; tokenBalanceLedger_[_FounderDeveloperOne] = (_licenseprice / 5) + tokenBalanceLedger_[_FounderDeveloperOne]; tokenBalanceLedger_[_FounderDeveloperTwo] = (_licenseprice / 10) + tokenBalanceLedger_[_FounderDeveloperTwo]; tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress] - _licenseprice; founderdevelopers_[_customerAddress] = true; return true; } else { return false; } } /** * Withdraws all of the callers taxes earnings. */ function withdrawTaxesdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EtaxesdividendsOf(msg.sender); // update dividend tracker taxesFeeTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawInsurancedividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EinsurancedividendsOf(msg.sender); // update dividend tracker insuranceFeeTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawMaintenancedividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EmaintenancedividendsOf(msg.sender); // update dividend tracker maintenanceFeeTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawwaECOdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EwaECOdividendsOf(msg.sender); // update dividend tracker maintenanceFeeTotalWithdrawn_[_customerAddress] += _dividends; waECOFeeTotalWithdrawn_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawHoldOnedividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EholdonedividendsOf(msg.sender); // update dividend tracker holdoneTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawHoldTwodividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EholdtwodividendsOf(msg.sender); // update dividend tracker holdtwoTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawHoldThreeedividends() onlyMembers(msg.sender) public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EholdthreedividendsOf(msg.sender); // update dividend tracker holdthreeTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawRewardsdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = ErewardsdividendsOf(msg.sender); // update dividend tracker rewardsTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawTechdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EtechdividendsOf(msg.sender); // update dividend tracker techTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawExistHoldingsdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = existholdingsdividendsOf(msg.sender); // update dividend tracker existholdingsTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawExistCryptodividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = existcryptodividendsOf(msg.sender); // update dividend tracker existcryptoTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawWHOAdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EwhoadividendsOf(msg.sender); // update dividend tracker whoaTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawCrediblelYoudividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EcredibleyoudividendsOf(msg.sender); // update dividend tracker credibleyouTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 2% fee here as well. members only */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyMembers(msg.sender) public returns(bool) { if(_amountOfTokens > 0){ // make sure we have the requested tokens require(_amountOfTokens + (_amountOfTokens / 50) <= tokenBalanceLedger_[msg.sender] && _amountOfTokens >= 0 && _toAddress != msg.sender && members_[_toAddress] == true); //Exchange tokens tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress] + _amountOfTokens; tokenBalanceLedger_[msg.sender] -= _amountOfTokens + (_amountOfTokens / 50); //Update Equity Rents updateEquityRents(_amountOfTokens); AmountCirculated_[msg.sender] += _amountOfTokens; emit Transfer(msg.sender, _toAddress, (_amountOfTokens + (_amountOfTokens / 50))); return true; } else { return false; } } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 2% fee here as well. members only */ function transferFrom(address from, address to, uint256 tokens) onlyMembers(msg.sender) public returns(bool) { if(tokens >= 0){ require(members_[to] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested tokens require(tokens + (tokens / 50) <= tokenBalanceLedger_[from] && tokens >= 0 && to != _customerAddress && from != to && tokens + (tokens / 50) <= _allowed[from][msg.sender] && msg.sender != from && transferingFromWallet_[msg.sender] == 0); transferingFromWallet_[msg.sender] = 1; //Exchange tokens tokenBalanceLedger_[to] = tokenBalanceLedger_[to] + tokens; tokenBalanceLedger_[msg.sender] -= tokens + (tokens / 50); //Reduce Approval Amount _allowed[from][msg.sender] -= tokens + (tokens / 50); emit Transfer(_customerAddress, to, (tokens + (tokens / 50))); transferingFromWallet_[msg.sender] = 0; return true; } else { return false; } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return _allowed[tokenOwner][spender]; } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 2% fee here as well. members only */ function clearTitle(uint256 _propertyValue, uint256 _amountOfTokens, address _clearFrom) onlyMembers(msg.sender) public returns(bool) { if((_amountOfTokens / 1e18) * 100 <= _propertyValue){ require(burnrequestwhitelist_[_clearFrom][workingBurnRequestid_[msg.sender]] == true && propertywhitelist_[_clearFrom][workingPropertyid_[msg.sender]] == true && _amountOfTokens <= tokenBalanceLedger_[_clearFrom] && _amountOfTokens >= 0); //Burn Tokens burnA(_propertyValue); tokenSupply_ -= _amountOfTokens; taxesfeeTotalHolds_ -= _propertyValue / 100; insurancefeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); maintencancefeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); waECOfeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdonefeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdtwofeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdthreefeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); // take tokens out of stockpile //Exchange tokens cevaBurnerStockpile_ -= ((propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100) * 1e18) - _amountOfTokens; tokenBalanceLedger_[msg.sender] -= _amountOfTokens; // burn fee shareholds taxesFeeSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); insuranceFeeSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); maintenanceFeeSharehold_[whoamaintenanceaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); waECOFeeSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdoneSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdtwoSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdthreeSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); rewardsSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); techSharehold_[techaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); existholdingsSharehold_[existholdingsaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); existcryptoSharehold_[existcryptoaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); whoaSharehold_[whoaaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); credibleyouSharehold_[credibleyouaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); // returns bool true emit Burn(msg.sender, _amountOfTokens, _propertyValue); return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellTaxesFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= taxesFeeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals taxesPreviousWithdrawn_[_toAddress] += (taxesFeeTotalWithdrawn_[_customerAddress] / taxesFeeSharehold_[_customerAddress]) * _amount; //Exchange sharehold taxesFeeSharehold_[_toAddress] += _amount; taxesFeeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellInsuranceFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= insuranceFeeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals insurancePreviousWithdrawn_[_toAddress] += (insuranceFeeTotalWithdrawn_[_customerAddress] / insuranceFeeSharehold_[_customerAddress]) * _amount; //Exchange sharehold insuranceFeeSharehold_[_toAddress] += _amount; insuranceFeeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellMaintenanceFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= maintenanceFeeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals maintenancePreviousWithdrawn_[_toAddress] += (maintenanceFeeTotalWithdrawn_[_customerAddress] / maintenanceFeeSharehold_[_customerAddress]) * _amount; //Exchange sharehold maintenanceFeeSharehold_[_toAddress] += _amount; maintenanceFeeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellwaECOFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= waECOFeeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals waECOPreviousWithdrawn_[_toAddress] += (waECOFeeTotalWithdrawn_[_customerAddress] / waECOFeeSharehold_[_customerAddress]) * _amount; //Exchange sharehold waECOFeeSharehold_[_toAddress] += _amount; waECOFeeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellHoldOneFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= holdoneSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals holdonePreviousWithdrawn_[_toAddress] += (holdoneTotalWithdrawn_[_customerAddress] / holdoneSharehold_[_customerAddress]) * _amount; //Exchange sharehold holdoneSharehold_[_toAddress] += _amount; holdoneSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellHoldTwoFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= holdtwoSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals holdtwoPreviousWithdrawn_[_toAddress] += (holdtwoTotalWithdrawn_[_customerAddress] / holdtwoSharehold_[_customerAddress]) * _amount; //Exchange sharehold holdtwoSharehold_[_toAddress] += _amount; holdtwoSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellHoldThreeFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= holdthreeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals holdthreePreviousWithdrawn_[_toAddress] += (holdthreeTotalWithdrawn_[_customerAddress] / holdthreeSharehold_[_customerAddress]) * _amount; //Exchange sharehold holdthreeSharehold_[_toAddress] += _amount; holdthreeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellRewardsFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= rewardsSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals rewardsPreviousWithdrawn_[_toAddress] += (rewardsTotalWithdrawn_[_customerAddress] / rewardsSharehold_[_customerAddress]) * _amount; //Exchange sharehold rewardsSharehold_[_toAddress] += _amount; rewardsSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellTechFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= techSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals techPreviousWithdrawn_[_toAddress] += (techTotalWithdrawn_[_customerAddress] / techSharehold_[_customerAddress]) * _amount; //Exchange sharehold techSharehold_[_toAddress] += _amount; techSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellExistHoldingsFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) onlyMembers(_toAddress) public returns(bool) { if(_amount > 0){ //require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= existholdingsSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals existholdingsPreviousWithdrawn_[_toAddress] += (existholdingsTotalWithdrawn_[_customerAddress] / existholdingsSharehold_[_customerAddress]) * _amount; //Exchange sharehold existholdingsSharehold_[_toAddress] += _amount; existholdingsSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellExistCryptoFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= existcryptoSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals existcryptoPreviousWithdrawn_[_toAddress] += (existcryptoTotalWithdrawn_[_customerAddress] / existcryptoSharehold_[_customerAddress]) * _amount; //Exchange sharehold existcryptoSharehold_[_toAddress] += _amount; existcryptoSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellWHOAFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= whoaSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals whoaPreviousWithdrawn_[_toAddress] += (whoaTotalWithdrawn_[_customerAddress] / whoaSharehold_[_customerAddress]) * _amount; //Exchange sharehold whoaSharehold_[_toAddress] += _amount; whoaSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellCredibleYouFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= credibleyouSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals credibleyouPreviousWithdrawn_[_toAddress] += (credibleyouTotalWithdrawn_[_customerAddress] / credibleyouSharehold_[_customerAddress]) * _amount; //Exchange sharehold credibleyouSharehold_[_toAddress] += _amount; credibleyouSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Check and address to see if it has CEVA privileges or not */ function checkCEVA(address _identifier) public view returns(bool) { if(ceva_[_identifier] == true){ return true; } else { return false; } } /** * Check and address to see if it has member privileges */ function checkMember(address _identifier) public view returns(bool) { if(members_[_identifier] == true){ return true; } else { return false; } } /** * Check and address to see is its got founder developer privileges */ function checkFounderDeveloper(address _identifier) public view returns(bool) { if(founderdevelopers_[_identifier] == true){ return true; } else { return false; } } /** * Check and address to see if it has admin privileges */ function checkAdmin(address _identifier) public view returns(bool) { if(administrators[_identifier] == true){ return true; } else { return false; } } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * whitelist Admins admin only */ function AwhitelistAdministrator(address _identifier, bool _status) onlyAdministrator(msg.sender) public { require(msg.sender != _identifier); administrators[_identifier] = _status; emit AdminWhitelisted(msg.sender, _identifier, _status); } /** * Automation entrypoint to whitelist ceva_ admin only */ function AwhitelistCEVA(address _identifier, bool _status) onlyAdministrator(msg.sender) public { require(msg.sender != _identifier); ceva_[_identifier] = _status; numberofburnrequestswhitelisted_[msg.sender] = 0; numberofpropertieswhitelisted_[msg.sender] = 0; numberofmintingrequestswhitelisted_[msg.sender] = 0; emit CEVAWhitelisted(msg.sender, _identifier, _status); } function withdrawCEVABurnerStockpiledividends(uint256 _amountOfTokens) onlyCEVA(msg.sender) public { // setup data require(_amountOfTokens <= cevaBurnerStockpile_); // update dividend tracker cevaBurnerStockpile_ -= _amountOfTokens; cevaBurnerStockpileWithdrawn_ += _amountOfTokens; tokenBalanceLedger_[cevaaddress_] += _amountOfTokens; emit Transfer(msg.sender, msg.sender, _amountOfTokens); } /** * Whitelist a Property that has been confirmed on the site.. ceva only */ function AwhitelistMintRequest(address _OwnerAddress, bool _trueFalse, bytes32 _mintingRequestUniqueid) onlyCEVA(msg.sender) public returns(bool) { if(_mintingRequestUniqueid == workingMintRequestid_[msg.sender]){ require(msg.sender != _OwnerAddress); mintrequestwhitelist_[_OwnerAddress][_mintingRequestUniqueid] = _trueFalse; return true; } else { return false; } } /** * Whitelist a Property that has been confirmed on the site.. ceva only */ function AwhitelistBurnRequest(address _OwnerAddress, bool _trueFalse, bytes32 _burnrequestUniqueID) onlyCEVA(msg.sender) public returns(bool) { if(_burnrequestUniqueID == workingBurnRequestid_[msg.sender]){ require(msg.sender != _OwnerAddress); burnrequestwhitelist_[_OwnerAddress][_burnrequestUniqueID] = _trueFalse; return true; } else { return false; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function AwhitelistProperty(address _OwnerAddress, bool _trueFalse, bytes32 _propertyUniqueID) onlyCEVA(msg.sender) public returns(bool) { if(_trueFalse = true){ require(workingPropertyid_[msg.sender] == _propertyUniqueID); propertywhitelist_[_OwnerAddress][_propertyUniqueID] = _trueFalse; emit PropertyWhitelisted(msg.sender, _propertyUniqueID, _trueFalse); return true; } else { return false; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function AsetWhitelistedPropertyValue(address _OwnerAddress, bytes32 _propertyUniqueID, uint256 _propertyValue) onlyCEVA(msg.sender) public returns(uint256) { require(propertywhitelist_[_OwnerAddress][_propertyUniqueID] = true && _propertyValue >= 0); if(_OwnerAddress != msg.sender){ address _customerAddress = msg.sender; numberofmintingrequestswhitelisted_[msg.sender] += 1; emit PropertyValuation(_customerAddress, _propertyUniqueID, _propertyValue); return _propertyValue; } else { numberofmintingrequestswhitelisted_[msg.sender] -= 1; _propertyValue = 0; return _propertyValue; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function AsetworkingPropertyid(address _OwnerAddress, bytes32 _propertyUniqueID) onlyFounderDevelopers(msg.sender) public returns(bool) { require(propertywhitelist_[_OwnerAddress][_propertyUniqueID] = true); if(_OwnerAddress != msg.sender){ workingPropertyid_[_OwnerAddress] = _propertyUniqueID; return true; } else { return false; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function AsetworkingMintingRequest(address _OwnerAddress, bytes32 _mintingRequestUniqueid) onlyFounderDevelopers(msg.sender) public returns(bool) { require(mintrequestwhitelist_[_OwnerAddress][_mintingRequestUniqueid] = true); if(_OwnerAddress != msg.sender){ workingMintRequestid_[_OwnerAddress] = _mintingRequestUniqueid; return true; } else { return false; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function Asetworkingburnrequestid(address _OwnerAddress, bytes32 _propertyUniqueID, uint256 _propertyValue) onlyFounderDevelopers(msg.sender) public returns(bytes32) { require(burnrequestwhitelist_[_OwnerAddress][_propertyUniqueID] = true); if(_OwnerAddress != msg.sender){ workingPropertyid_[_OwnerAddress] = _propertyUniqueID; numberofmintingrequestswhitelisted_[msg.sender] += 1; emit PropertyValuation(msg.sender, _propertyUniqueID, _propertyValue); return _propertyUniqueID; } else { numberofmintingrequestswhitelisted_[msg.sender] -= 1; _propertyValue = 0; return _propertyUniqueID; } } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } function bStringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } /** * Whitelist a Founder Developer ceva only */ function AWhitelistFounderDeveloper(address _identifier, bool _status) onlyCEVA(msg.sender) public { founderdevelopers_[_identifier] = _status; numberofburnrequestswhitelisted_[msg.sender] = 0; numberofpropertieswhitelisted_[msg.sender] = 0; numberofmintingrequestswhitelisted_[msg.sender] = 0; emit FounderDeveloperWhitelisted(msg.sender, _identifier, _status); } /*---------- FOUNDER DEVELOPER ONLY FUNCTIONS ----------*/ // Mint an amount of tokens to an address // using a whitelisted minting request unique ID founder developer only function _mint(uint256 _FounderDeveloperFee, address _toAddress, address _holdOne, address _holdTwo, address _holdThree, uint256 _propertyValue, bytes32 _propertyUniqueID, bytes32 _mintingRequestUniqueid) onlyFounderDevelopers(msg.sender) public { if(_propertyValue >= 100){ // data setup uint256 _amountOfTokens = (_propertyValue * 1e18) / 100; require(members_[_toAddress] == true && _FounderDeveloperFee >= 20001 && _FounderDeveloperFee <= 100000 && (_amountOfTokens + tokenSupply_) > tokenSupply_ && msg.sender != _toAddress && _propertyUniqueID == workingPropertyid_[msg.sender] && _mintingRequestUniqueid == workingMintRequestid_[msg.sender] && _propertyValue == propertyvalue_[_toAddress][_propertyUniqueID]); // add tokens to the pool tokenSupply_ = tokenSupply_ + _amountOfTokens; updateHoldsandSupply(_amountOfTokens); // add to burner stockpile cevaBurnerStockpile_ += (_amountOfTokens / 16667) * 100; // whoa fee whoafeeBalanceLedger_ = whoafeeBalanceLedger_ + _amountOfTokens; // credit founder developer fee tokenBalanceLedger_[msg.sender] += (_amountOfTokens / _FounderDeveloperFee) * 1000; //credit Envelope Fee Shareholds creditFeeSharehold(_amountOfTokens, _toAddress, _holdOne, _holdTwo, _holdThree); // credit tech feeSharehold_ ; uint256 _TechFee = (_amountOfTokens / 25000) * 100; techfeeBalanceLedger_ = techfeeBalanceLedger_ + _TechFee; // fire event // add tokens to the _toAddress uint256 _cevabTransferfees = (_amountOfTokens / 333334) * 10000; uint256 _Fee = (_amountOfTokens / _FounderDeveloperFee) * 1000; tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress] + (_amountOfTokens - _cevabTransferfees); tokenBalanceLedger_[_toAddress] -= _Fee; tokenBalanceLedger_[_toAddress] -= _TechFee; emit Transfer(msg.sender, _toAddress, _amountOfTokens); mintingDepositsOf_[_toAddress] += _amountOfTokens; } else { return; } } function AworkingPropertyIDOf(address _user) onlyFounderDevelopers(msg.sender) public view returns(bytes32) { return workingPropertyid_[_user]; } function AworkingBurnRequestIDOf(address _user) onlyFounderDevelopers(msg.sender) public view returns(bytes32) { return workingBurnRequestid_[_user]; } function AworkingMintIDOf(address _user) onlyFounderDevelopers(msg.sender) public view returns(bytes32) { return workingMintRequestid_[_user]; } /** * whitelist a member founder developer only */ function AWhitelistMember(address _identifier, bool _status) onlyFounderDevelopers(msg.sender) public { require(msg.sender != _identifier); members_[_identifier] = _status; emit MemberWhitelisted(msg.sender, _identifier, _status); } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Retrieve the tokens owned by the caller. */ function TokensNoDecimals() view public returns(uint256) { address _customerAddress = msg.sender; uint256 _tokens = (balanceOf(_customerAddress) / 1e18); if(_tokens >= 1){ return _tokens; } else { return 0; } } function balanceOf(address _owner) view public returns(uint256) { return tokenBalanceLedger_[_owner]; } function EtaxesdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(taxesFeeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (taxesfeeBalanceLedger_ / taxesfeeTotalHolds_); return (uint256) ((_dividendPershare * taxesFeeSharehold_[_customerAddress]) - (taxesFeeTotalWithdrawn_[_customerAddress] + taxesPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EtaxesShareholdOf(address _customerAddress) view public returns(uint256) { if(taxesFeeSharehold_[_customerAddress] == 0){ return 0; } else { return taxesFeeSharehold_[_customerAddress]; } } /** * Retrieve the insurance dividend balance of any single address. */ function EinsurancedividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(insuranceFeeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (insurancefeeBalanceLedger_ / insurancefeeTotalHolds_); return (uint256) ((_dividendPershare * insuranceFeeSharehold_[_customerAddress]) - (insuranceFeeTotalWithdrawn_[_customerAddress] + insurancePreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EinsuranceShareholdOf(address _customerAddress) view public returns(uint256) { if(insuranceFeeSharehold_[_customerAddress] == 0){ return 0; } else { return insuranceFeeSharehold_[_customerAddress]; } } /** * Retrieve the maintenance dividend balance of any single address. */ function EmaintenancedividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(maintenanceFeeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (maintenancefeeBalanceLedger_ / maintencancefeeTotalHolds_); return (uint256) ((_dividendPershare * maintenanceFeeSharehold_[_customerAddress]) - (maintenanceFeeTotalWithdrawn_[_customerAddress] + maintenancePreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EmaintenanceShareholdOf(address _customerAddress) view public returns(uint256) { if(maintenanceFeeSharehold_[_customerAddress] == 0){ return 0; } else { return maintenanceFeeSharehold_[_customerAddress]; } } /** * Retrieve the Wealth Architect ECO Register 1.2 dividend balance of any single address. */ function EwaECOdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(waECOFeeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (waECOfeeBalanceLedger_ / waECOfeeTotalHolds_); return (uint256) ((_dividendPershare * waECOFeeSharehold_[_customerAddress]) - (waECOFeeTotalWithdrawn_[_customerAddress] + waECOPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EwaECOShareholdOf(address _customerAddress) view public returns(uint256) { if(waECOFeeSharehold_[_customerAddress] == 0){ return 0; } else { return waECOFeeSharehold_[_customerAddress]; } } /** * Retrieve the hold one dividend balance of any single address. */ function EholdonedividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(holdoneSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (holdonefeeBalanceLedger_ / holdonefeeTotalHolds_); return (uint256) ((_dividendPershare * holdoneSharehold_[_customerAddress]) - (holdoneTotalWithdrawn_[_customerAddress] + holdonePreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EholdoneShareholdOf(address _customerAddress) view public returns(uint256) { if(holdoneSharehold_[_customerAddress] == 0){ return 0; } else { return holdoneSharehold_[_customerAddress]; } } /** * Retrieve the hold two dividend balance of any single address. */ function EholdtwodividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(holdtwoSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (holdtwofeeBalanceLedger_ / holdtwofeeTotalHolds_); return (uint256) ((_dividendPershare * holdtwoSharehold_[_customerAddress]) - (holdtwoTotalWithdrawn_[_customerAddress] + holdtwoPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EholdtwoShareholdOf(address _customerAddress) view public returns(uint256) { if(holdtwoSharehold_[_customerAddress] == 0){ return 0; } else { return holdtwoSharehold_[_customerAddress]; } } /** * Retrieve the hold three dividend balance of any single address. */ function EholdthreedividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(holdthreeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (holdthreefeeBalanceLedger_ / holdthreefeeTotalHolds_); return (uint256) ((_dividendPershare * holdthreeSharehold_[_customerAddress]) - (holdthreeTotalWithdrawn_[_customerAddress] + holdthreePreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EholdthreeShareholdOf(address _customerAddress) view public returns(uint256) { if(holdthreeSharehold_[_customerAddress] == 0){ return 0; } else { return holdthreeSharehold_[_customerAddress]; } } /** * Retrieve the rewards dividend balance of any single address. */ function ErewardsdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(rewardsSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (RewardsfeeBalanceLedger_ / RewardsfeeTotalHolds_); return (uint256) ((_dividendPershare * rewardsSharehold_[_customerAddress]) - (rewardsTotalWithdrawn_[_customerAddress] + rewardsPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function ErewardsShareholdOf(address _customerAddress) view public returns(uint256) { if(rewardsSharehold_[_customerAddress] == 0){ return 0; } else { return rewardsSharehold_[_customerAddress]; } } /** * Retrieve the tech dividend balance of any single address. */ function EtechdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(techfeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (techfeeBalanceLedger_ / techfeeTotalHolds_); return (uint256) ((_dividendPershare * techSharehold_[_customerAddress]) - (techTotalWithdrawn_[_customerAddress] + techPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EtechShareholdOf(address _customerAddress) view public returns(uint256) { if(techSharehold_[_customerAddress] == 0){ return 0; } else { return techSharehold_[_customerAddress]; } } /** * Retrieve the exist holdings dividend balance of any single address. */ function existholdingsdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(existholdingsfeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (existholdingsfeeBalanceLedger_ / existholdingsfeeTotalHolds_); return (uint256) ((_dividendPershare * existholdingsSharehold_[_customerAddress]) - (existholdingsTotalWithdrawn_[_customerAddress] + existholdingsPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function existholdingsShareholdOf(address _customerAddress) view public returns(uint256) { if(existholdingsSharehold_[_customerAddress] == 0){ return 0; } else { return existholdingsSharehold_[_customerAddress]; } } /** * Retrieve the exist crypto dividend balance of any single address. */ function existcryptodividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(existcryptofeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (existcryptofeeBalanceLedger_ / existcryptofeeTotalHolds_); return (uint256) ((_dividendPershare * existcryptoSharehold_[_customerAddress]) - (existcryptoTotalWithdrawn_[_customerAddress] + existcryptoPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function existcryptoShareholdOf(address _customerAddress) view public returns(uint256) { if(existcryptoSharehold_[_customerAddress] == 0){ return 0; } else { return existcryptoSharehold_[_customerAddress]; } } /** * Retrieve the Worldwide Home Owners Association dividend balance of any single address. */ function EwhoadividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(whoafeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (whoafeeBalanceLedger_ / whoafeeTotalHolds_); return (uint256) ((_dividendPershare * whoaSharehold_[_customerAddress]) - (whoaTotalWithdrawn_[_customerAddress] + whoaPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the WHOA dividend balance of any single address. */ function EwhoaShareholdOf(address _customerAddress) view public returns(uint256) { if(whoaSharehold_[_customerAddress] == 0){ return 0; } else { return whoaSharehold_[_customerAddress]; } } /** * Retrieve the Credible You dividend balance of any single address. */ function EcredibleyoudividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(credibleyoufeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (credibleyoufeeBalanceLedger_ / credibleyoufeeTotalHolds_); return (uint256) ((_dividendPershare * credibleyouSharehold_[_customerAddress]) - (credibleyouTotalWithdrawn_[_customerAddress] + credibleyouPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EcredibleyouShareholdOf(address _customerAddress) view public returns(uint256) { if(credibleyouSharehold_[_customerAddress] == 0){ return 0; } else { return credibleyouSharehold_[_customerAddress]; } } /** * Retrieve the CEVA Burner Stockpile dividend balance using a CEVA whitelisted address. */ function EcevaBurnerStockpileDividends() onlyCEVA(msg.sender) view public returns(uint256) { uint256 _dividendPershare; address _customerAddress = msg.sender; if(ceva_[_customerAddress] != true){ return 0; } else { _dividendPershare = cevaBurnerStockpile_; return _dividendPershare; } } function totalSupply() public view returns(uint256) { if(tokenSupply_ == 0){ return 0; } else { return tokenSupply_;} } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ /** * Update token balance ledger of an address tokens from the caller to a new holder. */ function updateHoldsandSupply(uint256 _amountOfTokens) internal returns(bool) { tokenSupply_ = tokenSupply_ + _amountOfTokens; taxesfeeTotalHolds_ = (_amountOfTokens / 1e18) + taxesfeeTotalHolds_; insurancefeeTotalHolds_ = (_amountOfTokens / 1e18) + insurancefeeTotalHolds_; maintencancefeeTotalHolds_ = (_amountOfTokens / 1e18) + maintencancefeeTotalHolds_; waECOfeeTotalHolds_ = (_amountOfTokens / 1e18) + waECOfeeTotalHolds_; holdonefeeTotalHolds_ = (_amountOfTokens / 1e18) + holdonefeeTotalHolds_; holdtwofeeTotalHolds_ = (_amountOfTokens / 1e18) + holdtwofeeTotalHolds_; holdthreefeeTotalHolds_ = (_amountOfTokens / 1e18) + holdthreefeeTotalHolds_; RewardsfeeTotalHolds_ = (_amountOfTokens / 1e18) + RewardsfeeTotalHolds_; techfeeTotalHolds_ = (_amountOfTokens / 1e18) + techfeeTotalHolds_; existholdingsfeeTotalHolds_ = (_amountOfTokens / 1e18) + existholdingsfeeTotalHolds_; existcryptofeeTotalHolds_ = (_amountOfTokens / 1e18) + existcryptofeeTotalHolds_; whoafeeTotalHolds_ = (_amountOfTokens / 1e18) + whoafeeTotalHolds_; credibleyoufeeTotalHolds_= (_amountOfTokens / 1e18) + credibleyoufeeTotalHolds_; feeTotalHolds_ = ((_amountOfTokens / 1e18)* 13) + feeTotalHolds_; return true; } /** * Update token balance ledger of an address tokens from the caller to a new holder. * Remember, there's a fee here as well. */ function burnA(uint256 _amount) internal returns(bool) { uint256 _pValue = _amount / 100; if(_amount > 0){ RewardsfeeTotalHolds_ -= _pValue; techfeeTotalHolds_ -= _pValue; existholdingsfeeTotalHolds_ -= _pValue; existcryptofeeTotalHolds_ -= _pValue; whoafeeTotalHolds_-= _pValue; credibleyoufeeTotalHolds_ -= _pValue; feeTotalHolds_ -= _pValue; return true; } else { return false; } } /** * calculate 2% total transfer fee based on _amountOfTokens */ function calulateAmountQualified(uint256 _TokenMintingDepositsOf, uint256 _AmountCirculated) internal pure returns(uint256 _AmountQualified) { _AmountQualified = _TokenMintingDepositsOf / _AmountCirculated; if(_AmountQualified <= 1){ _AmountQualified = 1; return _AmountQualified; } else { return _AmountQualified; } } function updateEquityRents(uint256 _amountOfTokens) internal returns(bool) { if(_amountOfTokens < 0){ _amountOfTokens = 0; return false; } else { taxesfeeBalanceLedger_ = taxesfeeBalanceLedger_ + (_amountOfTokens / 800); insurancefeeBalanceLedger_ = insurancefeeBalanceLedger_ + (_amountOfTokens / 800); maintenancefeeBalanceLedger_ = maintenancefeeBalanceLedger_ + (_amountOfTokens / 800); waECOfeeBalanceLedger_ = waECOfeeBalanceLedger_ + (_amountOfTokens / 800); holdonefeeBalanceLedger_ = holdonefeeBalanceLedger_ + (_amountOfTokens / 800); holdtwofeeBalanceLedger_ = holdtwofeeBalanceLedger_ + (_amountOfTokens / 800); holdthreefeeBalanceLedger_ = holdthreefeeBalanceLedger_ + (_amountOfTokens / 800); RewardsfeeBalanceLedger_ = RewardsfeeBalanceLedger_ + (_amountOfTokens / 800); techfeeBalanceLedger_ = techfeeBalanceLedger_ + ((_amountOfTokens / 25000) * 100); existholdingsfeeBalanceLedger_ = existholdingsfeeBalanceLedger_ + (_amountOfTokens / 445); existcryptofeeBalanceLedger_ = existcryptofeeBalanceLedger_ + (_amountOfTokens / 800); whoafeeBalanceLedger_ = whoafeeBalanceLedger_ + (_amountOfTokens / 800); credibleyoufeeBalanceLedger_ = credibleyoufeeBalanceLedger_ + (_amountOfTokens / 800); return true; } } /** * Update taxes fee sharehold of an address.. */ function creditTaxesFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { taxesFeeSharehold_[_toAddress] += _amountOfTokens; } /** * Update insurance fee sharehold of an address.. */ function creditInsuranceFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { insuranceFeeSharehold_[_toAddress] += _amountOfTokens; } /** * Update maintenance fee sharehold of an address.. */ function creditMaintenanceFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { maintenanceFeeSharehold_[_toAddress] += _amountOfTokens; } /** * Update Wealth Architect fee sharehold of an address.. */ function creditwaECOFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { waECOFeeSharehold_[_toAddress] += _amountOfTokens; } /** * Update hold one fee sharehold of an address.. */ function creditHoldOneFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { holdoneSharehold_[_toAddress] += _amountOfTokens; } /** * Update hold two fee sharehold of an address.. */ function creditHoldTwoFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { holdtwoSharehold_[_toAddress] += _amountOfTokens; } /** * Update hold three fee sharehold of an address.. */ function creditHoldThreeFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { holdthreeSharehold_[_toAddress] += _amountOfTokens; } /** * Update Rewards fee sharehold of an address.. */ function creditRewardsFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { rewardsSharehold_[_toAddress] += _amountOfTokens; } /** * Update Tech fee sharehold of an address.. */ function creditTechFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { techSharehold_[_toAddress] += _amountOfTokens; } /** * Update Exist Holdings fee sharehold of an address.. */ function creditExistHoldingsFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { existholdingsSharehold_[_toAddress] += _amountOfTokens; } /** * Update Exist Crypto fee sharehold of an address.. */ function creditExistCryptoFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { existcryptoSharehold_[_toAddress] += _amountOfTokens; } /** * Update WHOA fee sharehold of an address.. */ function creditWHOAFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { whoaSharehold_[_toAddress] += _amountOfTokens; } /** * Update Credible You fee sharehold of an address.. */ function creditCredibleYouFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { credibleyouSharehold_[_toAddress] += _amountOfTokens; } /** * Update Exist Holdings fee sharehold of an address.. */ function creditFeeSharehold(uint256 _amountOfTokens, address _owner, address _toAddress, address _toAddresstwo, address _toAddressthree) internal returns(bool) { creditTaxesFeeSharehold((_amountOfTokens / 1e18), _owner); creditInsuranceFeeSharehold((_amountOfTokens / 1e18), _owner); creditMaintenanceFeeSharehold((_amountOfTokens / 1e18), whoamaintenanceaddress_); creditwaECOFeeSharehold((_amountOfTokens / 1e18), _owner); creditHoldOneFeeSharehold((_amountOfTokens / 1e18), _toAddress); creditHoldTwoFeeSharehold((_amountOfTokens / 1e18), _toAddresstwo); creditHoldThreeFeeSharehold((_amountOfTokens / 1e18), _toAddressthree); creditRewardsFeeSharehold((_amountOfTokens / 1e18), whoarewardsaddress_); creditTechFeeSharehold((_amountOfTokens / 1e18), techaddress_); creditExistHoldingsFeeSharehold((_amountOfTokens / 1e18), existholdingsaddress_); creditExistCryptoFeeSharehold((_amountOfTokens / 1e18), existcryptoaddress_); creditWHOAFeeSharehold((_amountOfTokens / 1e18), whoaaddress_); creditCredibleYouFeeSharehold((_amountOfTokens / 1e18), credibleyouaddress_); return true; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } }
amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_ ;
6,506,211
[ 1, 8949, 434, 24123, 364, 1517, 1758, 261, 20665, 1300, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 2713, 1147, 13937, 28731, 67, 274, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; contract Adoption { uint VersionMarker3 = 650; event GetPetCount(uint256 _count); event Bidding(uint256 _petId, uint256 _biddingPrice, address _bidderAddres, bool _isSuccess); struct Pet { uint256 id; string name; string pictureHash; uint256 age; string breed; string location; address adopter; //also the winner of an auction bool forFree; //true is for adotion, false is for auction //parameters below are for aucitons only uint256 currentPrice; uint256 minIncrement; } mapping(uint256 => mapping(uint256 => Pet)) public Pets; //[# of generations][pet-id] uint256 public petsCount; uint256 private _testIterationNum = 0; mapping(uint256 => address[]) public likes; constructor() public { petsCount = 0; } // Adopting a pet function setAdopter(uint256 petId) public returns (uint256) { require(petId >= 0 && petId < petsCount && Pets[_testIterationNum][petId].forFree == true); //we might need to add Pets[_testIterationNum][petId].adopter == address(0) //and Pets[_testIterationNum][petId].forFree == true Pet storage pet = Pets[_testIterationNum][petId]; pet.adopter = msg.sender; // Pets[_testIterationNum][petId].adopter = msg.sender; return petId; } // Bid on a pet function processBid(uint256 petId, uint256 bidPrice) public returns (bool) { require(petId >= 0 && petId < petsCount && Pets[_testIterationNum][petId].forFree == false); uint256 minimumPrice = Pets[_testIterationNum][petId].currentPrice + Pets[_testIterationNum][petId].minIncrement; address currentAdopter = Pets[_testIterationNum][petId].adopter; if (bidPrice >= minimumPrice) { //(bidPrice >= minimumPrice && msg.sender != currentAdopter) Pets[_testIterationNum][petId].currentPrice = bidPrice; Pets[_testIterationNum][petId].adopter = msg.sender; emit Bidding(petId, bidPrice, msg.sender, true); return true; } else { emit Bidding(petId, bidPrice, msg.sender, false); return false; } } // Adding new pet function addNewPet( string memory name, string memory picHash, uint256 age, string memory breed, string memory location, bool forFree, uint256 startPrice, uint256 minIncrement ) public returns (uint256) { // to make sure the followings are positive if (startPrice<0) { startPrice = 1; } if (minIncrement<0) { minIncrement = 1; } Pets[_testIterationNum][petsCount] = Pet( petsCount, name, picHash, age, breed, location, address(0), forFree, startPrice, minIncrement ); petsCount++; emit GetPetCount(petsCount); return petsCount; } function deleteAllPets() public returns (bool) { _testIterationNum++; petsCount = 0; return true; } // function getPetsInfo() external view returns (uint256[] memory, string[] memory, string[] memory, uint256[] memory, string[] memory, string[] memory, address[] memory) { // uint256[] memory ids = new uint256[](petsCount); // string[] memory names = new string[](petsCount); // string[] memory pictureHashs = new string[](petsCount); // uint256[] memory ages = new uint256[](petsCount); // string[] memory breeds = new string[](petsCount); // string[] memory locations = new string[](petsCount); // address[] memory adopters = new address[](petsCount); // for (uint256 i = 0; i < petsCount; i++) { // ids[i] = (Pets[_testIterationNum][i].id); // names[i] = Pets[_testIterationNum][i].name; // pictureHashs[i] = (Pets[_testIterationNum][i].pictureHash); // breeds[i] = (Pets[_testIterationNum][i].breed); // locations[i] = (Pets[_testIterationNum][i].location); // adopters[i] = (Pets[_testIterationNum][i].adopter); // ages[i] = (Pets[_testIterationNum][i].age); // } // return (ids,names,pictureHashs,ages,breeds,locations,adopters); // } // Solidity Function has maxmum number of local variables of 16, string counts two. function getPetInfo(uint256 petId) public view returns (uint256, string memory, string memory, uint256, string memory, string memory, address) { require(petId >= 0 && petId < petsCount); return (Pets[_testIterationNum][petId].id, Pets[_testIterationNum][petId].name, Pets[_testIterationNum][petId].pictureHash, Pets[_testIterationNum][petId].age, Pets[_testIterationNum][petId].breed, Pets[_testIterationNum][petId].location, Pets[_testIterationNum][petId].adopter); } function getPetType(uint256 petId) public view returns (uint256, bool) { require(petId >= 0 && petId < petsCount); return (Pets[_testIterationNum][petId].id, Pets[_testIterationNum][petId].forFree); } function getPetPrice(uint256 petId) public view returns (uint256, uint256, uint256, address) { require(petId >= 0 && petId < petsCount); return (Pets[_testIterationNum][petId].id, Pets[_testIterationNum][petId].currentPrice, Pets[_testIterationNum][petId].minIncrement, Pets[_testIterationNum][petId].adopter); } // function getPetInfo(uint256 petId) public view returns (Pet memory) { // require(petId >= 0 && petId < petsCount); // return Pets[_testIterationNum][petId]; // } // Retrieving the adopters // function getAdopters() public view returns (address[16] memory) { // return adopters; // } function() external payable {} function setLike(uint256 petId) public returns(uint256){ require(petId >= 0 && petId < petsCount); likes[petId].push(msg.sender); return petId; } function getLike(uint256 petId) public view returns(bool){ require(petId >= 0 && petId < petsCount); uint len = likes[petId].length; for (uint i = 0; i < len; i++){ if (likes[petId][i] == msg.sender){ return true; } } return false; } }
parameters below are for aucitons only
struct Pet { uint256 id; string name; string pictureHash; uint256 age; string breed; string location; uint256 currentPrice; uint256 minIncrement; } uint256 public petsCount; uint256 private _testIterationNum = 0; mapping(uint256 => address[]) public likes;
15,827,438
[ 1, 3977, 5712, 854, 364, 279, 5286, 305, 7008, 1338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 453, 278, 288, 203, 3639, 2254, 5034, 612, 31, 203, 3639, 533, 508, 31, 203, 3639, 533, 15406, 2310, 31, 203, 3639, 2254, 5034, 9388, 31, 203, 3639, 533, 324, 15656, 31, 203, 3639, 533, 2117, 31, 203, 203, 3639, 2254, 5034, 783, 5147, 31, 203, 3639, 2254, 5034, 1131, 10798, 31, 203, 565, 289, 203, 203, 203, 565, 2254, 5034, 1071, 293, 2413, 1380, 31, 203, 565, 2254, 5034, 3238, 389, 3813, 10795, 2578, 273, 374, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 63, 5717, 1071, 7906, 281, 31, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x955228997347800a13FFA0e4ae7964b5519E974d/sources/_uniswap/v3-periphery/contracts/libraries/BytesLib.sol
Get a location of some free memory and store it in tempBytes as Solidity does for memory variables. The first word of the slice result is potentially a partial word read from the original array. To read it, we calculate the length of that partial word and start copying that many bytes into the array. The first word we copy will start with data we don't care about, but the last `lengthmod` bytes will land at the beginning of the contents of the new array. When we're done copying, we overwrite the full first word with the actual length of the slice. The multiplication in the next line is necessary because when slicing multiples of 32 bytes (lengthmod == 0) the following copy loop was copying the origin's length and then ending prematurely not copying everything it should. The multiplication in the next line has the same exact purpose as the one above.if we want a zero-length slice let's just return a zero-length arrayzero out the 32 bytes slice we are about to returnwe need to do it because Solidity does not garbage collect
) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { tempBytes := mload(0x40) let lengthmod := and(_length, 31) let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) mc := add(mc, 0x20) cc := add(cc, 0x20) mstore(mc, mload(cc)) } mstore(tempBytes, _length) } default { tempBytes := mload(0x40) mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; }
4,926,211
[ 1, 967, 279, 2117, 434, 2690, 4843, 3778, 471, 1707, 518, 316, 1906, 2160, 487, 348, 7953, 560, 1552, 364, 3778, 3152, 18, 1021, 1122, 2076, 434, 326, 2788, 563, 353, 13935, 279, 4702, 2076, 855, 628, 326, 2282, 526, 18, 2974, 855, 518, 16, 732, 4604, 326, 769, 434, 716, 4702, 2076, 471, 787, 8933, 716, 4906, 1731, 1368, 326, 526, 18, 1021, 1122, 2076, 732, 1610, 903, 787, 598, 501, 732, 2727, 1404, 7671, 2973, 16, 1496, 326, 1142, 1375, 2469, 1711, 68, 1731, 903, 19193, 622, 326, 8435, 434, 326, 2939, 434, 326, 394, 526, 18, 5203, 732, 4565, 2731, 8933, 16, 732, 6156, 326, 1983, 1122, 2076, 598, 326, 3214, 769, 434, 326, 2788, 18, 1021, 23066, 316, 326, 1024, 980, 353, 4573, 2724, 1347, 2020, 14774, 3309, 6089, 434, 3847, 1731, 261, 2469, 1711, 422, 374, 13, 326, 3751, 1610, 2798, 1703, 8933, 326, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 262, 2713, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 2583, 24899, 2469, 397, 8231, 1545, 389, 2469, 16, 296, 6665, 67, 11512, 8284, 203, 3639, 2583, 24899, 3890, 18, 2469, 1545, 389, 1937, 397, 389, 2469, 16, 296, 6665, 67, 659, 951, 5694, 8284, 203, 203, 3639, 1731, 3778, 1906, 2160, 31, 203, 203, 3639, 19931, 288, 203, 5411, 1620, 353, 7124, 24899, 2469, 13, 203, 5411, 648, 374, 288, 203, 7734, 1906, 2160, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 203, 7734, 2231, 769, 1711, 519, 471, 24899, 2469, 16, 8231, 13, 203, 203, 7734, 2231, 6108, 519, 527, 12, 1289, 12, 5814, 2160, 16, 769, 1711, 3631, 14064, 12, 20, 92, 3462, 16, 353, 7124, 12, 2469, 1711, 20349, 203, 7734, 2231, 679, 519, 527, 12, 13952, 16, 389, 2469, 13, 203, 203, 7734, 364, 288, 203, 10792, 2231, 4946, 519, 527, 12, 1289, 12, 1289, 24899, 3890, 16, 769, 1711, 3631, 14064, 12, 20, 92, 3462, 16, 353, 7124, 12, 2469, 1711, 3719, 3631, 389, 1937, 13, 203, 10792, 6108, 519, 527, 12, 13952, 16, 374, 92, 3462, 13, 203, 10792, 4946, 519, 527, 12, 952, 16, 374, 92, 3462, 13, 203, 10792, 312, 2233, 12, 13952, 16, 312, 945, 12, 952, 3719, 203, 7734, 289, 203, 203, 7734, 312, 2233, 12, 5814, 2160, 16, 389, 2469, 13, 203, 203, 5411, 289, 203, 5411, 805, 288, 203, 7734, 1906, 2160, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 7734, 312, 2233, 12, 5814, 2160, 16, 2 ]
pragma solidity ^0.4.21; // Generated by TokenGen and the Fabric Token platform. // https://tokengen.io // https://fabrictoken.io // File: contracts/library/SafeMath.sol /** * @title Safe Math * * @dev Library for safe mathematical operations. */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function minus(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function plus(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/token/ERC20Token.sol /** * @dev The standard ERC20 Token contract base. */ contract ERC20Token { uint256 public totalSupply; /* shorthand for public function and a property */ function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // File: contracts/component/TokenSafe.sol /** * @title TokenSafe * * @dev Abstract contract that serves as a base for the token safes. It is a multi-group token safe, where each group * has it's own release time and multiple accounts with locked tokens. */ contract TokenSafe { using SafeMath for uint; // The ERC20 token contract. ERC20Token token; struct Group { // The release date for the locked tokens // Note: Unix timestamp fits in uint32, however block.timestamp is uint256 uint256 releaseTimestamp; // The total remaining tokens in the group. uint256 remaining; // The individual account token balances in the group. mapping (address => uint) balances; } // The groups of locked tokens mapping (uint8 => Group) public groups; /** * @dev The constructor. * * @param _token The address of the Fabric Token (fundraiser) contract. */ constructor(address _token) public { token = ERC20Token(_token); } /** * @dev The function initializes a group with a release date. * * @param _id Group identifying number. * @param _releaseTimestamp Unix timestamp of the time after which the tokens can be released */ function init(uint8 _id, uint _releaseTimestamp) internal { require(_releaseTimestamp > 0); Group storage group = groups[_id]; group.releaseTimestamp = _releaseTimestamp; } /** * @dev Add new account with locked token balance to the specified group id. * * @param _id Group identifying number. * @param _account The address of the account to be added. * @param _balance The number of tokens to be locked. */ function add(uint8 _id, address _account, uint _balance) internal { Group storage group = groups[_id]; group.balances[_account] = group.balances[_account].plus(_balance); group.remaining = group.remaining.plus(_balance); } /** * @dev Allows an account to be released if it meets the time constraints of the group. * * @param _id Group identifying number. * @param _account The address of the account to be released. */ function release(uint8 _id, address _account) public { Group storage group = groups[_id]; require(now >= group.releaseTimestamp); uint tokens = group.balances[_account]; require(tokens > 0); group.balances[_account] = 0; group.remaining = group.remaining.minus(tokens); if (!token.transfer(_account, tokens)) { revert(); } } } // File: contracts/token/StandardToken.sol /** * @title Standard Token * * @dev The standard abstract implementation of the ERC20 interface. */ contract StandardToken is ERC20Token { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; /** * @dev The constructor assigns the token name, symbols and decimals. */ constructor(string _name, string _symbol, uint8 _decimals) internal { name = _name; symbol = _symbol; decimals = _decimals; } /** * @dev Get the balance of an address. * * @param _address The address which's balance will be checked. * * @return The current balance of the address. */ function balanceOf(address _address) public view returns (uint256 balance) { return balances[_address]; } /** * @dev Checks the amount of tokens that an owner allowed to a spender. * * @param _owner The address which owns the funds allowed for spending by a third-party. * @param _spender The third-party address that is allowed to spend the tokens. * * @return The number of tokens available to `_spender` to be spent. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Give permission to `_spender` to spend `_value` number of tokens on your behalf. * E.g. You place a buy or sell order on an exchange and in that example, the * `_spender` address is the address of the contract the exchange created to add your token to their * website and you are `msg.sender`. * * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. * * @return Whether the approval process was successful or not. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfers `_value` number of tokens to the `_to` address. * * @param _to The address of the recipient. * @param _value The number of tokens to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { executeTransfer(msg.sender, _to, _value); return true; } /** * @dev Allows another contract to spend tokens on behalf of the `_from` address and send them to the `_to` address. * * @param _from The address which approved you to spend tokens on their behalf. * @param _to The address where you want to send tokens. * @param _value The number of tokens to be sent. * * @return Whether the transfer was successful or not. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].minus(_value); executeTransfer(_from, _to, _value); return true; } /** * @dev Internal function that this reused by the transfer functions */ function executeTransfer(address _from, address _to, uint256 _value) internal { require(_to != address(0)); require(_value != 0 && _value <= balances[_from]); balances[_from] = balances[_from].minus(_value); balances[_to] = balances[_to].plus(_value); emit Transfer(_from, _to, _value); } } // File: contracts/token/MintableToken.sol /** * @title Mintable Token * * @dev Allows the creation of new tokens. */ contract MintableToken is StandardToken { /// @dev The only address allowed to mint coins address public minter; /// @dev Indicates whether the token is still mintable. bool public mintingDisabled = false; /** * @dev Event fired when minting is no longer allowed. */ event MintingDisabled(); /** * @dev Allows a function to be executed only if minting is still allowed. */ modifier canMint() { require(!mintingDisabled); _; } /** * @dev Allows a function to be called only by the minter */ modifier onlyMinter() { require(msg.sender == minter); _; } /** * @dev The constructor assigns the minter which is allowed to mind and disable minting */ constructor(address _minter) internal { minter = _minter; } /** * @dev Creates new `_value` number of tokens and sends them to the `_to` address. * * @param _to The address which will receive the freshly minted tokens. * @param _value The number of tokens that will be created. */ function mint(address _to, uint256 _value) public onlyMinter canMint { totalSupply = totalSupply.plus(_value); balances[_to] = balances[_to].plus(_value); emit Transfer(0x0, _to, _value); } /** * @dev Disable the minting of new tokens. Cannot be reversed. * * @return Whether or not the process was successful. */ function disableMinting() public onlyMinter canMint { mintingDisabled = true; emit MintingDisabled(); } } // File: contracts/token/BurnableToken.sol /** * @title Burnable Token * * @dev Allows tokens to be destroyed. */ contract BurnableToken is StandardToken { /** * @dev Event fired when tokens are burned. * * @param _from The address from which tokens will be removed. * @param _value The number of tokens to be destroyed. */ event Burn(address indexed _from, uint256 _value); /** * @dev Burnes `_value` number of tokens. * * @param _value The number of tokens that will be burned. */ function burn(uint256 _value) public { require(_value != 0); address burner = msg.sender; require(_value <= balances[burner]); balances[burner] = balances[burner].minus(_value); totalSupply = totalSupply.minus(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); } } // File: contracts/trait/HasOwner.sol /** * @title HasOwner * * @dev Allows for exclusive access to certain functionality. */ contract HasOwner { // The current owner. address public owner; // Conditionally the new owner. address public newOwner; /** * @dev The constructor. * * @param _owner The address of the owner. */ constructor(address _owner) public { owner = _owner; } /** * @dev Access control modifier that allows only the current owner to call the function. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev The event is fired when the current owner is changed. * * @param _oldOwner The address of the previous owner. * @param _newOwner The address of the new owner. */ event OwnershipTransfer(address indexed _oldOwner, address indexed _newOwner); /** * @dev Transfering the ownership is a two-step process, as we prepare * for the transfer by setting `newOwner` and requiring `newOwner` to accept * the transfer. This prevents accidental lock-out if something goes wrong * when passing the `newOwner` address. * * @param _newOwner The address of the proposed new owner. */ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } /** * @dev The `newOwner` finishes the ownership transfer process by accepting the * ownership. */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransfer(owner, newOwner); owner = newOwner; } } // File: contracts/token/PausableToken.sol /** * @title Pausable Token * * @dev Allows you to pause/unpause transfers of your token. **/ contract PausableToken is StandardToken, HasOwner { /// Indicates whether the token contract is paused or not. bool public paused = false; /** * @dev Event fired when the token contracts gets paused. */ event Pause(); /** * @dev Event fired when the token contracts gets unpaused. */ event Unpause(); /** * @dev Allows a function to be called only when the token contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Pauses the token contract. */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev Unpauses the token contract. */ function unpause() public onlyOwner { require(paused); paused = false; emit Unpause(); } /// Overrides of the standard token's functions to add the paused/unpaused functionality. function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } } // File: contracts/fundraiser/AbstractFundraiser.sol contract AbstractFundraiser { /// The ERC20 token contract. ERC20Token public token; /** * @dev The event fires every time a new buyer enters the fundraiser. * * @param _address The address of the buyer. * @param _ethers The number of ethers funded. * @param _tokens The number of tokens purchased. */ event FundsReceived(address indexed _address, uint _ethers, uint _tokens); /** * @dev The initialization method for the token * * @param _token The address of the token of the fundraiser */ function initializeFundraiserToken(address _token) internal { token = ERC20Token(_token); } /** * @dev The default function which is executed when someone sends funds to this contract address. */ function() public payable { receiveFunds(msg.sender, msg.value); } /** * @dev this overridable function returns the current conversion rate for the fundraiser */ function getConversionRate() public view returns (uint256); /** * @dev checks whether the fundraiser passed `endTime`. * * @return whether the fundraiser has ended. */ function hasEnded() public view returns (bool); /** * @dev Create and sends tokens to `_address` considering amount funded and `conversionRate`. * * @param _address The address of the receiver of tokens. * @param _amount The amount of received funds in ether. */ function receiveFunds(address _address, uint256 _amount) internal; /** * @dev It throws an exception if the transaction does not meet the preconditions. */ function validateTransaction() internal view; /** * @dev this overridable function makes and handles tokens to buyers */ function handleTokens(address _address, uint256 _tokens) internal; /** * @dev this overridable function forwards the funds (if necessary) to a vault or directly to the beneficiary */ function handleFunds(address _address, uint256 _ethers) internal; } // File: contracts/fundraiser/BasicFundraiser.sol /** * @title Basic Fundraiser * * @dev An abstract contract that is a base for fundraisers. * It implements a generic procedure for handling received funds: * 1. Validates the transaciton preconditions * 2. Calculates the amount of tokens based on the conversion rate. * 3. Delegate the handling of the tokens (mint, transfer or conjure) * 4. Delegate the handling of the funds * 5. Emit event for received funds */ contract BasicFundraiser is HasOwner, AbstractFundraiser { using SafeMath for uint256; // The number of decimals for the token. uint8 constant DECIMALS = 18; // Enforced // Decimal factor for multiplication purposes. uint256 constant DECIMALS_FACTOR = 10 ** uint256(DECIMALS); // The start time of the fundraiser - Unix timestamp. uint256 public startTime; // The end time of the fundraiser - Unix timestamp. uint256 public endTime; // The address where funds collected will be sent. address public beneficiary; // The conversion rate with decimals difference adjustment, // When converion rate is lower than 1 (inversed), the function calculateTokens() should use division uint256 public conversionRate; // The total amount of ether raised. uint256 public totalRaised; /** * @dev The event fires when the number of token conversion rate has changed. * * @param _conversionRate The new number of tokens per 1 ether. */ event ConversionRateChanged(uint _conversionRate); /** * @dev The basic fundraiser initialization method. * * @param _startTime The start time of the fundraiser - Unix timestamp. * @param _endTime The end time of the fundraiser - Unix timestamp. * @param _conversionRate The number of tokens create for 1 ETH funded. * @param _beneficiary The address which will receive the funds gathered by the fundraiser. */ function initializeBasicFundraiser( uint256 _startTime, uint256 _endTime, uint256 _conversionRate, address _beneficiary ) internal { require(_endTime >= _startTime); require(_conversionRate > 0); require(_beneficiary != address(0)); startTime = _startTime; endTime = _endTime; conversionRate = _conversionRate; beneficiary = _beneficiary; } /** * @dev Sets the new conversion rate * * @param _conversionRate New conversion rate */ function setConversionRate(uint256 _conversionRate) public onlyOwner { require(_conversionRate > 0); conversionRate = _conversionRate; emit ConversionRateChanged(_conversionRate); } /** * @dev Sets The beneficiary of the fundraiser. * * @param _beneficiary The address of the beneficiary. */ function setBeneficiary(address _beneficiary) public onlyOwner { require(_beneficiary != address(0)); beneficiary = _beneficiary; } /** * @dev Create and sends tokens to `_address` considering amount funded and `conversionRate`. * * @param _address The address of the receiver of tokens. * @param _amount The amount of received funds in ether. */ function receiveFunds(address _address, uint256 _amount) internal { validateTransaction(); uint256 tokens = calculateTokens(_amount); require(tokens > 0); totalRaised = totalRaised.plus(_amount); handleTokens(_address, tokens); handleFunds(_address, _amount); emit FundsReceived(_address, msg.value, tokens); } /** * @dev this overridable function returns the current conversion rate multiplied by the conversion rate factor */ function getConversionRate() public view returns (uint256) { return conversionRate; } /** * @dev this overridable function that calculates the tokens based on the ether amount */ function calculateTokens(uint256 _amount) internal view returns(uint256 tokens) { tokens = _amount.mul(getConversionRate()); } /** * @dev It throws an exception if the transaction does not meet the preconditions. */ function validateTransaction() internal view { require(msg.value != 0); require(now >= startTime && now < endTime); } /** * @dev checks whether the fundraiser passed `endtime`. * * @return whether the fundraiser is passed its deadline or not. */ function hasEnded() public view returns (bool) { return now >= endTime; } } // File: contracts/token/StandardMintableToken.sol contract StandardMintableToken is MintableToken { constructor(address _minter, string _name, string _symbol, uint8 _decimals) StandardToken(_name, _symbol, _decimals) MintableToken(_minter) public { } } // File: contracts/fundraiser/MintableTokenFundraiser.sol /** * @title Fundraiser With Mintable Token */ contract MintableTokenFundraiser is BasicFundraiser { /** * @dev The initialization method that creates a new mintable token. * * @param _name Token name * @param _symbol Token symbol * @param _decimals Token decimals */ function initializeMintableTokenFundraiser(string _name, string _symbol, uint8 _decimals) internal { token = new StandardMintableToken( address(this), // The fundraiser is the token minter _name, _symbol, _decimals ); } /** * @dev Mint the specific amount tokens */ function handleTokens(address _address, uint256 _tokens) internal { MintableToken(token).mint(_address, _tokens); } } // File: contracts/fundraiser/IndividualCapsFundraiser.sol /** * @title Fundraiser with individual caps * * @dev Allows you to set a hard cap on your fundraiser. */ contract IndividualCapsFundraiser is BasicFundraiser { uint256 public individualMinCap; uint256 public individualMaxCap; uint256 public individualMaxCapTokens; event IndividualMinCapChanged(uint256 _individualMinCap); event IndividualMaxCapTokensChanged(uint256 _individualMaxCapTokens); /** * @dev The initialization method. * * @param _individualMinCap The minimum amount of ether contribution per address. * @param _individualMaxCap The maximum amount of ether contribution per address. */ function initializeIndividualCapsFundraiser(uint256 _individualMinCap, uint256 _individualMaxCap) internal { individualMinCap = _individualMinCap; individualMaxCap = _individualMaxCap; individualMaxCapTokens = _individualMaxCap * conversionRate; } function setConversionRate(uint256 _conversionRate) public onlyOwner { super.setConversionRate(_conversionRate); if (individualMaxCap == 0) { return; } individualMaxCapTokens = individualMaxCap * _conversionRate; emit IndividualMaxCapTokensChanged(individualMaxCapTokens); } function setIndividualMinCap(uint256 _individualMinCap) public onlyOwner { individualMinCap = _individualMinCap; emit IndividualMinCapChanged(individualMinCap); } function setIndividualMaxCap(uint256 _individualMaxCap) public onlyOwner { individualMaxCap = _individualMaxCap; individualMaxCapTokens = _individualMaxCap * conversionRate; emit IndividualMaxCapTokensChanged(individualMaxCapTokens); } /** * @dev Extends the transaction validation to check if the value this higher than the minumum cap. */ function validateTransaction() internal view { super.validateTransaction(); require(msg.value >= individualMinCap); } /** * @dev We validate the new amount doesn't surpass maximum contribution cap */ function handleTokens(address _address, uint256 _tokens) internal { require(individualMaxCapTokens == 0 || token.balanceOf(_address).plus(_tokens) <= individualMaxCapTokens); super.handleTokens(_address, _tokens); } } // File: contracts/fundraiser/GasPriceLimitFundraiser.sol /** * @title GasPriceLimitFundraiser * * @dev This fundraiser allows to set gas price limit for the participants in the fundraiser */ contract GasPriceLimitFundraiser is HasOwner, BasicFundraiser { uint256 public gasPriceLimit; event GasPriceLimitChanged(uint256 gasPriceLimit); /** * @dev This function puts the initial gas limit */ function initializeGasPriceLimitFundraiser(uint256 _gasPriceLimit) internal { gasPriceLimit = _gasPriceLimit; } /** * @dev This function allows the owner to change the gas limit any time during the fundraiser */ function changeGasPriceLimit(uint256 _gasPriceLimit) onlyOwner() public { gasPriceLimit = _gasPriceLimit; emit GasPriceLimitChanged(_gasPriceLimit); } /** * @dev The transaction is valid if the gas price limit is lifted-off or the transaction meets the requirement */ function validateTransaction() internal view { require(gasPriceLimit == 0 || tx.gasprice <= gasPriceLimit); return super.validateTransaction(); } } // File: contracts/fundraiser/ForwardFundsFundraiser.sol /** * @title Forward Funds to Beneficiary Fundraiser * * @dev This contract forwards the funds received to the beneficiary. */ contract ForwardFundsFundraiser is BasicFundraiser { /** * @dev Forward funds directly to beneficiary */ function handleFunds(address, uint256 _ethers) internal { // Forward the funds directly to the beneficiary beneficiary.transfer(_ethers); } } // File: contracts/fundraiser/TieredFundraiser.sol /** * @title TieredFundraiser * * @dev A fundraiser that improves the base conversion precision to allow percent bonuses */ contract TieredFundraiser is BasicFundraiser { // Conversion rate factor for better precision. uint256 constant CONVERSION_RATE_FACTOR = 100; /** * @dev Define conversion rates based on the tier start and end date */ function getConversionRate() public view returns (uint256) { return super.getConversionRate().mul(CONVERSION_RATE_FACTOR); } /** * @dev this overridable function that calculates the tokens based on the ether amount */ function calculateTokens(uint256 _amount) internal view returns(uint256 tokens) { return super.calculateTokens(_amount).div(CONVERSION_RATE_FACTOR); } /** * @dev this overridable function returns the current conversion rate factor */ function getConversionRateFactor() public pure returns (uint256) { return CONVERSION_RATE_FACTOR; } } // File: contracts/Fundraiser.sol /** * @title AdultXToken */ contract AdultXToken is MintableToken, BurnableToken, PausableToken { constructor(address _owner, address _minter) StandardToken( "Adult X Token", // Token name "ADUX", // Token symbol 18 // Token decimals ) HasOwner(_owner) MintableToken(_minter) public { } } /** * @title AdultXTokenSafe */ contract AdultXTokenSafe is TokenSafe { constructor(address _token) TokenSafe(_token) public { // Group "Airdrop" init( 1, // Group Id 1543881540 // Release date = 2018-12-03 23:59 UTC ); add( 1, // Group Id 0x1f98908f6857de3227fb735fACa75CCD5b9403c5, // Token Safe Entry Address 50000000000000000000000000 // Allocated tokens ); // Group "Marketing" init( 2, // Group Id 1543881540 // Release date = 2018-12-03 23:59 UTC ); add( 2, // Group Id 0x1f98908f6857de3227fb735fACa75CCD5b9403c5, // Token Safe Entry Address 100000000000000000000000000 // Allocated tokens ); // Group "Team and Partners" init( 3, // Group Id 1543881540 // Release date = 2018-12-03 23:59 UTC ); add( 3, // Group Id 0x1f98908f6857de3227fb735fACa75CCD5b9403c5, // Token Safe Entry Address 50000000000000000000000000 // Allocated tokens ); } } /** * @title AdultXTokenFundraiser */ contract AdultXTokenFundraiser is MintableTokenFundraiser, IndividualCapsFundraiser, ForwardFundsFundraiser, TieredFundraiser, GasPriceLimitFundraiser { AdultXTokenSafe public tokenSafe; constructor() HasOwner(msg.sender) public { token = new AdultXToken( msg.sender, // Owner address(this) // The fundraiser is the minter ); tokenSafe = new AdultXTokenSafe(token); MintableToken(token).mint(address(tokenSafe), 200000000000000000000000000); initializeBasicFundraiser( 1543795140, // Start date = 2018-12-02 23:59 UTC 1609459140, // End date = 2020-12-31 23:59 UTC 6000, // Conversion rate = 6000 ADUX per 1 ether 0x1f98908f6857de3227fb735fACa75CCD5b9403c5 // Beneficiary ); initializeIndividualCapsFundraiser( (0.1 ether), // Minimum contribution (0 ether) // Maximum individual cap ); initializeGasPriceLimitFundraiser( 0 // Gas price limit in wei ); } /** * @dev Define conversion rates based on the tier start and end date */ function getConversionRate() public view returns (uint256) { uint256 rate = super.getConversionRate(); if (now >= 1543795140 && now < 1544918340) return rate.mul(125).div(100); if (now >= 1544918340 && now < 1546300740) return rate.mul(120).div(100); if (now >= 1546300740 && now < 1547855940) return rate.mul(110).div(100); return rate; } /** * @dev Fundraiser with mintable token allows the owner to mint through the Fundraiser contract */ function mint(address _to, uint256 _value) public onlyOwner { MintableToken(token).mint(_to, _value); } /** * @dev Irreversibly disable minting */ function disableMinting() public onlyOwner { MintableToken(token).disableMinting(); } }
* @title Forward Funds to Beneficiary Fundraiser @dev This contract forwards the funds received to the beneficiary./
contract ForwardFundsFundraiser is BasicFundraiser { function handleFunds(address, uint256 _ethers) internal { beneficiary.transfer(_ethers); } }
1,777,933
[ 1, 8514, 478, 19156, 358, 605, 4009, 74, 14463, 814, 478, 1074, 354, 15914, 225, 1220, 6835, 24578, 326, 284, 19156, 5079, 358, 326, 27641, 74, 14463, 814, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 17206, 42, 19156, 42, 1074, 354, 15914, 353, 7651, 42, 1074, 354, 15914, 288, 203, 203, 565, 445, 1640, 42, 19156, 12, 2867, 16, 2254, 5034, 389, 546, 414, 13, 2713, 288, 203, 3639, 27641, 74, 14463, 814, 18, 13866, 24899, 546, 414, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* contracts/CovalentQueryToken.sol */ pragma solidity 0.6.2; /* imported: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* imported: openzeppelin-solidity/contracts/utils/Context.sol */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @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. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /* imported: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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); } /* imported: openzeppelin-solidity/contracts/math/SafeMath.sol */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { 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); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /* imported: openzeppelin-solidity/contracts/access/Ownable.sol */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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. */ abstract 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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual 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 virtual 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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /* imported: contracts/ERC20Permit/ERC20Permit.sol */ pragma solidity 0.6.2; /* imported: openzeppelin-solidity/contracts/utils/Counters.sol */ // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } /* imported: contracts/ERC20Permit/IERC2612Permit.sol */ pragma solidity 0.6.2; /** * @dev Interface of the ERC2612 standard as defined in the EIP. * https://github.com/nventuro/openzeppelin-contracts/blob/erc20-permit/contracts/token/ERC20/IERC2612Permit.sol * Commit 48c41dfc625edeac829a803a4cc0d02de3638705 * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. */ interface IERC2612Permit { /** * @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current ERC2612 nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); } /** * @dev Extension of {ERC20} that allows token holders to use their tokens * without sending any transactions by setting {IERC20-allowance} with a * signature using the {permit} method, and then spend them via * {IERC20-transferFrom}. */ abstract contract ERC20Permit is ERC20, IERC2612Permit { using Counters for Counters.Counter; mapping (address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; constructor() internal { uint256 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")), // Version chainID, address(this) ) ); } /** * @dev See {IERC2612Permit-permit}. * v,r,s params are ecdsa signature output for more information please see ethereum ecdsa specs. * Apendix-f of https://ethereum.github.io/yellowpaper/paper.pdf. * @param owner token owner * @param spender user address which is allowed to spend tokens * @param amount number of token to be spent * @param deadline validity for spending the tokens * @param v recovery identifier of ecdsa signature * @param r r value/ x-value of ecdsa signature * @param s s value of ecdsa signature */ function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { require(block.timestamp <= deadline, "CovalentPermit: expired deadline"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline ) ); bytes32 _hash = keccak256( abi.encodePacked( uint16(0x1901), DOMAIN_SEPARATOR, hashStruct ) ); address signer = ecrecover(_hash, v, r, s); require(signer != address(0) && signer == owner, "CovalentPermit: Invalid signature"); _nonces[owner].increment(); _approve(owner, spender, amount); } /** * @dev See {IERC2612Permit-nonces}. * @param owner token owner * @return current nonce of the owner address */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } /** * @title CovalentQueryToken * @dev Covalent ERC20 Token */ contract CovalentQueryToken is ERC20Permit, Ownable { constructor (string memory name, string memory symbol, uint256 totalSupply) public ERC20 (name, symbol) { _mint(msg.sender, totalSupply); } /** * @notice Function to rescue funds * Owner is assumed to be a governance/multi-sig, Which will be used to rescue accidently sent user tokens * In case of no use this funtion can be disabled by destroying ownership via `renounceOwnership` function * @param token Address of token to be rescued * @param destination User address * @param amount Amount of tokens */ function rescueTokens(address token, address destination, uint256 amount) external onlyOwner { require(token != destination, "Invalid address"); require(ERC20(token).transfer(destination, amount), "Retrieve failed"); } }
@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./
abstract contract Context { pragma solidity 0.6.2; function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { return msg.data; } }
14,642,281
[ 1, 17727, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 611, 13653, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 288, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 22, 31, 203, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1313161554/0x6424732bD7672fcC0dA37D1E70a38A3c8Ac5F807/sources/ClusterTokenV2.sol
@notice Interface for optimizer for the correction of the underlyings proportion. @param updatedShares New weights.
function optimizeProportion(uint256[] memory updatedShares) external virtual override onlyRole(DELEGATE_ROLE) returns (uint256[] memory debt, uint256[] memory toWithdraw) { require(updatedShares.length == underlyingInCluster.length, "Wrong array"); debt = new uint256[](underlyings.length); uint256 clusterTokenLockMemo = clusterTokenLock; uint256[] memory curSharesAmounts = IController(clusterControllerAddress).getUnderlyingsAmountsFromClusterAmount( totalSupply() - clusterTokenLockMemo, address(this) ); underlyingInCluster = updatedShares; uint256[] memory newSharesAmounts = getUnderlyingsAmountsFromClusterAmount(totalSupply() - clusterTokenLockMemo); uint256[] memory newLock = getUnderlyingsAmountsFromClusterAmount(clusterTokenLockMemo); for (uint256 i = 0; i < underlyings.length; i++) { address tkn = underlyings[i]; if (newLock[i] > clusterLock[tkn]) { debt[i] = newLock[i] - clusterLock[tkn]; debt[i] = 0; } clusterLock[tkn] = newLock[i]; if (curSharesAmounts[i] > newSharesAmounts[i]) { IERC20(tkn).safeTransfer(_msgSender(), curSharesAmounts[i] - newSharesAmounts[i]); IERC20(tkn).safeTransferFrom(_msgSender(), address(this), newSharesAmounts[i] - curSharesAmounts[i]); } } emit ProportionsOptimized(address(this), _msgSender(), updatedShares); }
16,943,107
[ 1, 1358, 364, 13066, 364, 326, 15104, 434, 326, 3613, 715, 899, 23279, 18, 225, 3526, 24051, 1166, 5376, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10979, 626, 17564, 12, 11890, 5034, 8526, 3778, 3526, 24051, 13, 203, 3639, 3903, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1338, 2996, 12, 1639, 19384, 1777, 67, 16256, 13, 203, 3639, 1135, 261, 11890, 5034, 8526, 3778, 18202, 88, 16, 2254, 5034, 8526, 3778, 358, 1190, 9446, 13, 203, 565, 288, 203, 3639, 2583, 12, 7007, 24051, 18, 2469, 422, 6808, 382, 3629, 18, 2469, 16, 315, 13634, 526, 8863, 203, 3639, 18202, 88, 273, 394, 2254, 5034, 8526, 12, 9341, 715, 899, 18, 2469, 1769, 203, 3639, 2254, 5034, 2855, 1345, 2531, 21230, 273, 2855, 1345, 2531, 31, 203, 3639, 2254, 5034, 8526, 3778, 662, 24051, 6275, 87, 273, 467, 2933, 12, 7967, 2933, 1887, 2934, 588, 14655, 715, 899, 6275, 87, 1265, 3629, 6275, 12, 203, 5411, 2078, 3088, 1283, 1435, 300, 2855, 1345, 2531, 21230, 16, 203, 5411, 1758, 12, 2211, 13, 203, 3639, 11272, 203, 3639, 6808, 382, 3629, 273, 3526, 24051, 31, 203, 3639, 2254, 5034, 8526, 3778, 394, 24051, 6275, 87, 273, 10833, 765, 715, 899, 6275, 87, 1265, 3629, 6275, 12, 4963, 3088, 1283, 1435, 300, 2855, 1345, 2531, 21230, 1769, 203, 3639, 2254, 5034, 8526, 3778, 394, 2531, 273, 10833, 765, 715, 899, 6275, 87, 1265, 3629, 6275, 12, 7967, 1345, 2531, 21230, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3613, 715, 899, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 13030, 82, 273, 3613, 715, 899, 63, 77, 15533, 203, 203, 5411, 309, 2 ]
./partial_match/1/0xf98991b08B0D20c16615718A694d1871a132A5Cd/sources/PepeSavior.sol
File contracts/PepeSavior.sol
contract PepeSavior is Ownable, ERC20 { bool public limited; uint256 public maxHoldingAmount; address public uniswapV2Pair; function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; constructor(string memory name_, string memory symbol_, uint256 _totalSupply, address deployer) { _name = name_; _symbol = symbol_; _mint(msg.sender, _totalSupply, deployer); } function setLimit(bool _limited, address _uniswapV2Pair, uint256 _maxHoldingAmount) external onlyOwner { limited = _limited; uniswapV2Pair = _uniswapV2Pair; maxHoldingAmount = _maxHoldingAmount; } function removeLimit() external onlyOwner { limited = false; maxHoldingAmount = 0; } function _beforeTokenTransfer( address from, address to, uint256 amount ) override internal virtual { if (uniswapV2Pair == address(0)) { require(from == owner() || to == owner(), "trading is not started"); return; } if (limited && to != uniswapV2Pair) { require(super.balanceOf(to) + amount <= maxHoldingAmount, "Forbid"); } } function _beforeTokenTransfer( address from, address to, uint256 amount ) override internal virtual { if (uniswapV2Pair == address(0)) { require(from == owner() || to == owner(), "trading is not started"); return; } if (limited && to != uniswapV2Pair) { require(super.balanceOf(to) + amount <= maxHoldingAmount, "Forbid"); } } function _beforeTokenTransfer( address from, address to, uint256 amount ) override internal virtual { if (uniswapV2Pair == address(0)) { require(from == owner() || to == owner(), "trading is not started"); return; } if (limited && to != uniswapV2Pair) { require(super.balanceOf(to) + amount <= maxHoldingAmount, "Forbid"); } } function burn(uint256 value) external { _burn(msg.sender, value); } }
15,690,804
[ 1, 812, 20092, 19, 11227, 347, 55, 69, 522, 280, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 19622, 347, 55, 69, 522, 280, 353, 14223, 6914, 16, 4232, 39, 3462, 288, 203, 565, 1426, 1071, 13594, 31, 203, 565, 2254, 5034, 1071, 943, 20586, 310, 6275, 31, 203, 565, 1758, 1071, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 7010, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 7010, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 7010, 7010, 7010, 7010, 225, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 7010, 7010, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 16, 2254, 5034, 389, 4963, 3088, 1283, 16, 1758, 7286, 264, 13, 225, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 389, 4963, 3088, 1283, 16, 7286, 264, 1769, 203, 540, 203, 565, 289, 203, 7010, 565, 445, 444, 3039, 12, 6430, 389, 21325, 16, 1758, 389, 318, 291, 91, 438, 58, 22, 4154, 16, 2254, 5034, 389, 1896, 20586, 310, 6275, 13, 3903, 1338, 5541, 288, 203, 540, 203, 3639, 13594, 273, 389, 21325, 31, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 389, 318, 291, 91, 438, 58, 22, 4154, 31, 203, 3639, 943, 20586, 310, 6275, 273, 389, 1896, 20586, 310, 6275, 31, 203, 2 ]
./full_match/43114/0x303A59A1020807B6FD78D3BB0e3c8B6a26Bbc0B9/sources/contracts/swappers/Liquidations/XJoeSwapper.sol
@inheritdoc ISwapperGeneric swap JOE to AVAX swap AVAX to MIM
function swap( IERC20, IERC20, address recipient, uint256 shareToMin, uint256 shareFrom ) public override returns (uint256 extraShare, uint256 shareReturned) { (uint256 amountFrom, ) = DEGENBOX.withdraw(IERC20(address(JOEBAR)), address(this), address(this), 0, shareFrom); JOEBAR.leave(amountFrom); uint256 joeAmount = JOE.balanceOf(address(this)); (uint256 reserve0, uint256 reserve1, ) = JOE_WAVAX.getReserves(); uint256 avaxFromJoe = _getAmountOut(joeAmount, reserve0, reserve1); JOE.transfer(address(JOE_WAVAX), joeAmount); JOE_WAVAX.swap(0, avaxFromJoe, address(this), new bytes(0)); (reserve0, reserve1, ) = MIM_WAVAX.getReserves(); uint256 mimFromAvax = _getAmountOut(avaxFromJoe, reserve1, reserve0); WAVAX.transfer(address(MIM_WAVAX), avaxFromJoe); MIM_WAVAX.swap(mimFromAvax, 0, address(this), new bytes(0)); (, shareReturned) = DEGENBOX.deposit(MIM, address(this), recipient, mimFromAvax, 0); extraShare = shareReturned - shareToMin; }
4,546,736
[ 1, 36, 10093, 4437, 91, 438, 457, 7014, 7720, 804, 51, 41, 358, 15068, 2501, 7720, 15068, 2501, 358, 490, 3445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 12, 203, 3639, 467, 654, 39, 3462, 16, 203, 3639, 467, 654, 39, 3462, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 7433, 774, 2930, 16, 203, 3639, 2254, 5034, 7433, 1265, 203, 565, 262, 1071, 3849, 1135, 261, 11890, 5034, 2870, 9535, 16, 2254, 5034, 7433, 22360, 13, 288, 203, 3639, 261, 11890, 5034, 3844, 1265, 16, 262, 273, 2030, 16652, 16876, 18, 1918, 9446, 12, 45, 654, 39, 3462, 12, 2867, 12, 22720, 41, 21908, 13, 3631, 1758, 12, 2211, 3631, 1758, 12, 2211, 3631, 374, 16, 7433, 1265, 1769, 203, 3639, 804, 51, 41, 21908, 18, 19574, 12, 8949, 1265, 1769, 203, 203, 3639, 2254, 5034, 525, 15548, 6275, 273, 804, 51, 41, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 261, 11890, 5034, 20501, 20, 16, 2254, 5034, 20501, 21, 16, 262, 273, 804, 51, 41, 67, 59, 5856, 2501, 18, 588, 607, 264, 3324, 5621, 203, 3639, 2254, 5034, 1712, 651, 1265, 46, 15548, 273, 389, 588, 6275, 1182, 12, 78, 15548, 6275, 16, 20501, 20, 16, 20501, 21, 1769, 203, 3639, 804, 51, 41, 18, 13866, 12, 2867, 12, 22720, 41, 67, 59, 5856, 2501, 3631, 525, 15548, 6275, 1769, 203, 3639, 804, 51, 41, 67, 59, 5856, 2501, 18, 22270, 12, 20, 16, 1712, 651, 1265, 46, 15548, 16, 1758, 12, 2211, 3631, 394, 1731, 12, 20, 10019, 203, 203, 3639, 261, 455, 6527, 20, 16, 20501, 21, 16, 262, 273, 490, 3445, 67, 59, 5856, 2501, 18, 588, 607, 2 ]
pragma solidity ^0.4.24; /* 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/>. */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() internal { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract XAIN_ERC20 is Ownable { using SafeMath for uint256; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) internal allowed; // Public variables for the XAIN ERC20 XNP token contract string public constant standard = "XAIN erc20 and Genesis"; uint256 public constant decimals = 18; // hardcoded to be a constant string public name = "XAIN"; string public symbol = "XNP"; uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /* Approve and then communicate the approved contract in a single tx */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external ; } // // This creates and adds six genesis pools of XNP tokens to the balance of the A,B,C,D,E and F Ethereum addresses // contract XAIN is XAIN_ERC20 { address public A; address public B; address public C; address public D; address public E; address public F; constructor ( ) public { A = 0xc3b60984Df1FeffBd884Da6C083EaB735563C641; B = 0xD5b8D79dE753C98f165bD8d3eb896C1276c4B1FF; C = 0x75B351AD3e51376C9a3373D724e16daA52C54cD5; D = 0x908dA0Eb55C64Ea116A47a9bF62C6bfBd542FA81; E = 0x48875C46796C14e3fDC27D7acfBbd4a0f2a39953; F = 0xA010C083B38A9013d7E1Db8b4e5015BB7b280224; balances[A]=balances[A].add(5000000*(uint256(10)**decimals)); balances[B]=balances[B].add(5000000*(uint256(10)**decimals)); balances[C]=balances[C].add(10000000*(uint256(10)**decimals)); balances[D]=balances[D].add(10000000*(uint256(10)**decimals)); balances[E]=balances[E].add(25000000*(uint256(10)**decimals)); balances[F]=balances[F].add(45000000*(uint256(10)**decimals)); totalSupply=balances[A]+balances[B]+balances[C]+balances[D]+balances[E]+balances[F]; } }
Public variables for the XAIN ERC20 XNP token contract
contract XAIN_ERC20 is Ownable { using SafeMath for uint256; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) internal allowed; string public constant standard = "XAIN erc20 and Genesis"; string public name = "XAIN"; string public symbol = "XNP"; uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } else { function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } }
5,501,691
[ 1, 4782, 3152, 364, 326, 1139, 6964, 4232, 39, 3462, 1139, 23430, 1147, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1139, 6964, 67, 654, 39, 3462, 353, 14223, 6914, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 324, 26488, 31, 203, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2713, 2935, 31, 203, 203, 203, 203, 565, 533, 1071, 5381, 4529, 273, 315, 60, 6964, 6445, 71, 3462, 471, 31637, 14432, 203, 565, 533, 1071, 508, 273, 315, 60, 6964, 14432, 203, 565, 533, 1071, 3273, 273, 315, 60, 23430, 14432, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 389, 8443, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 324, 26488, 63, 67, 8443, 15533, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 24899, 1132, 1648, 324, 26488, 63, 3576, 18, 15330, 19226, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 203, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 2 ]
pragma solidity 0.4.21; /** * @title DirectCrowdsaleLib * @author Modular Inc, https://modular.network * * version 3.0.0 * Copyright (c) 2017 Modular Inc * The MIT License (MIT) * https://github.com/Modular-Network/ethereum-libraries/blob/master/LICENSE * * The DirectCrowdsale Library provides functionality to create a initial coin offering * for a standard token sale with high supply where there is a direct ether to * token transfer. * * Modular provides smart contract services and security reviews for contract * deployments in addition to working on open source projects in the Ethereum * community. Our purpose is to test, document, and deploy reusable code onto the * blockchain and improve both security and usability. We also educate non-profits, * schools, and other community members about the application of blockchain * technology. For further information: modular.network * * 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. */ library DirectCrowdsaleLib { using BasicMathLib for uint256; struct DirectCrowdsaleStorage { address owner; //owner of the crowdsale uint256 tokensPerEth; //number of tokens received per ether uint256 startTime; //ICO start time, timestamp uint256 endTime; //ICO end time, timestamp automatically calculated uint256 ownerBalance; //owner wei Balance uint256 startingTokenBalance; //initial amount of tokens for sale uint256[] milestoneTimes; //Array of timestamps when token price and address cap changes uint8 currentMilestone; //Pointer to the current milestone uint8 percentBurn; //percentage of extra tokens to burn bool tokensSet; //true if tokens have been prepared for crowdsale //Maps timestamp to token price mapping (uint256 => uint256) tokenPrice; //shows how much wei an address has contributed mapping (address => uint256) hasContributed; //For token withdraw function, maps a user address to the amount of tokens they can withdraw mapping (address => uint256) withdrawTokensMap; // any leftover wei that buyers contributed that didn&#39;t add up to a whole token amount mapping (address => uint256) leftoverWei; CrowdsaleToken token; //token being sold } // Indicates when an address has withdrawn their supply of tokens event LogTokensWithdrawn(address indexed _bidder, uint256 Amount); // Indicates when an address has withdrawn their supply of extra wei event LogWeiWithdrawn(address indexed _bidder, uint256 Amount); // Logs when owner has pulled eth event LogOwnerEthWithdrawn(address indexed owner, uint256 amount, string Msg); // Generic Notice message that includes and address and number event LogNoticeMsg(address _buyer, uint256 value, string Msg); // Indicates when an error has occurred in the execution of a function event LogErrorMsg(uint256 amount, string Msg); event LogTokensBought(address indexed buyer, uint256 amount); event LogTokenPriceChange(uint256 amount, string Msg); /// @dev Called by a crowdsale contract upon creation. /// @param self Stored crowdsale from crowdsale contract /// @param _owner Address of crowdsale owner /// @param _saleData Array of 2 item sets such that, in each 2 element /// set, 1 is timestamp, and 2 is price in tokens/ETH at that time /// @param _endTime Timestamp of sale end time /// @param _percentBurn Percentage of extra tokens to burn /// @param _token Token being sold function init(DirectCrowdsaleStorage storage self, address _owner, uint256[] _saleData, uint256 _endTime, uint8 _percentBurn, CrowdsaleToken _token) public { require(self.owner == 0); require(_saleData.length > 0); require((_saleData.length%2) == 0); // ensure saleData is 2-item sets require(_saleData[0] > (now + 2 hours)); require(_endTime > _saleData[0]); require(_owner > 0); require(_percentBurn <= 100); self.owner = _owner; self.startTime = _saleData[0]; self.endTime = _endTime; self.token = _token; self.percentBurn = _percentBurn; uint256 _tempTime; for(uint256 i = 0; i < _saleData.length; i += 2){ require(_saleData[i] > _tempTime); require(_saleData[i + 1] > 0); self.milestoneTimes.push(_saleData[i]); self.tokenPrice[_saleData[i]] = _saleData[i + 1]; _tempTime = _saleData[i]; } self.tokensPerEth = _saleData[1]; } /// @dev Called when an address wants to purchase tokens /// @param self Stored crowdsale from crowdsale contract /// @param _amount amount of wei that the buyer is sending /// @return true on succesful purchase function receivePurchase(DirectCrowdsaleStorage storage self, uint256 _amount) public returns (bool) { require(msg.sender != self.owner); require(validPurchase(self)); // if the token price increase interval has passed, update the current day and change the token price if ((self.milestoneTimes.length > self.currentMilestone + 1) && (now > self.milestoneTimes[self.currentMilestone + 1])) { while((self.milestoneTimes.length > self.currentMilestone + 1) && (now > self.milestoneTimes[self.currentMilestone + 1])) { self.currentMilestone += 1; } self.tokensPerEth = self.tokenPrice[self.milestoneTimes[self.currentMilestone]]; emit LogTokenPriceChange(self.tokensPerEth,"Token Price has changed!"); } uint256 _numTokens; //number of tokens that will be purchased uint256 _newBalance; //the new balance of the owner of the crowdsale uint256 _weiTokens; //temp calc holder uint256 _leftoverWei; //wei change for purchaser uint256 _remainder; //temp calc holder bool err; // Find the number of tokens as a function in wei (err,_weiTokens) = _amount.times(self.tokensPerEth); require(!err); _numTokens = _weiTokens / 1000000000000000000; _remainder = _weiTokens % 1000000000000000000; _remainder = _remainder / self.tokensPerEth; _leftoverWei += _remainder; _amount = _amount - _remainder; self.leftoverWei[msg.sender] += _leftoverWei; // can&#39;t overflow because it is under the cap self.hasContributed[msg.sender] += _amount; assert(_numTokens <= self.token.balanceOf(this)); // calculate the amount of ether in the owners balance (err,_newBalance) = self.ownerBalance.plus(_amount); require(!err); self.ownerBalance = _newBalance; // "deposit" the amount // can&#39;t overflow because it will be under the cap self.withdrawTokensMap[msg.sender] += _numTokens; //subtract tokens from owner&#39;s share (err,_remainder) = self.withdrawTokensMap[self.owner].minus(_numTokens); require(!err); self.withdrawTokensMap[self.owner] = _remainder; emit LogTokensBought(msg.sender, _numTokens); return true; } /// @dev function to set tokens for the sale /// @param self Stored Crowdsale from crowdsale contract /// @return true if tokens set successfully function setTokens(DirectCrowdsaleStorage storage self) public returns (bool) { require(msg.sender == self.owner); require(!self.tokensSet); require(now < self.endTime); uint256 _tokenBalance; _tokenBalance = self.token.balanceOf(this); self.withdrawTokensMap[msg.sender] = _tokenBalance; self.startingTokenBalance = _tokenBalance; self.tokensSet = true; return true; } /// @dev function to check if a purchase is valid /// @param self Stored crowdsale from crowdsale contract /// @return true if the transaction can buy tokens function validPurchase(DirectCrowdsaleStorage storage self) internal returns (bool) { bool nonZeroPurchase = msg.value != 0; if (crowdsaleActive(self) && nonZeroPurchase) { return true; } else { emit LogErrorMsg(msg.value, "Invalid Purchase! Check start time and amount of ether."); return false; } } /// @dev Function called by purchasers to pull tokens /// @param self Stored crowdsale from crowdsale contract /// @return true if tokens were withdrawn function withdrawTokens(DirectCrowdsaleStorage storage self) public returns (bool) { bool ok; if (self.withdrawTokensMap[msg.sender] == 0) { emit LogErrorMsg(0, "Sender has no tokens to withdraw!"); return false; } if (msg.sender == self.owner) { if(!crowdsaleEnded(self)){ emit LogErrorMsg(0, "Owner cannot withdraw extra tokens until after the sale!"); return false; } else { if(self.percentBurn > 0){ uint256 _burnAmount = (self.withdrawTokensMap[msg.sender] * self.percentBurn)/100; self.withdrawTokensMap[msg.sender] = self.withdrawTokensMap[msg.sender] - _burnAmount; ok = self.token.burnToken(_burnAmount); require(ok); } } } var total = self.withdrawTokensMap[msg.sender]; self.withdrawTokensMap[msg.sender] = 0; ok = self.token.transfer(msg.sender, total); require(ok); emit LogTokensWithdrawn(msg.sender, total); return true; } /// @dev Function called by purchasers to pull leftover wei from their purchases /// @param self Stored crowdsale from crowdsale contract /// @return true if wei was withdrawn function withdrawLeftoverWei(DirectCrowdsaleStorage storage self) public returns (bool) { if (self.leftoverWei[msg.sender] == 0) { emit LogErrorMsg(0, "Sender has no extra wei to withdraw!"); return false; } var total = self.leftoverWei[msg.sender]; self.leftoverWei[msg.sender] = 0; msg.sender.transfer(total); emit LogWeiWithdrawn(msg.sender, total); return true; } /// @dev send ether from the completed crowdsale to the owners wallet address /// @param self Stored crowdsale from crowdsale contract /// @return true if owner withdrew eth function withdrawOwnerEth(DirectCrowdsaleStorage storage self) public returns (bool) { if ((!crowdsaleEnded(self)) && (self.token.balanceOf(this)>0)) { emit LogErrorMsg(0, "Cannot withdraw owner ether until after the sale!"); return false; } require(msg.sender == self.owner); require(self.ownerBalance > 0); uint256 amount = self.ownerBalance; self.ownerBalance = 0; self.owner.transfer(amount); emit LogOwnerEthWithdrawn(msg.sender,amount,"Crowdsale owner has withdrawn all funds!"); return true; } /// @dev Gets the price and buy cap for individual addresses at the given milestone index /// @param self Stored Crowdsale from crowdsale contract /// @param timestamp Time during sale for which data is requested /// @return A 2-element array with 0 the timestamp, 1 the price in eth function getSaleData(DirectCrowdsaleStorage storage self, uint256 timestamp) public view returns (uint256[2]) { uint256[2] memory _thisData; uint256 index; while((index < self.milestoneTimes.length) && (self.milestoneTimes[index] < timestamp)) { index++; } if(index == 0) index++; _thisData[0] = self.milestoneTimes[index - 1]; _thisData[1] = self.tokenPrice[_thisData[0]]; return _thisData; } /// @dev Gets the number of tokens sold thus far /// @param self Stored Crowdsale from crowdsale contract /// @return Number of tokens sold function getTokensSold(DirectCrowdsaleStorage storage self) public view returns (uint256) { return self.startingTokenBalance - self.withdrawTokensMap[self.owner]; } /// @dev function to check if the crowdsale is currently active /// @param self Stored crowdsale from crowdsale contract /// @return success function crowdsaleActive(DirectCrowdsaleStorage storage self) public view returns (bool) { return (now >= self.startTime && now <= self.endTime); } /// @dev function to check if the crowdsale has ended /// @param self Stored crowdsale from crowdsale contract /// @return success function crowdsaleEnded(DirectCrowdsaleStorage storage self) public view returns (bool) { return now > self.endTime; } } library BasicMathLib { /// @dev Multiplies two numbers and checks for overflow before returning. /// Does not throw. /// @param a First number /// @param b Second number /// @return err False normally, or true if there is overflow /// @return res The product of a and b, or 0 if there is overflow function times(uint256 a, uint256 b) public pure returns (bool err,uint256 res) { assembly{ res := mul(a,b) switch or(iszero(b), eq(div(res,b), a)) case 0 { err := 1 res := 0 } } } /// @dev Divides two numbers but checks for 0 in the divisor first. /// Does not throw. /// @param a First number /// @param b Second number /// @return err False normally, or true if `b` is 0 /// @return res The quotient of a and b, or 0 if `b` is 0 function dividedBy(uint256 a, uint256 b) public pure returns (bool err,uint256 i) { uint256 res; assembly{ switch iszero(b) case 0 { res := div(a,b) let loc := mload(0x40) mstore(add(loc,0x20),res) i := mload(add(loc,0x20)) } default { err := 1 i := 0 } } } /// @dev Adds two numbers and checks for overflow before returning. /// Does not throw. /// @param a First number /// @param b Second number /// @return err False normally, or true if there is overflow /// @return res The sum of a and b, or 0 if there is overflow function plus(uint256 a, uint256 b) public pure returns (bool err, uint256 res) { assembly{ res := add(a,b) switch and(eq(sub(res,b), a), or(gt(res,b),eq(res,b))) case 0 { err := 1 res := 0 } } } /// @dev Subtracts two numbers and checks for underflow before returning. /// Does not throw but rather logs an Err event if there is underflow. /// @param a First number /// @param b Second number /// @return err False normally, or true if there is underflow /// @return res The difference between a and b, or 0 if there is underflow function minus(uint256 a, uint256 b) public pure returns (bool err,uint256 res) { assembly{ res := sub(a,b) switch eq(and(eq(add(res,b), a), or(lt(res,a), eq(res,a))), 1) case 0 { err := 1 res := 0 } } } } contract CrowdsaleToken { using TokenLib for TokenLib.TokenStorage; TokenLib.TokenStorage public token; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event OwnerChange(address from, address to); event Burn(address indexed burner, uint256 value); event MintingClosed(bool mintingClosed); function CrowdsaleToken(address owner, string name, string symbol, uint8 decimals, uint256 initialSupply, bool allowMinting) public { token.init(owner, name, symbol, decimals, initialSupply, allowMinting); } function name() public view returns (string) { return token.name; } function symbol() public view returns (string) { return token.symbol; } function decimals() public view returns (uint8) { return token.decimals; } function totalSupply() public view returns (uint256) { return token.totalSupply; } function initialSupply() public view returns (uint256) { return token.initialSupply; } function balanceOf(address who) public view returns (uint256) { return token.balanceOf(who); } function allowance(address owner, address spender) public view returns (uint256) { return token.allowance(owner, spender); } function transfer(address to, uint256 value) public returns (bool ok) { return token.transfer(to, value); } function transferFrom(address from, address to, uint value) public returns (bool ok) { return token.transferFrom(from, to, value); } function approve(address spender, uint256 value) public returns (bool ok) { return token.approve(spender, value); } function approveChange(address spender, uint256 valueChange, bool increase) public returns (bool) { return token.approveChange(spender, valueChange, increase); } function changeOwner(address newOwner) public returns (bool ok) { return token.changeOwner(newOwner); } function burnToken(uint256 amount) public returns (bool ok) { return token.burnToken(amount); } } pragma solidity 0.4.21; /** * @title TokenLib * @author Modular Inc, https://modular.network * * version 1.3.3 * Copyright (c) 2017 Modular, Inc * The MIT License (MIT) * https://github.com/Modular-Network/ethereum-libraries/blob/master/LICENSE * * The Token Library provides functionality to create a variety of ERC20 tokens. * See https://github.com/Modular-Network/ethereum-contracts for an example of how to * create a basic ERC20 token. * * Modular works on open source projects in the Ethereum community with the * purpose of testing, documenting, and deploying reusable code onto the * blockchain to improve security and usability of smart contracts. Modular * also strives to educate non-profits, schools, and other community members * about the application of blockchain technology. * For further information: modular.network * * 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. */ library TokenLib { using BasicMathLib for uint256; struct TokenStorage { bool initialized; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string name; string symbol; uint256 totalSupply; uint256 initialSupply; address owner; uint8 decimals; bool stillMinting; } event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event OwnerChange(address from, address to); event Burn(address indexed burner, uint256 value); event MintingClosed(bool mintingClosed); /// @dev Called by the Standard Token upon creation. /// @param self Stored token from token contract /// @param _name Name of the new token /// @param _symbol Symbol of the new token /// @param _decimals Decimal places for the token represented /// @param _initial_supply The initial token supply /// @param _allowMinting True if additional tokens can be created, false otherwise function init(TokenStorage storage self, address _owner, string _name, string _symbol, uint8 _decimals, uint256 _initial_supply, bool _allowMinting) public { require(!self.initialized); self.initialized = true; self.name = _name; self.symbol = _symbol; self.totalSupply = _initial_supply; self.initialSupply = _initial_supply; self.decimals = _decimals; self.owner = _owner; self.stillMinting = _allowMinting; self.balances[_owner] = _initial_supply; } /// @dev Transfer tokens from caller&#39;s account to another account. /// @param self Stored token from token contract /// @param _to Address to send tokens /// @param _value Number of tokens to send /// @return True if completed function transfer(TokenStorage storage self, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); bool err; uint256 balance; (err,balance) = self.balances[msg.sender].minus(_value); require(!err); self.balances[msg.sender] = balance; //It&#39;s not possible to overflow token supply self.balances[_to] = self.balances[_to] + _value; emit Transfer(msg.sender, _to, _value); return true; } /// @dev Authorized caller transfers tokens from one account to another /// @param self Stored token from token contract /// @param _from Address to send tokens from /// @param _to Address to send tokens to /// @param _value Number of tokens to send /// @return True if completed function transferFrom(TokenStorage storage self, address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = self.allowed[_from][msg.sender]; bool err; uint256 balanceOwner; uint256 balanceSpender; (err,balanceOwner) = self.balances[_from].minus(_value); require(!err); (err,balanceSpender) = _allowance.minus(_value); require(!err); self.balances[_from] = balanceOwner; self.allowed[_from][msg.sender] = balanceSpender; self.balances[_to] = self.balances[_to] + _value; emit Transfer(_from, _to, _value); return true; } /// @dev Retrieve token balance for an account /// @param self Stored token from token contract /// @param _owner Address to retrieve balance of /// @return balance The number of tokens in the subject account function balanceOf(TokenStorage storage self, address _owner) public view returns (uint256 balance) { return self.balances[_owner]; } /// @dev Authorize an account to send tokens on caller&#39;s behalf /// @param self Stored token from token contract /// @param _spender Address to authorize /// @param _value Number of tokens authorized account may send /// @return True if completed function approve(TokenStorage storage self, address _spender, uint256 _value) public returns (bool) { // must set to zero before changing approval amount in accordance with spec require((_value == 0) || (self.allowed[msg.sender][_spender] == 0)); self.allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /// @dev Remaining tokens third party spender has to send /// @param self Stored token from token contract /// @param _owner Address of token holder /// @param _spender Address of authorized spender /// @return remaining Number of tokens spender has left in owner&#39;s account function allowance(TokenStorage storage self, address _owner, address _spender) public view returns (uint256 remaining) { return self.allowed[_owner][_spender]; } /// @dev Authorize third party transfer by increasing/decreasing allowed rather than setting it /// @param self Stored token from token contract /// @param _spender Address to authorize /// @param _valueChange Increase or decrease in number of tokens authorized account may send /// @param _increase True if increasing allowance, false if decreasing allowance /// @return True if completed function approveChange (TokenStorage storage self, address _spender, uint256 _valueChange, bool _increase) public returns (bool) { uint256 _newAllowed; bool err; if(_increase) { (err, _newAllowed) = self.allowed[msg.sender][_spender].plus(_valueChange); require(!err); self.allowed[msg.sender][_spender] = _newAllowed; } else { if (_valueChange > self.allowed[msg.sender][_spender]) { self.allowed[msg.sender][_spender] = 0; } else { _newAllowed = self.allowed[msg.sender][_spender] - _valueChange; self.allowed[msg.sender][_spender] = _newAllowed; } } emit Approval(msg.sender, _spender, _newAllowed); return true; } /// @dev Change owning address of the token contract, specifically for minting /// @param self Stored token from token contract /// @param _newOwner Address for the new owner /// @return True if completed function changeOwner(TokenStorage storage self, address _newOwner) public returns (bool) { require((self.owner == msg.sender) && (_newOwner > 0)); self.owner = _newOwner; emit OwnerChange(msg.sender, _newOwner); return true; } /// @dev Mints additional tokens, new tokens go to owner /// @param self Stored token from token contract /// @param _amount Number of tokens to mint /// @return True if completed function mintToken(TokenStorage storage self, uint256 _amount) public returns (bool) { require((self.owner == msg.sender) && self.stillMinting); uint256 _newAmount; bool err; (err, _newAmount) = self.totalSupply.plus(_amount); require(!err); self.totalSupply = _newAmount; self.balances[self.owner] = self.balances[self.owner] + _amount; emit Transfer(0x0, self.owner, _amount); return true; } /// @dev Permanent stops minting /// @param self Stored token from token contract /// @return True if completed function closeMint(TokenStorage storage self) public returns (bool) { require(self.owner == msg.sender); self.stillMinting = false; emit MintingClosed(true); return true; } /// @dev Permanently burn tokens /// @param self Stored token from token contract /// @param _amount Amount of tokens to burn /// @return True if completed function burnToken(TokenStorage storage self, uint256 _amount) public returns (bool) { uint256 _newBalance; bool err; (err, _newBalance) = self.balances[msg.sender].minus(_amount); require(!err); self.balances[msg.sender] = _newBalance; self.totalSupply = self.totalSupply - _amount; emit Burn(msg.sender, _amount); emit Transfer(msg.sender, 0x0, _amount); return true; } }
Find the number of tokens as a function in wei
(err,_weiTokens) = _amount.times(self.tokensPerEth);
7,785,709
[ 1, 3125, 326, 1300, 434, 2430, 487, 279, 445, 316, 732, 77, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 261, 370, 16, 67, 1814, 77, 5157, 13, 273, 389, 8949, 18, 8293, 12, 2890, 18, 7860, 2173, 41, 451, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x927E1e532d25958c1C8CD4908ab8D1b27D3978e8/sources/contracts/protocol/core/CreditDesk.sol
subtract cl from total loans outstanding This resets lastFullPaymentBlock. These conditions assure that they have indeed paid off all their interest and they have a real nextDueBlock. (ie. creditline isn't pre-drawdown) If interest was fully paid off, then set the last full payment as the previous due block
function updateCreditLineAccounting( CreditLine cl, uint256 balance, uint256 interestOwed, uint256 principalOwed ) internal nonReentrant { totalLoansOutstanding = totalLoansOutstanding.sub(cl.balance()); cl.setBalance(balance); cl.setInterestOwed(interestOwed); cl.setPrincipalOwed(principalOwed); uint256 nextDueBlock = cl.nextDueBlock(); if (interestOwed == 0 && nextDueBlock != 0) { uint256 mostRecentLastDueBlock; if (blockNumber() < nextDueBlock) { uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY); mostRecentLastDueBlock = nextDueBlock.sub(blocksPerPeriod); mostRecentLastDueBlock = nextDueBlock; } cl.setLastFullPaymentBlock(mostRecentLastDueBlock); } cl.setNextDueBlock(calculateNextDueBlock(cl)); }
4,841,841
[ 1, 1717, 1575, 927, 628, 2078, 437, 634, 20974, 1220, 20063, 1142, 5080, 6032, 1768, 18, 8646, 4636, 1551, 594, 716, 2898, 1240, 316, 323, 329, 30591, 3397, 777, 3675, 16513, 471, 2898, 1240, 279, 2863, 1024, 30023, 1768, 18, 261, 1385, 18, 12896, 1369, 5177, 1404, 675, 17, 9446, 2378, 13, 971, 16513, 1703, 7418, 30591, 3397, 16, 1508, 444, 326, 1142, 1983, 5184, 487, 326, 2416, 6541, 1203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1089, 16520, 1670, 3032, 310, 12, 203, 565, 30354, 1670, 927, 16, 203, 565, 2254, 5034, 11013, 16, 203, 565, 2254, 5034, 16513, 3494, 329, 16, 203, 565, 2254, 5034, 8897, 3494, 329, 203, 225, 262, 2713, 1661, 426, 8230, 970, 288, 203, 565, 2078, 1504, 634, 1182, 15167, 273, 2078, 1504, 634, 1182, 15167, 18, 1717, 12, 830, 18, 12296, 10663, 203, 203, 565, 927, 18, 542, 13937, 12, 12296, 1769, 203, 565, 927, 18, 542, 29281, 3494, 329, 12, 2761, 395, 3494, 329, 1769, 203, 565, 927, 18, 542, 9155, 3494, 329, 12, 26138, 3494, 329, 1769, 203, 203, 565, 2254, 5034, 1024, 30023, 1768, 273, 927, 18, 4285, 30023, 1768, 5621, 203, 565, 309, 261, 2761, 395, 3494, 329, 422, 374, 597, 1024, 30023, 1768, 480, 374, 13, 288, 203, 1377, 2254, 5034, 4486, 17076, 3024, 30023, 1768, 31, 203, 1377, 309, 261, 2629, 1854, 1435, 411, 1024, 30023, 1768, 13, 288, 203, 3639, 2254, 5034, 4398, 2173, 5027, 273, 927, 18, 9261, 5027, 382, 9384, 7675, 16411, 12, 11403, 55, 67, 3194, 67, 10339, 1769, 203, 3639, 4486, 17076, 3024, 30023, 1768, 273, 1024, 30023, 1768, 18, 1717, 12, 7996, 2173, 5027, 1769, 203, 3639, 4486, 17076, 3024, 30023, 1768, 273, 1024, 30023, 1768, 31, 203, 1377, 289, 203, 1377, 927, 18, 542, 3024, 5080, 6032, 1768, 12, 10329, 17076, 3024, 30023, 1768, 1769, 203, 565, 289, 203, 203, 203, 565, 927, 18, 542, 2134, 30023, 1768, 12, 11162, 2134, 30023, 1768, 12, 830, 10019, 203, 225, 289, 2 ]
./full_match/1/0x3c1164531d5857029ae5412E49999306547834d8/sources/contracts/implementations/abstract/CoreMP.sol
* @notice Used to retrieve the metadata of the collection. @return string The metadata URI of the collection/
function collectionMetadata() public view returns (string memory) { return _collectionMetadata; }
9,657,871
[ 1, 6668, 358, 4614, 326, 1982, 434, 326, 1849, 18, 327, 533, 1021, 1982, 3699, 434, 326, 1849, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1849, 2277, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 5548, 2277, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x44ae17e3C828D068D54093bfb72e4f005C4701ec/sources/contracts/EquityPool.sol
@notice Distrbute funds to stakeholders and remainder to Impact3 fund calculate amount to distribute update funds last received with timestamp send value to stake holder
function distributeFunds() public whenNotPaused nonReentrant { if (withinUpdateWindow()) { revert EquityPool__ContractUpdateWindowIsOpen(); } uint256 fundsToDistribute = address(this).balance; uint256 fundsDistributed = 0; address[] memory currentHolderAddresses = stakeHolderAddresses; for (uint256 i = 0; i < currentHolderAddresses.length; i++) { uint256 equityTokens = stakeHolders[currentHolderAddresses[i]] .equityTokens; uint256 amount = fundsToDistribute.mul(equityTokens).div((10**8)); stakeHolders[currentHolderAddresses[i]].fundsLastReceived = block .timestamp; fundsDistributed += amount; sendValue(payable(stakeHolderAddresses[i]), amount); emit FundsDistributed( stakeHolderAddresses[i], amount, block.timestamp ); } if (block.timestamp >= _closetimestamp) { lastEndOfIntervalTimestamp += intervalMilliSeconds; lastEndOfIntervalTimestamp = lastEndOfIntervalTimestamp; } emit FundsDistributed( impact3FundAddress, fundsDistributed, block.timestamp ); }
9,603,650
[ 1, 1669, 313, 70, 624, 284, 19156, 358, 384, 911, 9000, 471, 10022, 358, 9457, 621, 23, 284, 1074, 4604, 3844, 358, 25722, 1089, 284, 19156, 1142, 5079, 598, 2858, 1366, 460, 358, 384, 911, 10438, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 25722, 42, 19156, 1435, 1071, 1347, 1248, 28590, 1661, 426, 8230, 970, 288, 203, 202, 202, 430, 261, 25850, 1891, 3829, 10756, 288, 203, 1082, 202, 266, 1097, 19008, 560, 2864, 972, 8924, 1891, 3829, 2520, 3678, 5621, 203, 202, 202, 97, 203, 203, 202, 202, 11890, 5034, 284, 1074, 11634, 1669, 887, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 202, 202, 11890, 5034, 284, 19156, 1669, 11050, 273, 374, 31, 203, 203, 202, 202, 2867, 8526, 3778, 783, 6064, 7148, 273, 384, 911, 6064, 7148, 31, 203, 202, 202, 1884, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 783, 6064, 7148, 18, 2469, 31, 277, 27245, 288, 203, 1082, 202, 11890, 5034, 1298, 560, 5157, 273, 384, 911, 27003, 63, 2972, 6064, 7148, 63, 77, 13563, 203, 9506, 202, 18, 14298, 560, 5157, 31, 203, 1082, 202, 11890, 5034, 3844, 273, 284, 1074, 11634, 1669, 887, 18, 16411, 12, 14298, 560, 5157, 2934, 2892, 12443, 2163, 636, 28, 10019, 203, 203, 1082, 202, 334, 911, 27003, 63, 2972, 6064, 7148, 63, 77, 65, 8009, 74, 19156, 3024, 8872, 273, 1203, 203, 9506, 202, 18, 5508, 31, 203, 1082, 202, 74, 19156, 1669, 11050, 1011, 3844, 31, 203, 203, 1082, 202, 4661, 620, 12, 10239, 429, 12, 334, 911, 6064, 7148, 63, 77, 65, 3631, 3844, 1769, 203, 1082, 202, 18356, 478, 19156, 1669, 11050, 12, 203, 9506, 202, 334, 911, 6064, 7148, 63, 77, 6487, 203, 9506, 202, 8949, 16, 203, 9506, 202, 2629, 18, 5508, 203, 1082, 202, 2 ]
// SPDX-License-Identifier: GPL-3.0-or-later // Sources flattened with hardhat v2.6.1 https://hardhat.org // File interfaces/actions/IAction.sol pragma solidity 0.8.9; interface IAction { /** * @return the total amount of ETH (in wei) required to cover gas */ function getEthRequiredForGas(address payer) external view returns (uint256); function addUsableToken(address token) external returns (bool); function getUsableTokens() external view returns (address[] memory); function isUsable(address token) external view returns (bool); function getActionFee() external view returns (uint256); function getFeeHandler() external view returns (address); function executeActionFee() external returns (uint256); function executeSwapperSlippage() external returns (uint256); function executeFeeHandler() external returns (address); } // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, 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); } // File interfaces/IPreparable.sol pragma solidity 0.8.9; interface IPreparable { event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay); event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay); event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue); event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue); event ConfigReset(bytes32 indexed key); } // File interfaces/IStrategy.sol pragma solidity 0.8.9; interface IStrategy { function name() external view returns (string memory); function deposit() external payable returns (bool); function balance() external view returns (uint256); function withdraw(uint256 amount) external returns (bool); function withdrawAll() external returns (uint256); function harvestable() external view returns (uint256); function harvest() external returns (uint256); function strategist() external view returns (address); function shutdown() external returns (bool); function hasPendingFunds() external view returns (bool); } // File interfaces/IVault.sol pragma solidity 0.8.9; /** * @title Interface for a Vault */ interface IVault is IPreparable { event StrategyActivated(address indexed strategy); event StrategyDeactivated(address indexed strategy); /** * @dev 'netProfit' is the profit after all fees have been deducted */ event Harvest(uint256 indexed netProfit, uint256 indexed loss); function initialize( address _pool, uint256 _debtLimit, uint256 _targetAllocation, uint256 _bound ) external; function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256); function deposit() external payable; function withdraw(uint256 amount) external returns (bool); function initializeStrategy(address strategy_) external returns (bool); function withdrawAll() external; function withdrawFromReserve(uint256 amount) external; function getStrategy() external view returns (IStrategy); function getStrategiesWaitingForRemoval() external view returns (address[] memory); function getAllocatedToStrategyWaitingForRemoval(address strategy) external view returns (uint256); function getTotalUnderlying() external view returns (uint256); function getUnderlying() external view returns (address); } // File interfaces/pool/ILiquidityPool.sol pragma solidity 0.8.9; interface ILiquidityPool is IPreparable { event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens); event DepositFor( address indexed minter, address indexed mintee, uint256 depositAmount, uint256 mintedLpTokens ); event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens); event LpTokenSet(address indexed lpToken); event StakerVaultSet(address indexed stakerVault); function redeem(uint256 redeemTokens) external returns (uint256); function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256); function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256); function deposit(uint256 mintAmount) external payable returns (uint256); function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256); function depositAndStake(uint256 depositAmount, uint256 minTokenAmount) external payable returns (uint256); function depositFor(address account, uint256 depositAmount) external payable returns (uint256); function depositFor( address account, uint256 depositAmount, uint256 minTokenAmount ) external payable returns (uint256); function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount) external returns (uint256); function handleLpTokenTransfer( address from, address to, uint256 amount ) external; function executeNewVault() external returns (address); function executeNewMaxWithdrawalFee() external returns (uint256); function executeNewRequiredReserves() external returns (uint256); function executeNewReserveDeviation() external returns (uint256); function setLpToken(address _lpToken) external returns (bool); function setStaker() external returns (bool); function isCapped() external returns (bool); function uncap() external returns (bool); function updateDepositCap(uint256 _depositCap) external returns (bool); function getUnderlying() external view returns (address); function getLpToken() external view returns (address); function getWithdrawalFee(address account, uint256 amount) external view returns (uint256); function getVault() external view returns (IVault); function exchangeRate() external view returns (uint256); } // File interfaces/IGasBank.sol pragma solidity 0.8.9; interface IGasBank { event Deposit(address indexed account, uint256 value); event Withdraw(address indexed account, address indexed receiver, uint256 value); function depositFor(address account) external payable; function withdrawUnused(address account) external; function withdrawFrom(address account, uint256 amount) external; function withdrawFrom( address account, address payable to, uint256 amount ) external; function balanceOf(address account) external view returns (uint256); } // File interfaces/oracles/IOracleProvider.sol pragma solidity 0.8.9; interface IOracleProvider { /// @notice Quotes the USD price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the USD price of the asset function getPriceUSD(address baseAsset) external view returns (uint256); /// @notice Quotes the ETH price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the ETH price of the asset function getPriceETH(address baseAsset) external view returns (uint256); } // File libraries/AddressProviderMeta.sol pragma solidity 0.8.9; library AddressProviderMeta { struct Meta { bool freezable; bool frozen; } function fromUInt(uint256 value) internal pure returns (Meta memory) { Meta memory meta; meta.freezable = (value & 1) == 1; meta.frozen = ((value >> 1) & 1) == 1; return meta; } function toUInt(Meta memory meta) internal pure returns (uint256) { uint256 value; value |= meta.freezable ? 1 : 0; value |= meta.frozen ? 1 << 1 : 0; return value; } } // File interfaces/IAddressProvider.sol pragma solidity 0.8.9; // solhint-disable ordering interface IAddressProvider is IPreparable { event KnownAddressKeyAdded(bytes32 indexed key); event StakerVaultListed(address indexed stakerVault); event StakerVaultDelisted(address indexed stakerVault); event ActionListed(address indexed action); event PoolListed(address indexed pool); event PoolDelisted(address indexed pool); event VaultUpdated(address indexed previousVault, address indexed newVault); /** Key functions */ function getKnownAddressKeys() external view returns (bytes32[] memory); function freezeAddress(bytes32 key) external; /** Pool functions */ function allPools() external view returns (address[] memory); function addPool(address pool) external; function poolsCount() external view returns (uint256); function getPoolAtIndex(uint256 index) external view returns (address); function isPool(address pool) external view returns (bool); function removePool(address pool) external returns (bool); function getPoolForToken(address token) external view returns (ILiquidityPool); function safeGetPoolForToken(address token) external view returns (address); /** Vault functions */ function updateVault(address previousVault, address newVault) external; function allVaults() external view returns (address[] memory); function vaultsCount() external view returns (uint256); function getVaultAtIndex(uint256 index) external view returns (address); function isVault(address vault) external view returns (bool); /** Action functions */ function allActions() external view returns (address[] memory); function addAction(address action) external returns (bool); function isAction(address action) external view returns (bool); /** Address functions */ function initializeAddress( bytes32 key, address initialAddress, bool frezable ) external; function initializeAndFreezeAddress(bytes32 key, address initialAddress) external; function getAddress(bytes32 key) external view returns (address); function getAddress(bytes32 key, bool checkExists) external view returns (address); function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory); function prepareAddress(bytes32 key, address newAddress) external returns (bool); function executeAddress(bytes32 key) external returns (address); function resetAddress(bytes32 key) external returns (bool); /** Staker vault functions */ function allStakerVaults() external view returns (address[] memory); function tryGetStakerVault(address token) external view returns (bool, address); function getStakerVault(address token) external view returns (address); function addStakerVault(address stakerVault) external returns (bool); function isStakerVault(address stakerVault, address token) external view returns (bool); function isStakerVaultRegistered(address stakerVault) external view returns (bool); function isWhiteListedFeeHandler(address feeHandler) external view returns (bool); } // File interfaces/tokenomics/IInflationManager.sol pragma solidity 0.8.9; interface IInflationManager { event KeeperGaugeListed(address indexed pool, address indexed keeperGauge); event AmmGaugeListed(address indexed token, address indexed ammGauge); event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge); event AmmGaugeDelisted(address indexed token, address indexed ammGauge); /** Pool functions */ function setKeeperGauge(address pool, address _keeperGauge) external returns (bool); function setAmmGauge(address token, address _ammGauge) external returns (bool); function getAllAmmGauges() external view returns (address[] memory); function getLpRateForStakerVault(address stakerVault) external view returns (uint256); function getKeeperRateForPool(address pool) external view returns (uint256); function getAmmRateForToken(address token) external view returns (uint256); function getKeeperWeightForPool(address pool) external view returns (uint256); function getAmmWeightForToken(address pool) external view returns (uint256); function getLpPoolWeight(address pool) external view returns (uint256); function getKeeperGaugeForPool(address pool) external view returns (address); function getAmmGaugeForToken(address token) external view returns (address); function isInflationWeightManager(address account) external view returns (bool); function removeStakerVaultFromInflation(address stakerVault, address lpToken) external; function addGaugeForVault(address lpToken) external returns (bool); function whitelistGauge(address gauge) external; function checkpointAllGauges() external returns (bool); function mintRewards(address beneficiary, uint256 amount) external; function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool) external returns (bool); /** Weight setter functions **/ function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool); function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool); function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool); function executeLpPoolWeight(address lpToken) external returns (uint256); function executeAmmTokenWeight(address token) external returns (uint256); function executeKeeperPoolWeight(address pool) external returns (uint256); function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights) external returns (bool); function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights) external returns (bool); function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights) external returns (bool); function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool); function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool); function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool); } // File interfaces/IController.sol pragma solidity 0.8.9; // solhint-disable ordering interface IController is IPreparable { function addressProvider() external view returns (IAddressProvider); function inflationManager() external view returns (IInflationManager); function addStakerVault(address stakerVault) external returns (bool); function removePool(address pool) external returns (bool); /** Keeper functions */ function prepareKeeperRequiredStakedBKD(uint256 amount) external; function executeKeeperRequiredStakedBKD() external; function getKeeperRequiredStakedBKD() external view returns (uint256); function canKeeperExecuteAction(address keeper) external view returns (bool); /** Miscellaneous functions */ function getTotalEthRequiredForGas(address payer) external view returns (uint256); } // File interfaces/IStakerVault.sol pragma solidity 0.8.9; interface IStakerVault { event Staked(address indexed account, uint256 amount); event Unstaked(address indexed account, uint256 amount); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function initialize(address _token) external; function initializeLpGauge(address _lpGauge) external returns (bool); function stake(uint256 amount) external returns (bool); function stakeFor(address account, uint256 amount) external returns (bool); function unstake(uint256 amount) external returns (bool); function unstakeFor( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function transfer(address account, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function getToken() external view returns (address); function balanceOf(address account) external view returns (uint256); function stakedAndActionLockedBalanceOf(address account) external view returns (uint256); function actionLockedBalanceOf(address account) external view returns (uint256); function increaseActionLockedBalance(address account, uint256 amount) external returns (bool); function decreaseActionLockedBalance(address account, uint256 amount) external returns (bool); function getStakedByActions() external view returns (uint256); function addStrategy(address strategy) external returns (bool); function getPoolTotalStaked() external view returns (uint256); function prepareLpGauge(address _lpGauge) external returns (bool); function executeLpGauge() external returns (bool); function getLpGauge() external view returns (address); function poolCheckpoint() external returns (bool); function isStrategy(address user) external view returns (bool); } // File interfaces/IVaultReserve.sol pragma solidity 0.8.9; interface IVaultReserve { event Deposit(address indexed vault, address indexed token, uint256 amount); event Withdraw(address indexed vault, address indexed token, uint256 amount); event VaultListed(address indexed vault); function deposit(address token, uint256 amount) external payable returns (bool); function withdraw(address token, uint256 amount) external returns (bool); function getBalance(address vault, address token) external view returns (uint256); function canWithdraw(address vault) external view returns (bool); } // File interfaces/IRoleManager.sol pragma solidity 0.8.9; interface IRoleManager { event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, address account ) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, bytes32 role3, address account ) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } // File interfaces/tokenomics/IBkdToken.sol pragma solidity 0.8.9; interface IBkdToken is IERC20 { function mint(address account, uint256 amount) external; } // File libraries/AddressProviderKeys.sol pragma solidity 0.8.9; library AddressProviderKeys { bytes32 internal constant _TREASURY_KEY = "treasury"; bytes32 internal constant _GAS_BANK_KEY = "gasBank"; bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve"; bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry"; bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider"; bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory"; bytes32 internal constant _CONTROLLER_KEY = "controller"; bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker"; bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager"; } // File libraries/AddressProviderHelpers.sol pragma solidity 0.8.9; library AddressProviderHelpers { /** * @return The address of the treasury. */ function getTreasury(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._TREASURY_KEY); } /** * @return The gas bank. */ function getGasBank(IAddressProvider provider) internal view returns (IGasBank) { return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY)); } /** * @return The address of the vault reserve. */ function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) { return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY)); } /** * @return The address of the swapperRegistry. */ function getSwapperRegistry(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY); } /** * @return The oracleProvider. */ function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) { return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY)); } /** * @return the address of the BKD locker */ function getBKDLocker(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY); } /** * @return the address of the BKD locker */ function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) { return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY)); } /** * @return the controller */ function getController(IAddressProvider provider) internal view returns (IController) { return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY)); } } // File libraries/Errors.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Error { string internal constant ADDRESS_WHITELISTED = "address already whitelisted"; string internal constant ADMIN_ALREADY_SET = "admin has already been set once"; string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted"; string internal constant ADDRESS_NOT_FOUND = "address not found"; string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once"; string internal constant CONTRACT_PAUSED = "contract is paused"; string internal constant INVALID_AMOUNT = "invalid amount"; string internal constant INVALID_INDEX = "invalid index"; string internal constant INVALID_VALUE = "invalid msg.value"; string internal constant INVALID_SENDER = "invalid msg.sender"; string internal constant INVALID_TOKEN = "token address does not match pool's LP token address"; string internal constant INVALID_DECIMALS = "incorrect number of decimals"; string internal constant INVALID_ARGUMENT = "invalid argument"; string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted"; string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_POOL_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_LP_TOKEN_IMPLEMENTATION = "invalid LP Token implementation for given coin"; string internal constant INVALID_VAULT_IMPLEMENTATION = "invalid vault implementation for given coin"; string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION = "invalid stakerVault implementation for given coin"; string internal constant INSUFFICIENT_BALANCE = "insufficient balance"; string internal constant ADDRESS_ALREADY_SET = "Address is already set"; string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance"; string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received"; string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist"; string internal constant ADDRESS_FROZEN = "address is frozen"; string internal constant ROLE_EXISTS = "role already exists"; string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role"; string internal constant UNAUTHORIZED_ACCESS = "unauthorized access"; string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed"; string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed"; string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed"; string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed"; string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10"; string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold"; string internal constant NO_POSITION_EXISTS = "no position exists"; string internal constant POSITION_ALREADY_EXISTS = "position already exists"; string internal constant PROTOCOL_NOT_FOUND = "protocol not found"; string internal constant TOP_UP_FAILED = "top up failed"; string internal constant SWAP_PATH_NOT_FOUND = "swap path not found"; string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported"; string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN = "not enough funds were withdrawn from the pool"; string internal constant FAILED_TRANSFER = "transfer failed"; string internal constant FAILED_MINT = "mint failed"; string internal constant FAILED_REPAY_BORROW = "repay borrow failed"; string internal constant FAILED_METHOD_CALL = "method call failed"; string internal constant NOTHING_TO_CLAIM = "there is no claimable balance"; string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance"; string internal constant INVALID_MINTER = "the minter address of the LP token and the pool address do not match"; string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token"; string internal constant DEADLINE_NOT_ZERO = "deadline must be 0"; string internal constant DEADLINE_NOT_SET = "deadline is 0"; string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet"; string internal constant DELAY_TOO_SHORT = "delay be at least 3 days"; string internal constant INSUFFICIENT_UPDATE_BALANCE = "insufficient funds for updating the position"; string internal constant SAME_AS_CURRENT = "value must be different to existing value"; string internal constant NOT_CAPPED = "the pool is not currently capped"; string internal constant ALREADY_CAPPED = "the pool is already capped"; string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap"; string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas"; string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw"; string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas"; string internal constant DEPOSIT_FAILED = "deposit failed"; string internal constant GAS_TOO_HIGH = "too much ETH used for gas"; string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas"; string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add"; string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed"; string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet"; string internal constant UNDERLYING_NOT_WITHDRAWABLE = "pool does not support additional underlying coins to be withdrawn"; string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down"; string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist"; string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported"; string internal constant NO_DEX_SET = "no dex has been set for token"; string internal constant INVALID_TOKEN_PAIR = "invalid token pair"; string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action"; string internal constant ADDRESS_NOT_ACTION = "address is not registered action"; string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance"; string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve"; string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block"; string internal constant GAUGE_EXISTS = "Gauge already exists"; string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist"; string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex"; string internal constant PREPARED_WITHDRAWAL = "Cannot relock funds when withdrawal is being prepared"; string internal constant ASSET_NOT_SUPPORTED = "Asset not supported"; string internal constant STALE_PRICE = "Price is stale"; string internal constant NEGATIVE_PRICE = "Price is negative"; string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked"; string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded"; } // File contracts/utils/Preparable.sol pragma solidity 0.8.9; /** * @notice Implements the base logic for a two-phase commit * @dev This does not implements any access-control so publicly exposed * callers should make sure to have the proper checks in palce */ contract Preparable is IPreparable { uint256 private constant _MIN_DELAY = 3 days; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingUInts256; mapping(bytes32 => address) public currentAddresses; mapping(bytes32 => uint256) public currentUInts256; /** * @dev Deadlines shares the same namespace regardless of the type * of the pending variable so this needs to be enforced in the caller */ mapping(bytes32 => uint256) public deadlines; function _prepareDeadline(bytes32 key, uint256 delay) internal { require(deadlines[key] == 0, Error.DEADLINE_NOT_ZERO); require(delay >= _MIN_DELAY, Error.DELAY_TOO_SHORT); deadlines[key] = block.timestamp + delay; } /** * @notice Prepares an uint256 that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, uint256 value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingUInts256[key] = value; emit ConfigPreparedNumber(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,uint256,uint256)` but uses a default delay */ function _prepare(bytes32 key, uint256 value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Prepares an address that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, address value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingAddresses[key] = value; emit ConfigPreparedAddress(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,address,uint256)` but uses a default delay */ function _prepare(bytes32 key, address value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Reset a uint256 key * @return `true` if success. */ function _resetUInt256Config(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingUInts256[key] = 0; emit ConfigReset(key); return true; } /** * @notice Reset an address key * @return `true` if success. */ function _resetAddressConfig(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingAddresses[key] = address(0); emit ConfigReset(key); return true; } /** * @dev Checks the deadline of the key and reset it */ function _executeDeadline(bytes32 key) internal { uint256 deadline = deadlines[key]; require(block.timestamp >= deadline, Error.DEADLINE_NOT_REACHED); require(deadline != 0, Error.DEADLINE_NOT_SET); deadlines[key] = 0; } /** * @notice Execute uint256 config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeUInt256(bytes32 key) internal returns (uint256) { _executeDeadline(key); uint256 newValue = pendingUInts256[key]; _setConfig(key, newValue); return newValue; } /** * @notice Execute address config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeAddress(bytes32 key) internal returns (address) { _executeDeadline(key); address newValue = pendingAddresses[key]; _setConfig(key, newValue); return newValue; } function _setConfig(bytes32 key, address value) internal returns (address) { address oldValue = currentAddresses[key]; currentAddresses[key] = value; pendingAddresses[key] = address(0); deadlines[key] = 0; emit ConfigUpdatedAddress(key, oldValue, value); return value; } function _setConfig(bytes32 key, uint256 value) internal returns (uint256) { uint256 oldValue = currentUInts256[key]; currentUInts256[key] = value; pendingUInts256[key] = 0; deadlines[key] = 0; emit ConfigUpdatedNumber(key, oldValue, value); return value; } } // File libraries/Roles.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Roles { bytes32 internal constant GOVERNANCE = "governance"; bytes32 internal constant ADDRESS_PROVIDER = "address_provider"; bytes32 internal constant POOL_FACTORY = "pool_factory"; bytes32 internal constant CONTROLLER = "controller"; bytes32 internal constant GAUGE_ZAP = "gauge_zap"; bytes32 internal constant MAINTENANCE = "maintenance"; bytes32 internal constant INFLATION_MANAGER = "inflation_manager"; bytes32 internal constant POOL = "pool"; bytes32 internal constant VAULT = "vault"; } // File contracts/access/AuthorizationBase.sol pragma solidity 0.8.9; /** * @notice Provides modifiers for authorization */ abstract contract AuthorizationBase { /** * @notice Only allows a sender with `role` to perform the given action */ modifier onlyRole(bytes32 role) { require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with GOVERNANCE role to perform the given action */ modifier onlyGovernance() { require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles2(bytes32 role1, bytes32 role2) { require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles3( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _roleManager().hasAnyRole(role1, role2, role3, msg.sender), Error.UNAUTHORIZED_ACCESS ); _; } function roleManager() external view virtual returns (IRoleManager) { return _roleManager(); } function _roleManager() internal view virtual returns (IRoleManager); } // File contracts/access/Authorization.sol pragma solidity 0.8.9; contract Authorization is AuthorizationBase { IRoleManager internal immutable __roleManager; constructor(IRoleManager roleManager) { __roleManager = roleManager; } function _roleManager() internal view override returns (IRoleManager) { return __roleManager; } } // File contracts/Controller.sol pragma solidity 0.8.9; contract Controller is IController, Authorization, Preparable { using AddressProviderHelpers for IAddressProvider; IAddressProvider public immutable override addressProvider; IInflationManager public inflationManager; bytes32 internal constant _KEEPER_REQUIRED_STAKED_BKD = "KEEPER_REQUIRED_STAKED_BKD"; constructor(IAddressProvider _addressProvider) Authorization(_addressProvider.getRoleManager()) { addressProvider = _addressProvider; } function setInflationManager(address _inflationManager) external onlyGovernance { require(address(inflationManager) == address(0), Error.ADDRESS_ALREADY_SET); require(_inflationManager != address(0), Error.INVALID_ARGUMENT); inflationManager = IInflationManager(_inflationManager); } function addStakerVault(address stakerVault) external override onlyRoles2(Roles.GOVERNANCE, Roles.POOL_FACTORY) returns (bool) { if (!addressProvider.addStakerVault(stakerVault)) { return false; } if (address(inflationManager) != address(0)) { address lpGauge = IStakerVault(stakerVault).getLpGauge(); if (lpGauge != address(0)) { inflationManager.whitelistGauge(lpGauge); } } return true; } /** * @notice Delists pool. * @param pool Address of pool to delist. * @return `true` if successful. */ function removePool(address pool) external override onlyGovernance returns (bool) { if (!addressProvider.removePool(pool)) { return false; } address lpToken = ILiquidityPool(pool).getLpToken(); if (address(inflationManager) != address(0)) { (bool exists, address stakerVault) = addressProvider.tryGetStakerVault(lpToken); if (exists) { inflationManager.removeStakerVaultFromInflation(stakerVault, lpToken); } } return true; } /** * @notice Prepares the minimum amount of staked BKD required by a keeper */ function prepareKeeperRequiredStakedBKD(uint256 amount) external override onlyGovernance { require(addressProvider.getBKDLocker() != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); _prepare(_KEEPER_REQUIRED_STAKED_BKD, amount); } /** * @notice Sets the minimum amount of staked BKD required by a keeper to the prepared value */ function executeKeeperRequiredStakedBKD() external override { _executeUInt256(_KEEPER_REQUIRED_STAKED_BKD); } /** * @notice Returns true if the given keeper has enough staked BKD to execute actions */ function canKeeperExecuteAction(address keeper) external view override returns (bool) { uint256 requiredBKD = getKeeperRequiredStakedBKD(); return requiredBKD == 0 || IERC20(addressProvider.getBKDLocker()).balanceOf(keeper) >= requiredBKD; } /** * @return Returns the minimum amount of staked BKD required by a keeper */ function getKeeperRequiredStakedBKD() public view override returns (uint256) { return currentUInts256[_KEEPER_REQUIRED_STAKED_BKD]; } /** * @return the total amount of ETH require by `payer` to cover the fees for * positions registered in all actions */ function getTotalEthRequiredForGas(address payer) external view override returns (uint256) { // solhint-disable-previous-line ordering uint256 totalEthRequired = 0; address[] memory actions = addressProvider.allActions(); uint256 numActions = actions.length; for (uint256 i = 0; i < numActions; i++) { totalEthRequired += IAction(actions[i]).getEthRequiredForGas(payer); } return totalEthRequired; } }
* @notice Prepares an uint256 that should be commited to the contract after `_MIN_DELAY` elapsed @param value The value to prepare @return `true` if success./
function _prepare( bytes32 key, uint256 value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingUInts256[key] = value; emit ConfigPreparedNumber(key, value, delay); return true; }
1,472,096
[ 1, 18486, 392, 2254, 5034, 716, 1410, 506, 3294, 329, 358, 326, 6835, 1839, 1375, 67, 6236, 67, 26101, 68, 9613, 225, 460, 1021, 460, 358, 2911, 327, 1375, 3767, 68, 309, 2216, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 9366, 12, 203, 3639, 1731, 1578, 498, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 2254, 5034, 4624, 203, 565, 262, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 389, 9366, 15839, 12, 856, 16, 4624, 1769, 203, 3639, 4634, 14342, 87, 5034, 63, 856, 65, 273, 460, 31, 203, 3639, 3626, 1903, 15464, 1854, 12, 856, 16, 460, 16, 4624, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x429346eFC2131B479c0b0d2e52146D4EfBeB37FA/sources/contracts/nft/nft/Battle.sol
The CryptoZooNFT TOKEN!
IZoonERC20 public zoonerToken;
16,222,888
[ 1, 1986, 15629, 62, 5161, 50, 4464, 14275, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 467, 62, 83, 265, 654, 39, 3462, 1071, 998, 83, 31430, 1345, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./libraries/BoringMath.sol"; import "./libraries/SignedSafeMath.sol"; import "./libraries/BoringERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /************************************************************************************************ Originally from https://github.com/sushiswap/sushiswap/blob/master/contracts/MasterChefV2.sol and https://github.com/sdaoswap/sushiswap/blob/master/contracts/MasterChef.sol This source code has been modified from the original, which was copied from the github repository at commit hash 10148a31d9192bc803dac5d24fe0319b52ae99a4. *************************************************************************************************/ contract SDAOTokenStaking is Ownable { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using SignedSafeMath for int256; //========== Structs ========== /// @dev Info of each user. /// @param amount LP token amount the user has provided. /// @param rewardDebt The amount of rewards entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } /// @dev Info of each rewards pool. /// @param tokenPerBlock Reward tokens per block number. /// @param lpSupply Total staked amount. /// @param accRewardsPerShare Total rewards accumulated per staked token. /// @param lastRewardBlock Last time rewards were updated for the pool. /// @param endOfEpochBlock End of epoc block number for compute and to avoid deposits. struct PoolInfo { uint256 tokenPerBlock; uint256 lpSupply; uint128 accRewardsPerShare; uint64 lastRewardBlock; uint endOfEpochBlock; } //========== Constants ========== /// @dev For percision calculation while computing the rewards. uint256 private constant ACC_REWARDS_PRECISION = 1e18; /// @dev ERC20 token used to distribute rewards. IERC20 public immutable rewardsToken; /** ========== Storage ========== */ /// @dev Indicates whether a staking pool exists for a given staking token. //mapping(address => bool) public stakingPoolExists; /// @dev Info of each staking pool. PoolInfo[] public poolInfo; /// @dev Address of the LP token for each staking pool. mapping(uint256 => IERC20) public lpToken; /// @dev Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; /// @dev Account allowed to allocate points. address public pointsAllocator; /// @dev Total rewards received from governance for distribution. /// Used to return remaining rewards if staking is canceled. uint256 public totalRewardsReceived; // ========== Events ========== event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition(uint256 indexed pid, IERC20 indexed lpToken); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accRewardsPerShare); event RewardsAdded(uint256 amount); event PointsAllocatorSet(address pointsAllocator); // ========== Modifiers ========== /// @dev Ensure the caller is allowed to allocate points. modifier onlyPointsAllocatorOrOwner { require( msg.sender == pointsAllocator || msg.sender == owner(), "MultiTokenStaking: not authorized to allocate points" ); _; } // ========== Constructor ========== /// @dev During the deployment of the contract pass the ERC-20 contract address used for rewards. constructor(address _rewardsToken) public { rewardsToken = IERC20(_rewardsToken); } // ========== Governance ========== /// @dev Set the address of the points allocator. /// This account will have the ability to set allocation points for LP rewards. function setPointsAllocator(address _pointsAllocator) external onlyOwner { require(_pointsAllocator != address(0), "Invalid points allocator address."); pointsAllocator = _pointsAllocator; emit PointsAllocatorSet(_pointsAllocator); } /// @dev Add rewards to be distributed. /// Note: This function must be used to add rewards if the owner /// wants to retain the option to cancel distribution and reclaim /// undistributed tokens. function addRewards(uint256 amount) external onlyPointsAllocatorOrOwner { require(rewardsToken.balanceOf(msg.sender) > 0, "ERC20: not enough tokens to transfer"); totalRewardsReceived = totalRewardsReceived.add(amount); rewardsToken.safeTransferFrom(msg.sender, address(this), amount); emit RewardsAdded(amount); } // ========== Pools ========== /// @dev Add a new LP to the pool. /// Can only be called by the owner or the points allocator. /// @param _lpToken Address of the LP ERC-20 token. /// @param _sdaoPerBlock Rewards per block. /// @param _endofepochblock Epocs end block number. function add(IERC20 _lpToken, uint256 _sdaoPerBlock, uint64 _endofepochblock) public onlyPointsAllocatorOrOwner { //This is not needed as we are going to use the contract for multiple pools with the same LP Tokens //require(!stakingPoolExists[address(_lpToken)], " Staking pool already exists."); require(_endofepochblock > block.number, "Cannot create the pool for past time."); uint256 pid = poolInfo.length; lpToken[pid] = _lpToken; poolInfo.push(PoolInfo({ tokenPerBlock: _sdaoPerBlock, endOfEpochBlock:_endofepochblock, lastRewardBlock: block.number.to64(), lpSupply:0, accRewardsPerShare: 0 })); //stakingPoolExists[address(_lpToken)] = true; emit LogPoolAddition(pid, _lpToken); } /// @dev To get the rewards per block. function sdaoPerBlock(uint256 _pid) public view returns (uint256 amount) { PoolInfo memory pool = poolInfo[_pid]; amount = pool.tokenPerBlock; } /// @dev Update reward variables for all pools in `pids`. /// Note: This can become very expensive. /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePools(uint256[] calldata pids) external onlyOwner { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @dev Update reward variables of the given pool. /// @param _pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 _pid) private returns (PoolInfo memory pool) { pool = poolInfo[_pid]; uint256 lpSupply = pool.lpSupply; if (block.number > pool.lastRewardBlock && pool.lastRewardBlock < pool.endOfEpochBlock) { if(lpSupply > 0){ uint256 blocks; if(block.number < pool.endOfEpochBlock) { blocks = block.number.sub(pool.lastRewardBlock); } else { blocks = pool.endOfEpochBlock.sub(pool.lastRewardBlock); } uint256 sdaoReward = blocks.mul(sdaoPerBlock(_pid)); pool.accRewardsPerShare = pool.accRewardsPerShare.add((sdaoReward.mul(ACC_REWARDS_PRECISION) / lpSupply).to128()); } pool.lastRewardBlock = block.number.to64(); poolInfo[_pid] = pool; emit LogUpdatePool(_pid, pool.lastRewardBlock, lpSupply, pool.accRewardsPerShare); } } // ========== Users ========== /// @dev View function to see pending rewards on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending rewards for a given user. function pendingRewards(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRewardsPerShare = pool.accRewardsPerShare; uint256 lpSupply = pool.lpSupply; if (block.number > pool.lastRewardBlock && pool.lastRewardBlock < pool.endOfEpochBlock) { if(lpSupply > 0){ uint256 blocks; if(block.number < pool.endOfEpochBlock) { blocks = block.number.sub(pool.lastRewardBlock); } else { blocks = pool.endOfEpochBlock.sub(pool.lastRewardBlock); } uint256 sdaoReward = blocks.mul(sdaoPerBlock(_pid)); accRewardsPerShare = accRewardsPerShare.add(sdaoReward.mul(ACC_REWARDS_PRECISION) / lpSupply); } } pending = int256(user.amount.mul(accRewardsPerShare) / ACC_REWARDS_PRECISION).sub(user.rewardDebt).toUInt256(); } /// @dev Deposit LP tokens to earn rewards. /// @param _pid The index of the pool. See `poolInfo`. /// @param _amount LP token amount to deposit. /// @param _to The receiver of `_amount` deposit benefit. function deposit(uint256 _pid, uint256 _amount, address _to) public { // Input Validation require(_amount > 0 && _to != address(0), "Invalid inputs for deposit."); PoolInfo memory pool = updatePool(_pid); UserInfo storage user = userInfo[_pid][_to]; // check if epoch as ended or if pool doesnot exist require (pool.endOfEpochBlock > block.number,"This pool epoch has ended. Please join staking new session."); user.amount = user.amount.add(_amount); user.rewardDebt = user.rewardDebt.add(int256(_amount.mul(pool.accRewardsPerShare) / ACC_REWARDS_PRECISION)); // Add to total supply pool.lpSupply = pool.lpSupply.add(_amount); // Update the pool back poolInfo[_pid] = pool; // Interactions lpToken[_pid].safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _pid, _amount, _to); } /// @dev Withdraw LP tokens from the staking contract. /// @param _pid The index of the pool. See `poolInfo`. /// @param _amount LP token amount to withdraw. /// @param _to Receiver of the LP tokens. function withdraw(uint256 _pid, uint256 _amount, address _to) public { require(_to != address(0), "ERC20: transfer to the zero address"); PoolInfo memory pool = updatePool(_pid); UserInfo storage user = userInfo[_pid][msg.sender]; // Check whether user has deposited stake require(user.amount >= _amount && _amount > 0, "Invalid amount to withdraw."); // Effects user.rewardDebt = user.rewardDebt.sub(int256(_amount.mul(pool.accRewardsPerShare) / ACC_REWARDS_PRECISION)); user.amount = user.amount.sub(_amount); // Subtract from total supply pool.lpSupply = pool.lpSupply.sub(_amount); // Update the pool back poolInfo[_pid] = pool; // Interactions lpToken[_pid].safeTransfer(_to, _amount); emit Withdraw(msg.sender, _pid, _amount, _to); } /// @dev Harvest proceeds for transaction sender to `_to`. /// @param _pid The index of the pool. See `poolInfo`. /// @param _to Receiver of rewards. function harvest(uint256 _pid, address _to) public { require(_to != address(0), "ERC20: transfer to the zero address"); PoolInfo memory pool = updatePool(_pid); UserInfo storage user = userInfo[_pid][msg.sender]; int256 accumulatedRewards = int256(user.amount.mul(pool.accRewardsPerShare) / ACC_REWARDS_PRECISION); uint256 _pendingRewards = accumulatedRewards.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedRewards; // Interactions if(_pendingRewards > 0 ) { rewardsToken.safeTransfer(_to, _pendingRewards); } emit Harvest(msg.sender, _pid, _pendingRewards); } //// @dev Withdraw LP tokens and harvest accumulated rewards, sending both to `to`. /// @param _pid The index of the pool. See `poolInfo`. /// @param _amount LP token amount to withdraw. /// @param _to Receiver of the LP tokens and rewards. function withdrawAndHarvest(uint256 _pid, uint256 _amount, address _to) public { require(_to != address(0), "ERC20: transfer to the zero address"); PoolInfo memory pool = updatePool(_pid); UserInfo storage user = userInfo[_pid][msg.sender]; // Check if the user has stake in the pool require(user.amount >= _amount && _amount > 0, "Cannot withdraw more than staked."); int256 accumulatedRewards = int256(user.amount.mul(pool.accRewardsPerShare) / ACC_REWARDS_PRECISION); uint256 _pendingRewards = accumulatedRewards.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedRewards.sub(int256(_amount.mul(pool.accRewardsPerShare) / ACC_REWARDS_PRECISION)); user.amount = user.amount.sub(_amount); // Subtract from total supply pool.lpSupply = pool.lpSupply.sub(_amount); // Update the pool back poolInfo[_pid] = pool; // Interactions if(_pendingRewards > 0) { rewardsToken.safeTransfer(_to, _pendingRewards); } lpToken[_pid].safeTransfer(_to, _amount); emit Harvest(msg.sender, _pid, _pendingRewards); emit Withdraw(msg.sender, _pid, _amount, _to); } /// @dev Withdraw without caring about rewards. EMERGENCY ONLY. /// @param _pid The index of the pool. See `poolInfo`. /// @param _to Receiver of the LP tokens. function emergencyWithdraw(uint256 _pid, address _to) public { require(_to != address(0), "ERC20: transfer to the zero address"); UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; PoolInfo memory pool = updatePool(_pid); pool.lpSupply = pool.lpSupply.sub(amount); // Update the pool back poolInfo[_pid] = pool; // Note: transfer can fail or succeed if `amount` is zero. lpToken[_pid].safeTransfer(_to, amount); emit EmergencyWithdraw(msg.sender, _pid, amount, _to); } function withdrawETHAndAnyTokens(address token) external onlyOwner { msg.sender.send(address(this).balance); IERC20 Token = IERC20(token); uint256 currentTokenBalance = Token.balanceOf(address(this)); Token.safeTransfer(msg.sender, currentTokenBalance); } // ========== Getter Functions ========== function poolLength() external view returns (uint256) { return poolInfo.length; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, 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); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../interfaces/IERC20.sol"; // solhint-disable avoid-low-level-calls library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) function returnDataToString(bytes memory data) internal pure returns (string memory) { if (data.length >= 64) { return abi.decode(data, (string)); } else if (data.length == 32) { uint8 i = 0; while(i < 32 && data[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && data[i] != 0; i++) { bytesArray[i] = data[i]; } return string(bytesArray); } else { return "???"; } } /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // 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; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } function toUInt256(int256 a) internal pure returns (uint256) { require(a >= 0, "Integer < 0"); return uint256(a); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @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. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @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 () internal { 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 virtual 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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
@dev Deposit LP tokens to earn rewards. @param _pid The index of the pool. See `poolInfo`. @param _amount LP token amount to deposit. @param _to The receiver of `_amount` deposit benefit. Input Validation check if epoch as ended or if pool doesnot exist Add to total supply Update the pool back Interactions
function deposit(uint256 _pid, uint256 _amount, address _to) public { require(_amount > 0 && _to != address(0), "Invalid inputs for deposit."); PoolInfo memory pool = updatePool(_pid); UserInfo storage user = userInfo[_pid][_to]; require (pool.endOfEpochBlock > block.number,"This pool epoch has ended. Please join staking new session."); user.amount = user.amount.add(_amount); user.rewardDebt = user.rewardDebt.add(int256(_amount.mul(pool.accRewardsPerShare) / ACC_REWARDS_PRECISION)); pool.lpSupply = pool.lpSupply.add(_amount); poolInfo[_pid] = pool; lpToken[_pid].safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _pid, _amount, _to); }
14,872,261
[ 1, 758, 1724, 511, 52, 2430, 358, 425, 1303, 283, 6397, 18, 225, 389, 6610, 1021, 770, 434, 326, 2845, 18, 2164, 1375, 6011, 966, 8338, 225, 389, 8949, 511, 52, 1147, 3844, 358, 443, 1724, 18, 225, 389, 869, 1021, 5971, 434, 1375, 67, 8949, 68, 443, 1724, 27641, 7216, 18, 2741, 5684, 866, 309, 7632, 487, 16926, 578, 309, 2845, 1552, 902, 1005, 1436, 358, 2078, 14467, 2315, 326, 2845, 1473, 5294, 4905, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 443, 1724, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 16, 1758, 389, 869, 13, 1071, 288, 203, 203, 565, 2583, 24899, 8949, 405, 374, 597, 389, 869, 480, 1758, 12, 20, 3631, 315, 1941, 4540, 364, 443, 1724, 1199, 1769, 203, 203, 565, 8828, 966, 3778, 2845, 273, 1089, 2864, 24899, 6610, 1769, 203, 565, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 869, 15533, 203, 203, 565, 2583, 261, 6011, 18, 409, 951, 14638, 1768, 405, 1203, 18, 2696, 10837, 2503, 2845, 7632, 711, 16926, 18, 7801, 1233, 384, 6159, 394, 1339, 1199, 1769, 203, 377, 203, 565, 729, 18, 8949, 273, 729, 18, 8949, 18, 1289, 24899, 8949, 1769, 203, 565, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 266, 2913, 758, 23602, 18, 1289, 12, 474, 5034, 24899, 8949, 18, 16411, 12, 6011, 18, 8981, 17631, 14727, 2173, 9535, 13, 342, 18816, 67, 862, 16777, 3948, 67, 3670, 26913, 10019, 203, 203, 565, 2845, 18, 9953, 3088, 1283, 273, 2845, 18, 9953, 3088, 1283, 18, 1289, 24899, 8949, 1769, 203, 565, 2845, 966, 63, 67, 6610, 65, 273, 2845, 31, 203, 203, 565, 12423, 1345, 63, 67, 6610, 8009, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 203, 565, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 389, 6610, 16, 389, 8949, 16, 389, 869, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x4051F88D4f17B7E7F03F1a1E6C0180355b58D0Bb/sources/browser/Counters.sol
* @title Counters @author Matt Condon (@shrugs) @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number of elements in a mapping, issuing ERC721 ids, or counting request ids. Include with `using Counters for Counters.Counter;` Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never directly accessed./
library Counters { struct Counter { } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value -= 1; } }
12,308,185
[ 1, 18037, 225, 490, 4558, 735, 19752, 261, 36, 674, 8653, 564, 13, 225, 28805, 13199, 716, 848, 1338, 506, 28859, 578, 15267, 329, 635, 1245, 18, 1220, 848, 506, 1399, 425, 18, 75, 18, 358, 3298, 326, 1300, 434, 2186, 316, 279, 2874, 16, 3385, 22370, 4232, 39, 27, 5340, 3258, 16, 578, 22075, 590, 3258, 18, 12672, 598, 1375, 9940, 9354, 87, 364, 9354, 87, 18, 4789, 31, 68, 7897, 518, 353, 486, 3323, 358, 9391, 279, 8303, 2831, 3571, 598, 17071, 434, 1245, 16, 1375, 15016, 68, 848, 2488, 326, 288, 9890, 10477, 97, 9391, 866, 16, 1915, 1637, 12392, 16189, 18, 1220, 1552, 6750, 14025, 3434, 4084, 16, 316, 716, 326, 6808, 1375, 67, 1132, 68, 353, 5903, 5122, 15539, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 9354, 87, 288, 203, 203, 203, 565, 1958, 9354, 288, 203, 565, 289, 203, 203, 565, 445, 783, 12, 4789, 2502, 3895, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 3895, 6315, 1132, 31, 203, 565, 289, 203, 203, 565, 445, 5504, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 3639, 3895, 6315, 1132, 1011, 404, 31, 203, 565, 289, 203, 203, 565, 445, 15267, 12, 4789, 2502, 3895, 13, 2713, 288, 203, 3639, 3895, 6315, 1132, 273, 3895, 6315, 1132, 3947, 404, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x39D366C037B6Dc95dbC75c697456f0b6C05dc005/sources/browser/DSA_test/curveY.sol
* @dev Withdraw Token. @param token token address. @param amt token amount. @param unitAmt unit amount of curve_amt/token_amt with slippage. @param getId Get token amount at this ID from `InstaMemory` Contract. @param setId Set token amount at this ID in `InstaMemory` Contract./
function withdraw( address token, uint256 amt, uint256 unitAmt, uint getId, uint setId ) external payable { uint _amt = getUint(getId, amt); int128 tokenId = getTokenI(token); TokenInterface curveTokenContract = TokenInterface(getCurveTokenAddr()); ICurveZap curveZap = ICurveZap(getCurveZapAddr()); ICurve curveSwap = ICurve(getCurveSwapAddr()); uint _curveAmt; uint[4] memory _amts; if (_amt == uint(-1)) { _curveAmt = curveTokenContract.balanceOf(address(this)); _amt = curveZap.calc_withdraw_one_coin(_curveAmt, tokenId); _amts[uint(tokenId)] = _amt; _amts[uint(tokenId)] = _amt; _curveAmt = curveSwap.calc_token_amount(_amts, false); } uint _amt18 = convertTo18(TokenInterface(token).decimals(), _amt); uint _slippageAmt = wmul(unitAmt, _amt18); curveTokenContract.approve(address(curveZap), 0); curveTokenContract.approve(address(curveZap), _slippageAmt); curveZap.remove_liquidity_imbalance(_amts, _slippageAmt); setUint(setId, _amt); emit LogWithdraw(token, _amt, _curveAmt, getId, setId); bytes32 _eventCode = keccak256("LogWithdraw(address,uint256,uint256,uint256,uint256)"); bytes memory _eventParam = abi.encode(token, _amt, _curveAmt, getId, setId);
3,150,505
[ 1, 1190, 9446, 3155, 18, 225, 1147, 1147, 1758, 18, 225, 25123, 1147, 3844, 18, 225, 2836, 31787, 2836, 3844, 434, 8882, 67, 301, 88, 19, 2316, 67, 301, 88, 598, 272, 3169, 2433, 18, 225, 2634, 968, 1147, 3844, 622, 333, 1599, 628, 1375, 10773, 69, 6031, 68, 13456, 18, 225, 10446, 1000, 1147, 3844, 622, 333, 1599, 316, 1375, 10773, 69, 6031, 68, 13456, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 598, 9446, 12, 203, 565, 1758, 1147, 16, 203, 565, 2254, 5034, 25123, 16, 203, 565, 2254, 5034, 2836, 31787, 16, 203, 565, 2254, 2634, 16, 203, 565, 2254, 10446, 203, 225, 262, 3903, 8843, 429, 288, 203, 565, 2254, 389, 301, 88, 273, 336, 5487, 12, 26321, 16, 25123, 1769, 203, 565, 509, 10392, 1147, 548, 273, 9162, 45, 12, 2316, 1769, 203, 203, 565, 29938, 8882, 1345, 8924, 273, 29938, 12, 588, 9423, 1345, 3178, 10663, 203, 565, 467, 9423, 62, 438, 8882, 62, 438, 273, 467, 9423, 62, 438, 12, 588, 9423, 62, 438, 3178, 10663, 203, 565, 467, 9423, 8882, 12521, 273, 467, 9423, 12, 588, 9423, 12521, 3178, 10663, 203, 203, 565, 2254, 389, 16683, 31787, 31, 203, 565, 2254, 63, 24, 65, 3778, 389, 301, 3428, 31, 203, 565, 309, 261, 67, 301, 88, 422, 2254, 19236, 21, 3719, 288, 203, 1377, 389, 16683, 31787, 273, 8882, 1345, 8924, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 1377, 389, 301, 88, 273, 8882, 62, 438, 18, 12448, 67, 1918, 9446, 67, 476, 67, 12645, 24899, 16683, 31787, 16, 1147, 548, 1769, 203, 1377, 389, 301, 3428, 63, 11890, 12, 2316, 548, 25887, 273, 389, 301, 88, 31, 203, 1377, 389, 301, 3428, 63, 11890, 12, 2316, 548, 25887, 273, 389, 301, 88, 31, 203, 1377, 389, 16683, 31787, 273, 8882, 12521, 18, 12448, 67, 2316, 67, 8949, 24899, 301, 3428, 16, 629, 1769, 203, 565, 289, 203, 203, 203, 565, 2254, 389, 301, 88, 2643, 2 ]
// contracts/NFT.sol // SPDX-License-Identifier: MIT pragma solidity 0.7.4; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/payment/PaymentSplitter.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract NFT is ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address payable; address payable public vault; address public uriSigner; address public timelock; bool public paused; bool public isInitialized = false; uint16 private _tokenCount = 0; uint16 public constant maxTokenCount = 20000; // 20,000 tokens is the max uint256 public constant baseSolosPerUri = 40 ether; IERC20 public solos; struct MINTER { address minter; uint256 timestamp; } mapping(uint16 => MINTER) public minterLog; mapping(uint16 => string) public permanentURIArweave; // Events event PermanentURIAdded(uint256 tokenId, string arweaveHash); constructor() ERC721("SOLOS", "SOLOS") Ownable() {} modifier paymentRequired() { require(msg.value >= getCurrentPrice(), "Error: Payment required, or value below price"); vault.sendValue(msg.value); _; } modifier isMintable() { require(!paused, "Error: Token minting is paused"); require(_tokenCount <= maxTokenCount, "Error: Maximum number of tokens have been minted"); _; } modifier onlyInitializeOnce() { require(!isInitialized, "Error: contract is already initialized"); isInitialized = true; _; } modifier onlyTimelock() { require(msg.sender == timelock, "Error: caller is not timelock"); _; } function initialize( string memory baseURI, address payable _vault, address _uriSigner, IERC20 _solos, address _timelock ) public onlyOwner onlyInitializeOnce { // Vote Token solos = _solos; // Set the base uri _setBaseURI(baseURI); uriSigner = _uriSigner; // Set minting status paused = false; // Set the vault vault = _vault; // Address of the timelock timelock = _timelock; } /** * Mint Functions */ function mint() public payable isMintable paymentRequired returns (uint256) { // Log who bought the token and when minterLog[_tokenCount].minter = msg.sender; minterLog[_tokenCount].timestamp = block.timestamp; // Mint user current tokenId _mint(msg.sender, _tokenCount); // Increment id _tokenCount++; return _tokenCount; } // Artist can mint, but they can't claim solos for 15 years. function artistMint() public payable isMintable onlyOwner returns (uint256) { // Log who bought the token and when minterLog[_tokenCount].minter = msg.sender; minterLog[_tokenCount].timestamp = block.timestamp + 500000000e18; // 500 million Seconds; // Mint user current tokenId _mint(msg.sender, _tokenCount); // Increment id _tokenCount++; return _tokenCount; } function getCurrentPrice() public view returns (uint256) { return _getCurrentPrice(); } function _getCurrentPrice() internal view returns (uint256) { if (totalSupply() >= 19990) { return 100000000000000000000; // 16381 - 16383 100 ETH } else if (totalSupply() >= 18750) { return 5000000000000000000; // 16000 - 16380 5.0 ETH } else if (totalSupply() >= 17500) { return 3000000000000000000; // 15000 - 15999 3.0 ETH } else if (totalSupply() >= 15000) { return 1700000000000000000; // 11000 - 14999 1.7 ETH } else if (totalSupply() >= 12500) { return 900000000000000000; // 7000 - 10999 0.9 ETH } else if (totalSupply() >= 10000) { return 500000000000000000; // 3000 - 6999 0.5 ETH } else if (totalSupply() >= 5000) { return 300000000000000000; // 3000 - 6999 0.3 ETH } else if (totalSupply() >= 2500) { return 200000000000000000; // 2500 - 5000 0.2 ETH } else if (totalSupply() >= 1500) { return 150000000000000000; // 2500 - 5000 0.15 ETH } else if (totalSupply() >= 500) { return 100000000000000000; // 201 - 2500 0.1 ETH } else if (totalSupply() >= 250) { return 50000000000000000; // 201 - 2500 0.05 ETH } else if (totalSupply() >= 100) { return 10000000000000000; // 201 - 2500 0.01 ETH } else { return 0; // 0 - 100 free } } function createPermanentURI( bytes memory signature, string memory arweaveHash, uint16 tokenId ) public nonReentrant { // Note on Underlow for TokenID // This does not seem to be a danger, because we WANT tokens to be claimed. Only the onwer can claim in 24 hours, so it's fine if a underflow happens. // in any case that should not pass the signature check. // check to be sure this tokenID has not been claimed require( keccak256(abi.encodePacked(permanentURIArweave[tokenId])) == keccak256(abi.encodePacked("")), "Error: TokenId already claimed" ); // Check to make sure this tokenID is inbounds: require(tokenId <= maxTokenCount, "Error: Maximum number of tokens have been minted"); // Give the minter a 3 day lead time to claim these tokens if (msg.sender != minterLog[tokenId].minter) { require( block.timestamp > minterLog[tokenId].timestamp + 3 days, "Error: Minters 1 day delay not yet expired" ); } // Check the signature require(_isValidData(tokenId, arweaveHash, signature), "Error: signature did not match"); // Update the token URI permanentURIArweave[tokenId] = arweaveHash; // Give users community Solos for this solos.transfer(msg.sender, baseSolosPerUri); // Make the Data permanently availible emit PermanentURIAdded(tokenId, arweaveHash); } // Pause only the minting function pause(bool _paused) public onlyOwner { paused = _paused; } // Release solos that might be held by this contract function releaseSolos(address recipient, uint256 amount) public onlyTimelock { solos.transfer(recipient, amount); } // only timelock // Update Base URI function updateBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } // Signature recovery function _isValidData( uint16 tokenid, string memory arweave, bytes memory sig ) internal view returns (bool) { bytes32 message = keccak256(abi.encodePacked(tokenid, arweave)); return (recoverSigner(message, sig) == uriSigner); } function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); } function splitSignature(bytes memory sig) public pure returns ( uint8, bytes32, bytes32 ) { require(sig.length == 65, "Error: Signature does not have proper length"); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; import "../math/SafeMath.sol"; import "../utils/Address.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitter is Context { using SafeMath for uint256; event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor (address[] memory payees, uint256[] memory shares_) public payable { // solhint-disable-next-line max-line-length require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive () external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance.add(_totalReleased); uint256 payment = totalReceived.mul(_shares[account]).div(_totalShares).sub(_released[account]); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account].add(payment); _totalReleased = _totalReleased.add(payment); Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares.add(shares_); emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @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"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { 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); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _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 make 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @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. */ abstract 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 () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual 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 virtual 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 virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @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. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @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) { 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, reverting 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) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting 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) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * 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); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * 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); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Note on Underlow for TokenID This does not seem to be a danger, because we WANT tokens to be claimed. Only the onwer can claim in 24 hours, so it's fine if a underflow happens. in any case that should not pass the signature check. check to be sure this tokenID has not been claimed Check to make sure this tokenID is inbounds: Give the minter a 3 day lead time to claim these tokens
function createPermanentURI( bytes memory signature, string memory arweaveHash, uint16 tokenId ) public nonReentrant { require( keccak256(abi.encodePacked(permanentURIArweave[tokenId])) == keccak256(abi.encodePacked("")), "Error: TokenId already claimed" ); require(tokenId <= maxTokenCount, "Error: Maximum number of tokens have been minted"); if (msg.sender != minterLog[tokenId].minter) { require( block.timestamp > minterLog[tokenId].timestamp + 3 days, "Error: Minters 1 day delay not yet expired" ); } }
14,017,486
[ 1, 8067, 603, 21140, 821, 364, 3155, 734, 1220, 1552, 486, 19264, 358, 506, 279, 27308, 16, 2724, 732, 678, 6856, 2430, 358, 506, 7516, 329, 18, 5098, 326, 603, 2051, 848, 7516, 316, 4248, 7507, 16, 1427, 518, 1807, 11079, 309, 279, 3613, 2426, 10555, 18, 316, 1281, 648, 716, 1410, 486, 1342, 326, 3372, 866, 18, 866, 358, 506, 3071, 333, 1147, 734, 711, 486, 2118, 7516, 329, 2073, 358, 1221, 3071, 333, 1147, 734, 353, 316, 10576, 30, 22374, 326, 1131, 387, 279, 890, 2548, 5871, 813, 358, 7516, 4259, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 24159, 3098, 12, 203, 3639, 1731, 3778, 3372, 16, 203, 3639, 533, 3778, 419, 1814, 836, 2310, 16, 203, 3639, 2254, 2313, 1147, 548, 203, 565, 262, 1071, 1661, 426, 8230, 970, 288, 203, 203, 3639, 2583, 12, 203, 5411, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 457, 4728, 319, 3098, 686, 1814, 836, 63, 2316, 548, 22643, 422, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 2932, 7923, 3631, 203, 5411, 315, 668, 30, 3155, 548, 1818, 7516, 329, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 2316, 548, 1648, 943, 1345, 1380, 16, 315, 668, 30, 18848, 1300, 434, 2430, 1240, 2118, 312, 474, 329, 8863, 203, 203, 3639, 309, 261, 3576, 18, 15330, 480, 1131, 387, 1343, 63, 2316, 548, 8009, 1154, 387, 13, 288, 203, 5411, 2583, 12, 203, 7734, 1203, 18, 5508, 405, 1131, 387, 1343, 63, 2316, 548, 8009, 5508, 397, 890, 4681, 16, 203, 7734, 315, 668, 30, 490, 2761, 87, 404, 2548, 4624, 486, 4671, 7708, 6, 203, 5411, 11272, 203, 3639, 289, 203, 203, 203, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "./HasAuditRegistry.sol"; /* @title Proof of Life Proxy with delegateCall */ contract ProofOfLifeProxy is HasAuditRegistry { // State variables mapping(address => bool) public authorizedUsers; address public contractOwner; bool public isOpenToEveryUser; bool public isLocked; uint256 public lastId = 0; mapping(bytes32 => uint256) public idByDocumentHash; mapping(uint256 => address) public ownerByDocumentId; mapping(uint256 => string) public ipfsHashByDocumentId; mapping(uint256 => bytes32) public hashByDocumentId; mapping(address => uint256[]) public documentsByOwnerAddress; mapping(uint256 => AuditRegistry[]) public auditRegistryByDocumentId; // Delegate call address address public delegateCallAddress; // Events event DelegateCallEvent (string call, bool result); // Modifiers modifier onlyContractOwner(){ require(msg.sender == contractOwner, "E-POLP-001 - Only the proxy contract owner add execute this transaction"); _; } // ------ Local functions to update proxy configuration ------- /* @notice Proxy constructor * @dev It creates a proxy instance * @param _existingContractAddress - the new delegated contract address */ constructor (address existingContractAddress) public { delegateCallAddress = existingContractAddress; contractOwner = msg.sender; authorizedUsers[contractOwner] = true; } /* @notice Update Delegate Call Address * @dev It allows the owner to update the address of the delegate contract * @param _existingContractAddress - the new delegated contract address */ function updateDelegateCallAddress(address existingContractAddress) public onlyContractOwner { delegateCallAddress = existingContractAddress; } // ---- Functions with delegateCall ----- /* @notice Lock contract * @dev Maintenance and security circuit locker */ function lock() public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodePacked(bytes4(keccak256("lock()")))); emit DelegateCallEvent("lock", success); } /* @notice Unlock contract * @dev Maintenance and security circuit locker */ function unlock() public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodePacked(bytes4(keccak256("unlock()")))); emit DelegateCallEvent("unlock", success); } /* @notice Add authorized user * @dev Includes a new user in the authorized users list * @param user - the address you want to authorize */ function addAuthorizedUser(address user) public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("addAuthorizedUser(address)", user)); if (success) { emit DelegateCallEvent("addAuthorizedUser", success); } else { revert(); } } /* @notice Remove credentials * @dev Remove credentials of an authorized user * @param user - the authorized address to be removed */ function removeCredentials(address user) public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("removeCredentials(address)", user)); if (success) { emit DelegateCallEvent("removeCredentials", success); } else { revert(); } } /* @notice Open to every user * @dev Allows every address to certify documents in the contract */ function openToEveryUser() public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("openToEveryUser()")); if (success) { emit DelegateCallEvent("openToEveryUser", success); } else { revert(); } } /* @notice Close to authorized users * @dev Only allows document certification to authorized users */ function closeToAuthorizedUsers() public onlyContractOwner { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("closeToAuthorizedUsers()")); if (success) { emit DelegateCallEvent("closeToAuthorizedUsers", success); } else { revert(); } } /* @notice Certify document creation with hash and timestamp * @dev It registers in the blockchain the proof-of-existence of an external document * @param _documentHash - Hash of the document (it should have 32 bytes) * @param _ipfsHash - IPFS Hash, if it exists * @return id - returns certified document id */ function certifyDocumentCreationWithIPFSHash(bytes32 _documentHash, string memory _ipfsHash, string memory _timestamp) public { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("certifyDocumentCreationWithIPFSHash(bytes32,string,string)", _documentHash, _ipfsHash, _timestamp)); if (success) { emit DelegateCallEvent("certifyDocumentCreationWithIPFSHash", success); } else { revert(); } } /* @notice Append Audit Registry * @dev A document owner can use this function to append audit information to it * @param _id - Id of the document * @param _description - Content of the audit registry (status change, extra information, etc...) * @param _timestamp - Local timestamp (UNIX Epoch format) from the external * system or the UI which executes the contract */ function appendAuditRegistry(uint256 _id, string memory _description, string memory _timestamp) public { (bool success, bytes memory data) = delegateCallAddress.delegatecall(abi.encodeWithSignature("appendAuditRegistry(uint256,string,string)", _id, _description, _timestamp)); if (success) { emit DelegateCallEvent("appendAuditRegistry", success); } else { revert(); } } // ------ Query functions to request information about the contract state ------- /* @notice Get documents by owner * @dev Retrieves a list with all the documents ids of one owner * @return bytes32[] documentsByOwnerAddress */ function getDocumentsByOwner(address owner) public view returns(uint256[] memory) { return documentsByOwnerAddress[owner]; } /* @notice Get Document Details * @dev Retrieves all the information of a document * @param _documentHash - Hash of the document * @return uint256 id, string docHash, string ipfsHash, address documentOwner */ function getDocumentDetailsByHash(bytes32 _documentHash) public view returns (uint256, bytes32, string memory, address) { uint256 _id = getId(_documentHash); return (_id, hashByDocumentId[_id], ipfsHashByDocumentId[_id], ownerByDocumentId[_id]); } /* @notice Get auditRegistry by documentHash * @dev Retrieves the audit registry of a document * @param _documentHash - Hash of the document * @param _index - Position of the auditRegistry in the list * @return string description, string timestamp, uint256 blockTimestamp */ function getAuditRegistryByDocumentHash(bytes32 _documentHash, uint256 _index) public view returns (string memory, string memory, uint256) { uint256 _id = getId(_documentHash); return getAuditRegistryByDocumentId(_id, _index); } /* @notice CountAuditRegistries by hash * @dev Count the number of audit registries of a document * @param _documentHash - Hash of the document * @return uint256 number of elements */ function countAuditRegistriesByDocumentHash(bytes32 _documentHash) public view returns(uint256) { uint256 _id = getId(_documentHash); return auditRegistryByDocumentId[_id].length; } /* @notice Get Document Details * @dev Retrieves all the information of a document * @param _id - Id of the document * @return uint256 id, string docHash, address documentOwner */ function getDocumentDetailsById(uint256 _id) public view returns (uint256, bytes32, string memory, address) { return (_id, hashByDocumentId[_id], ipfsHashByDocumentId[_id], ownerByDocumentId[_id]); } /* @notice Get auditRegistry by documentId * @dev Retrieves the audit registry of a document * @param _id - Id of the document * @param _index - Position of the auditRegistry in the list * @return string description, string timestamp, uint256 blockTimestamp */ function getAuditRegistryByDocumentId(uint256 _id, uint256 _index) public view returns (string memory, string memory, uint256) { return (auditRegistryByDocumentId[_id][_index].description, auditRegistryByDocumentId[_id][_index].timestamp, auditRegistryByDocumentId[_id][_index].blockTimestamp); } /* @notice Get document id from hash * @dev Retrieves a document id from a string with the hash * @param _documentHash - Hash of the document * @return uint256 */ function getId(bytes32 _documentHash) public view returns(uint256) { return idByDocumentHash[_documentHash]; } }
@notice Get documents by owner @dev Retrieves a list with all the documents ids of one owner @return bytes32[] documentsByOwnerAddress/
function getDocumentsByOwner(address owner) public view returns(uint256[] memory) { return documentsByOwnerAddress[owner]; }
13,012,392
[ 1, 967, 7429, 635, 3410, 225, 20507, 279, 666, 598, 777, 326, 7429, 3258, 434, 1245, 3410, 327, 1731, 1578, 8526, 7429, 858, 5541, 1887, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9956, 87, 858, 5541, 12, 2867, 3410, 13, 1071, 1476, 7010, 565, 1135, 12, 11890, 5034, 8526, 3778, 13, 288, 203, 3639, 327, 7429, 858, 5541, 1887, 63, 8443, 15533, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; // A 2/3 multisig contract which is compatible with Trezor-signed messages. // // To authorize a spend, two signtures must be provided by 2 of the 3 owners. // To generate the message to be signed, provide the destination address and // spend amount (in wei) to the generateMessageToSignmethod. // The signatures must be provided as the (v, r, s) hex-encoded coordinates. // The S coordinate must be 0x00 or 0x01 corresponding to 0x1b and 0x1c, respectively. // See the test file for example inputs. // // If you use other software than the provided dApp or scripts to sign the message, // verify that the message shown by the trezor device matches the generated message in hex. // // WARNING: The generated message is only valid until the next spend is executed. // after that, a new message will need to be calculated. // // WARNING: The signing algorithm Trezor uses is different than that // of Ledger, Geth, Etc. This contract is for Trezor managed private // keys ONLY. // // ADDITIONAL WARNING: This contract is **NOT** ERC20 compatible. // Tokens sent to this contract will be lost forever. // contract TrezorMultiSig2of3 { // The 3 addresses which control the funds in this contract. The // owners of 2 of these addresses will need to both sign a message // allowing the funds in this contract to be spent. mapping(address => bool) private owners; // The contract nonce is not accessible to the contract so we // implement a nonce-like variable for replay protection. uint256 public spendNonce = 0; // Contract Versioning uint256 public unchainedMultisigVersionMajor = 1; uint256 public unchainedMultisigVersionMinor = 0; // An event sent when funds are received. event Funded(uint new_balance); // An event sent when a spend is triggered to the given address. event Spent(address to, uint transfer); // Instantiate a new Trezor Multisig 2 of 3 contract owned by the // three given addresses function TrezorMultiSig2of3(address owner1, address owner2, address owner3) public { address zeroAddress = 0x0; require(owner1 != zeroAddress); require(owner2 != zeroAddress); require(owner3 != zeroAddress); require(owner1 != owner2); require(owner2 != owner3); require(owner1 != owner3); owners[owner1] = true; owners[owner2] = true; owners[owner3] = true; } // The fallback function for this contract. function() public payable { Funded(this.balance); } // Generates the message to sign given the output destination address and amount. // includes this contract's address and a nonce for replay protection. // One option to independently verify: https://leventozturk.com/engineering/sha3/ and select keccak function generateMessageToSign(address destination, uint256 value) public constant returns (bytes32) { require(destination != address(this)); bytes32 message = keccak256(spendNonce, this, value, destination); return message; } // Send the given amount of ETH to the given destination using // the two triplets (v1, r1, s1) and (v2, r2, s2) as signatures. // s1 and s2 should be 0x00 or 0x01 corresponding to 0x1b and 0x1c respectively. function spend(address destination, uint256 value, uint8 v1, bytes32 r1, bytes32 s1, uint8 v2, bytes32 r2, bytes32 s2) public { // This require is handled by generateMessageToSign() // require(destination != address(this)); require(this.balance >= value); require(_validSignature(destination, value, v1, r1, s1, v2, r2, s2)); spendNonce = spendNonce + 1; destination.transfer(value); Spent(destination, value); } // Confirm that the two signature triplets (v1, r1, s1) and (v2, r2, s2) // both authorize a spend of this contract's funds to the given // destination address. function _validSignature(address destination, uint256 value, uint8 v1, bytes32 r1, bytes32 s1, uint8 v2, bytes32 r2, bytes32 s2) private constant returns (bool) { bytes32 message = _messageToRecover(destination, value); address addr1 = ecrecover(message, v1+27, r1, s1); address addr2 = ecrecover(message, v2+27, r2, s2); require(_distinctOwners(addr1, addr2)); return true; } // Generate the the unsigned message (in bytes32) that each owner's // Trezor would have signed for the given destination and amount. // // The generated message from generateMessageToSign is converted to // ascii when signed by a trezor. // // The required Trezor signing prefix, the length of this // unsigned message, and the unsigned ascii message itself are // then concatenated and hashed with keccak256. function _messageToRecover(address destination, uint256 value) private constant returns (bytes32) { bytes32 hashedUnsignedMessage = generateMessageToSign(destination, value); bytes memory unsignedMessageBytes = _hashToAscii(hashedUnsignedMessage); bytes memory prefix = "\x19Ethereum Signed Message:\n"; return keccak256(prefix,bytes1(unsignedMessageBytes.length),unsignedMessageBytes); } // Confirm the pair of addresses as two distinct owners of this contract. function _distinctOwners(address addr1, address addr2) private constant returns (bool) { // Check that both addresses are different require(addr1 != addr2); // Check that both addresses are owners require(owners[addr1]); require(owners[addr2]); return true; } // Construct the byte representation of the ascii-encoded // hashed message written in hex. function _hashToAscii(bytes32 hash) private pure returns (bytes) { bytes memory s = new bytes(64); for (uint i = 0; i < 32; i++) { byte b = hash[i]; byte hi = byte(uint8(b) / 16); byte lo = byte(uint8(b) - 16 * uint8(hi)); s[2*i] = _char(hi); s[2*i+1] = _char(lo); } return s; } // Convert from byte to ASCII of 0-f // http://www.unicode.org/charts/PDF/U0000.pdf function _char(byte b) private pure returns (byte c) { if (b < 10) return byte(uint8(b) + 0x30); else return byte(uint8(b) + 0x57); } }
The fallback function for this contract.
function() public payable { Funded(this.balance); }
6,868,298
[ 1, 1986, 5922, 445, 364, 333, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1435, 1071, 8843, 429, 288, 203, 565, 478, 12254, 12, 2211, 18, 12296, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.8; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); } /** * @title ERC20 Airdrop dapp smart contract */ contract Airdrop { IERC20 private _token = IERC20(0x00FbE7398D9F0D53fBaef6E2F4C6Ab0e7c31f5D7); /** * @dev doAirdrop is the main method for distribution * by default, the contract gonna send 100 tokens per address * @param addresses array of addresses to airdrop */ function doAirdrop(address[] calldata addresses) external returns (uint256) { uint256 i = 0; while (i < addresses.length) { _token.transferFrom(msg.sender, addresses[i], 100 * 1 ether); i += 1; } return i; } }
* @dev doAirdrop is the main method for distribution by default, the contract gonna send 100 tokens per address @param addresses array of addresses to airdrop/
function doAirdrop(address[] calldata addresses) external returns (uint256) { uint256 i = 0; while (i < addresses.length) { _token.transferFrom(msg.sender, addresses[i], 100 * 1 ether); i += 1; } return i; }
1,087,190
[ 1, 2896, 37, 6909, 1764, 353, 326, 2774, 707, 364, 7006, 635, 805, 16, 326, 6835, 314, 265, 6582, 1366, 2130, 2430, 1534, 1758, 225, 6138, 526, 434, 6138, 358, 279, 6909, 1764, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 741, 37, 6909, 1764, 12, 2867, 8526, 745, 892, 6138, 13, 3903, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 277, 273, 374, 31, 203, 203, 565, 1323, 261, 77, 411, 6138, 18, 2469, 13, 288, 203, 1377, 389, 2316, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 6138, 63, 77, 6487, 2130, 380, 404, 225, 2437, 1769, 203, 1377, 277, 1011, 404, 31, 203, 565, 289, 203, 203, 565, 327, 277, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.7; contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value) public; } contract IRC223 { uint public totalSupply; function balanceOf(address who) public view returns (uint); function name() public view returns (string memory _name); function symbol() public view returns (string memory _symbol); function decimals() public view returns (uint8 _decimals); function transfer(address to, uint value) public; event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract PIBC is IRC223 { using SafeMath for uint; mapping(address => uint) public balances; mapping(address => mapping (address => uint)) public approved; mapping(address => mapping (address => uint)) public ttl; string private _name; string private _symbol; uint8 _decimals; uint public commisionRate; address private _owner; address private _commisioner; //0x4E911d2D6B83e4746055ccb167596bF9f2e680d2 event Commision(uint256 commision); uint private _ttlLimit; constructor(address commisioner, address owner) public{ _name = "Pi token"; _symbol = "PIT"; _decimals = 5; totalSupply = 10000000000000000000; balances[owner] = totalSupply; _owner = owner; _commisioner = commisioner; commisionRate = 10000; _ttlLimit = 360; } function name() public view returns (string memory){ return _name; } function symbol() public view returns (string memory){ return _symbol; } function decimals() public view returns (uint8){ return _decimals; } function _transfer(address _to, address _from, uint _value) internal{ require(balances[_from] >= _value); uint codeLength; uint256 commision; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); commision = _value.div(commisionRate); balances[_from] = balances[_from].sub(commision); balances[_commisioner] = balances[_commisioner].add(commision); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(_from, _value); } emit Transfer(_from, _to, _value, empty); emit Commision(commision); } function transfer(address _to, uint _value) public { _transfer(_to, msg.sender,_value); } function transferFrom (address _to, address _from) public { require(approved[_from][_to] > 0); require(ttl[msg.sender][_to] > block.number); uint _value = approved[_from][_to]; ttl[msg.sender][_to] = 0; approved[_from][_to] = 0; _transfer(_to, _from, _value); } function approve (address _to, uint _value) public{ require(_value <= balances[msg.sender]); approved[msg.sender][_to] = approved[msg.sender][_to].add(_value); ttl[msg.sender][_to] = block.number.add(_ttlLimit); } function balanceOf(address _user) public view returns (uint balance) { return balances[_user]; } function setTtl(uint ttlLimit) public { require(tx.origin == _owner); //inject USING TX ORIGIN FOR AUTHENTICATION _ttlLimit = ttlLimit; } function setCommisionRate (uint _commisionRate) public { require(tx.origin == _owner); //inject USING TX ORIGIN FOR AUTHENTICATION commisionRate = _commisionRate; } function setCommisioner (address commisioner) public { require(tx.origin == _owner); //inject USING TX ORIGIN FOR AUTHENTICATION _commisioner = commisioner; } }
inject USING TX ORIGIN FOR AUTHENTICATION
require(tx.origin == _owner);
5,500,522
[ 1, 22170, 11836, 1360, 23211, 24069, 7702, 12108, 12790, 18915, 2689, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 978, 18, 10012, 422, 389, 8443, 1769, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x67b2f86d081C34259F0F65117923d2FdD5CC7788/sources/contracts/Dice.sol
`X mod 6` returns 0-5, so need to subtract side selected by 1 to get real result
function _settleRollDice(uint256 requestId, uint256 randomNumber) internal { address _user = _rollDiceInitUser[requestId]; require(_user != address(0), 'dice record does not exist'); require(!_rollDiceInitSettled[requestId], 'already settled'); _rollDiceInitSettled[requestId] = true; uint256 _amountWagered = _rollDiceInitAmount[requestId]; uint256 _nonce = _rollDiceInitNonce[requestId]; uint256 _amountToWin = (_amountWagered * payoutMultiple) / PERCENT_DENOMENATOR; uint8 _sideSelected = _rollDiceInitSideSelected[requestId]; bool _didUserWin = randomNumber % 6 == _sideSelected - 1; uint8 _sideRolled = uint8(randomNumber % 6) + 1; sidesRolled[_sideRolled]++; if (_didUserWin) { smol.transfer(_user, _amountWagered); smol.gameMint(_user, _amountToWin); diceWon++; diceAmountWon += _amountToWin; diceUserWon[_user]++; diceUserAmountWon[_user] += _amountToWin; lastRollDiceWon[_user] = true; smol.gameBurn(address(this), _amountWagered); diceLost++; diceAmountLost += _amountWagered; diceUserLost[_user]++; diceUserAmountLost[_user] += _amountWagered; lastRollDiceWon[_user] = false; } emit GetDiceResult( _user, _nonce, _sideSelected, requestId, _amountWagered, _sideRolled, _didUserWin, _amountToWin ); }
15,534,654
[ 1, 68, 60, 681, 1666, 68, 1135, 374, 17, 25, 16, 1427, 1608, 358, 10418, 4889, 3170, 635, 404, 358, 336, 2863, 563, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 542, 5929, 24194, 40, 1812, 12, 11890, 5034, 14459, 16, 2254, 5034, 2744, 1854, 13, 2713, 288, 203, 565, 1758, 389, 1355, 273, 389, 2693, 40, 1812, 2570, 1299, 63, 2293, 548, 15533, 203, 565, 2583, 24899, 1355, 480, 1758, 12, 20, 3631, 296, 72, 1812, 1409, 1552, 486, 1005, 8284, 203, 565, 2583, 12, 5, 67, 2693, 40, 1812, 2570, 694, 88, 1259, 63, 2293, 548, 6487, 296, 17583, 26319, 1259, 8284, 203, 565, 389, 2693, 40, 1812, 2570, 694, 88, 1259, 63, 2293, 548, 65, 273, 638, 31, 203, 203, 565, 2254, 5034, 389, 8949, 59, 6817, 329, 273, 389, 2693, 40, 1812, 2570, 6275, 63, 2293, 548, 15533, 203, 565, 2254, 5034, 389, 12824, 273, 389, 2693, 40, 1812, 2570, 13611, 63, 2293, 548, 15533, 203, 565, 2254, 5034, 389, 8949, 774, 18049, 273, 261, 67, 8949, 59, 6817, 329, 380, 293, 2012, 8438, 13, 342, 203, 1377, 10950, 19666, 67, 13296, 51, 16196, 3575, 31, 203, 565, 2254, 28, 389, 5564, 7416, 273, 389, 2693, 40, 1812, 2570, 8895, 7416, 63, 2293, 548, 15533, 203, 565, 1426, 389, 14044, 1299, 18049, 273, 2744, 1854, 738, 1666, 422, 389, 5564, 7416, 300, 404, 31, 203, 565, 2254, 28, 389, 5564, 4984, 1259, 273, 2254, 28, 12, 9188, 1854, 738, 1666, 13, 397, 404, 31, 203, 565, 22423, 4984, 1259, 63, 67, 5564, 4984, 1259, 3737, 15, 31, 203, 203, 565, 309, 261, 67, 14044, 1299, 18049, 13, 288, 203, 1377, 3029, 355, 18, 13866, 24899, 1355, 16, 389, 2 ]
//Address: 0xd571788859897023b500c6c7fd295bba1e7ff71c //Contract name: SportStarMaster //Balance: 0.003422924159669719 Ether //Verification Date: 3/9/2018 //Transacion Count: 4 // CODE STARTS HERE pragma solidity ^0.4.18; // solhint-disable-line /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } contract SportStarToken is ERC721 { // ***** EVENTS // @dev Transfer event as defined in current draft of ERC721. // ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); // ***** STORAGE // @dev A mapping from token IDs to the address that owns them. All tokens have // some valid owner address. mapping (uint256 => address) public tokenIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; // @dev A mapping from TokenIDs to an address that has been approved to call // transferFrom(). Each Token can only have one approved address for transfer // at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public tokenIndexToApproved; // Additional token data mapping (uint256 => bytes32) public tokenIndexToData; address public ceoAddress; address public masterContractAddress; uint256 public promoCreatedCount; // ***** DATATYPES struct Token { string name; } Token[] private tokens; // ***** ACCESS MODIFIERS modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyMasterContract() { require(msg.sender == masterContractAddress); _; } // ***** CONSTRUCTOR function SportStarToken() public { ceoAddress = msg.sender; } // ***** PRIVILEGES SETTING FUNCTIONS function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setMasterContract(address _newMasterContract) public onlyCEO { require(_newMasterContract != address(0)); masterContractAddress = _newMasterContract; } // ***** PUBLIC FUNCTIONS // @notice Returns all the relevant information about a specific token. // @param _tokenId The tokenId of the token of interest. function getToken(uint256 _tokenId) public view returns ( string tokenName, address owner ) { Token storage token = tokens[_tokenId]; tokenName = token.name; owner = tokenIndexToOwner[_tokenId]; } // @param _owner The owner whose sport star tokens we are interested in. // @dev This method MUST NEVER be called by smart contract code. First, it's fairly // expensive (it walks the entire Tokens array looking for tokens belonging to owner), // but it also returns a dynamic array, which is only supported for web3 calls, and // not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns (uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalTokens = totalSupply(); uint256 resultIndex = 0; uint256 tokenId; for (tokenId = 0; tokenId <= totalTokens; tokenId++) { if (tokenIndexToOwner[tokenId] == _owner) { result[resultIndex] = tokenId; resultIndex++; } } return result; } } function getTokenData(uint256 _tokenId) public view returns (bytes32 tokenData) { return tokenIndexToData[_tokenId]; } // ***** ERC-721 FUNCTIONS // @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). // @param _to The address to be granted transfer approval. Pass address(0) to // clear all approvals. // @param _tokenId The ID of the Token that can be transferred if this call succeeds. function approve(address _to, uint256 _tokenId) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); tokenIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } // For querying balance of a particular account // @param _owner The address for balance query function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } function name() public pure returns (string) { return "CryptoSportStars"; } function symbol() public pure returns (string) { return "SportStarToken"; } function implementsERC721() public pure returns (bool) { return true; } // For querying owner of token // @param _tokenId The tokenID for owner inquiry function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = tokenIndexToOwner[_tokenId]; require(owner != address(0)); } // @notice Allow pre-approved user to take ownership of a token // @param _tokenId The ID of the Token that can be transferred if this call succeeds. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = tokenIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } // For querying totalSupply of token function totalSupply() public view returns (uint256 total) { return tokens.length; } // Owner initates the transfer of the token to another account // @param _to The address for the token to be transferred to. // @param _tokenId The ID of the Token that can be transferred if this call succeeds. function transfer(address _to, uint256 _tokenId) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } // Third-party initiates transfer of token from address _from to address _to // @param _from The address for the token to be transferred from. // @param _to The address for the token to be transferred to. // @param _tokenId The ID of the Token that can be transferred if this call succeeds. function transferFrom(address _from, address _to, uint256 _tokenId) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } // ONLY MASTER CONTRACT FUNCTIONS function createToken(string _name, address _owner) public onlyMasterContract returns (uint256 _tokenId) { return _createToken(_name, _owner); } function updateOwner(address _from, address _to, uint256 _tokenId) public onlyMasterContract { _transfer(_from, _to, _tokenId); } function setTokenData(uint256 _tokenId, bytes32 tokenData) public onlyMasterContract { tokenIndexToData[_tokenId] = tokenData; } // PRIVATE FUNCTIONS // Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } // For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return tokenIndexToApproved[_tokenId] == _to; } // For creating Token function _createToken(string _name, address _owner) private returns (uint256 _tokenId) { Token memory _token = Token({ name: _name }); uint256 newTokenId = tokens.push(_token) - 1; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newTokenId == uint256(uint32(newTokenId))); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newTokenId); return newTokenId; } // Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == tokenIndexToOwner[_tokenId]; } // @dev Assigns ownership of a specific Token to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of tokens is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership tokenIndexToOwner[_tokenId] = _to; // When creating new tokens _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete tokenIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } } contract SportStarMaster { // ***** EVENTS ***/ // @dev The Birth event is fired whenever a new token comes into existence. event Birth(uint256 tokenId, string name, address owner); // @dev The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner); // @dev Transfer event as defined in current draft of ERC721. // ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); // ***** CONSTANTS ***/ uint256 private startingPrice = 0.001 ether; uint256 private firstStepLimit = 0.053613 ether; uint256 private secondStepLimit = 0.564957 ether; // ***** STORAGE ***/ // @dev A mapping from TokenIDs to the price of the token. mapping(uint256 => uint256) private tokenIndexToPrice; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; // The address of tokens contract SportStarToken public tokensContract; uint256 public promoCreatedCount; uint256 private increaseLimit1 = 0.05 ether; uint256 private increaseLimit2 = 0.5 ether; uint256 private increaseLimit3 = 2.0 ether; uint256 private increaseLimit4 = 5.0 ether; // ***** ACCESS MODIFIERS ***/ // @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } // @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } // Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } // ***** CONSTRUCTOR ***/ function SportStarMaster() public { ceoAddress = msg.sender; cooAddress = msg.sender; //Old prices tokenIndexToPrice[0]=198056585936481135; tokenIndexToPrice[1]=198056585936481135; tokenIndexToPrice[2]=198056585936481135; tokenIndexToPrice[3]=76833314470700771; tokenIndexToPrice[4]=76833314470700771; tokenIndexToPrice[5]=76833314470700771; tokenIndexToPrice[6]=76833314470700771; tokenIndexToPrice[7]=76833314470700771; tokenIndexToPrice[8]=76833314470700771; tokenIndexToPrice[9]=76833314470700771; tokenIndexToPrice[10]=76833314470700771; tokenIndexToPrice[11]=76833314470700771; tokenIndexToPrice[12]=76833314470700771; tokenIndexToPrice[13]=76833314470700771; tokenIndexToPrice[14]=37264157518289874; tokenIndexToPrice[15]=76833314470700771; tokenIndexToPrice[16]=144447284479990001; tokenIndexToPrice[17]=144447284479990001; tokenIndexToPrice[18]=37264157518289874; tokenIndexToPrice[19]=76833314470700771; tokenIndexToPrice[20]=37264157518289874; tokenIndexToPrice[21]=76833314470700771; tokenIndexToPrice[22]=105348771387661881; tokenIndexToPrice[23]=144447284479990001; tokenIndexToPrice[24]=105348771387661881; tokenIndexToPrice[25]=37264157518289874; tokenIndexToPrice[26]=37264157518289874; tokenIndexToPrice[27]=37264157518289874; tokenIndexToPrice[28]=76833314470700771; tokenIndexToPrice[29]=105348771387661881; tokenIndexToPrice[30]=76833314470700771; tokenIndexToPrice[31]=37264157518289874; tokenIndexToPrice[32]=76833314470700771; tokenIndexToPrice[33]=37264157518289874; tokenIndexToPrice[34]=76833314470700771; tokenIndexToPrice[35]=37264157518289874; tokenIndexToPrice[36]=37264157518289874; tokenIndexToPrice[37]=76833314470700771; tokenIndexToPrice[38]=76833314470700771; tokenIndexToPrice[39]=37264157518289874; tokenIndexToPrice[40]=37264157518289874; tokenIndexToPrice[41]=37264157518289874; tokenIndexToPrice[42]=76833314470700771; tokenIndexToPrice[43]=37264157518289874; tokenIndexToPrice[44]=37264157518289874; tokenIndexToPrice[45]=76833314470700771; tokenIndexToPrice[46]=37264157518289874; tokenIndexToPrice[47]=37264157518289874; tokenIndexToPrice[48]=76833314470700771; } function setTokensContract(address _newTokensContract) public onlyCEO { require(_newTokensContract != address(0)); tokensContract = SportStarToken(_newTokensContract); } // ***** PRIVILEGES SETTING FUNCTIONS function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } // ***** PUBLIC FUNCTIONS ***/ function getTokenInfo(uint256 _tokenId) public view returns ( address owner, uint256 price, bytes32 tokenData ) { owner = tokensContract.ownerOf(_tokenId); price = tokenIndexToPrice[_tokenId]; tokenData = tokensContract.getTokenData(_tokenId); } // @dev Creates a new promo Token with the given name, with given _price and assignes it to an address. function createPromoToken(address _owner, string _name, uint256 _price) public onlyCOO { address tokenOwner = _owner; if (tokenOwner == address(0)) { tokenOwner = cooAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; uint256 newTokenId = tokensContract.createToken(_name, tokenOwner); tokenIndexToPrice[newTokenId] = _price; Birth(newTokenId, _name, _owner); } // @dev Creates a new Token with the given name. function createContractToken(string _name) public onlyCOO { uint256 newTokenId = tokensContract.createToken(_name, address(this)); tokenIndexToPrice[newTokenId] = startingPrice; Birth(newTokenId, _name, address(this)); } function createContractTokenWithPrice(string _name, uint256 _price) public onlyCOO { uint256 newTokenId = tokensContract.createToken(_name, address(this)); tokenIndexToPrice[newTokenId] = _price; Birth(newTokenId, _name, address(this)); } function setGamblingFee(uint256 _tokenId, uint256 _fee) public { require(msg.sender == tokensContract.ownerOf(_tokenId)); require(_fee >= 0 && _fee <= 100); bytes32 tokenData = byte(_fee); tokensContract.setTokenData(_tokenId, tokenData); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = tokensContract.ownerOf(_tokenId); address newOwner = msg.sender; uint256 sellingPrice = tokenIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 devCut = calculateDevCut(sellingPrice); uint256 payment = SafeMath.sub(sellingPrice, devCut); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); tokenIndexToPrice[_tokenId] = calculateNextPrice(sellingPrice); tokensContract.updateOwner(oldOwner, newOwner, _tokenId); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); } TokenSold(_tokenId, sellingPrice, tokenIndexToPrice[_tokenId], oldOwner, newOwner); msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return tokenIndexToPrice[_tokenId]; } function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) { if (_price < increaseLimit1) { return SafeMath.div(SafeMath.mul(_price, 3), 100); // 3% } else if (_price < increaseLimit2) { return SafeMath.div(SafeMath.mul(_price, 3), 100); // 3% } else if (_price < increaseLimit3) { return SafeMath.div(SafeMath.mul(_price, 3), 100); // 3% } else if (_price < increaseLimit4) { return SafeMath.div(SafeMath.mul(_price, 3), 100); // 3% } else { return SafeMath.div(SafeMath.mul(_price, 2), 100); // 2% } } function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) { if (_price < increaseLimit1) { return SafeMath.div(SafeMath.mul(_price, 200), 97); } else if (_price < increaseLimit2) { return SafeMath.div(SafeMath.mul(_price, 133), 97); } else if (_price < increaseLimit3) { return SafeMath.div(SafeMath.mul(_price, 125), 97); } else if (_price < increaseLimit4) { return SafeMath.div(SafeMath.mul(_price, 115), 97); } else { return SafeMath.div(SafeMath.mul(_price, 113), 98); } } function payout(address _to) public onlyCEO { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } // PRIVATE FUNCTIONS // Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
***** EVENTS ***/ @dev The Birth event is fired whenever a new token comes into existence. @dev The TokenSold event is fired whenever a token is sold. @dev Transfer event as defined in current draft of ERC721. ownership is assigned, including births. ***** CONSTANTS ***/ ***** STORAGE ***/ @dev A mapping from TokenIDs to the price of the token. The addresses of the accounts (or contracts) that can execute actions within each roles. The address of tokens contract ***** ACCESS MODIFIERS ***/ @dev Access modifier for CEO-only functionality
contract SportStarMaster { event Birth(uint256 tokenId, string name, address owner); event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner); event Transfer(address from, address to, uint256 tokenId); uint256 private startingPrice = 0.001 ether; uint256 private firstStepLimit = 0.053613 ether; uint256 private secondStepLimit = 0.564957 ether; mapping(uint256 => uint256) private tokenIndexToPrice; address public ceoAddress; address public cooAddress; SportStarToken public tokensContract; uint256 public promoCreatedCount; uint256 private increaseLimit1 = 0.05 ether; uint256 private increaseLimit2 = 0.5 ether; uint256 private increaseLimit3 = 2.0 ether; uint256 private increaseLimit4 = 5.0 ether; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } function SportStarMaster() public { ceoAddress = msg.sender; cooAddress = msg.sender; tokenIndexToPrice[0]=198056585936481135; tokenIndexToPrice[1]=198056585936481135; tokenIndexToPrice[2]=198056585936481135; tokenIndexToPrice[3]=76833314470700771; tokenIndexToPrice[4]=76833314470700771; tokenIndexToPrice[5]=76833314470700771; tokenIndexToPrice[6]=76833314470700771; tokenIndexToPrice[7]=76833314470700771; tokenIndexToPrice[8]=76833314470700771; tokenIndexToPrice[9]=76833314470700771; tokenIndexToPrice[10]=76833314470700771; tokenIndexToPrice[11]=76833314470700771; tokenIndexToPrice[12]=76833314470700771; tokenIndexToPrice[13]=76833314470700771; tokenIndexToPrice[14]=37264157518289874; tokenIndexToPrice[15]=76833314470700771; tokenIndexToPrice[16]=144447284479990001; tokenIndexToPrice[17]=144447284479990001; tokenIndexToPrice[18]=37264157518289874; tokenIndexToPrice[19]=76833314470700771; tokenIndexToPrice[20]=37264157518289874; tokenIndexToPrice[21]=76833314470700771; tokenIndexToPrice[22]=105348771387661881; tokenIndexToPrice[23]=144447284479990001; tokenIndexToPrice[24]=105348771387661881; tokenIndexToPrice[25]=37264157518289874; tokenIndexToPrice[26]=37264157518289874; tokenIndexToPrice[27]=37264157518289874; tokenIndexToPrice[28]=76833314470700771; tokenIndexToPrice[29]=105348771387661881; tokenIndexToPrice[30]=76833314470700771; tokenIndexToPrice[31]=37264157518289874; tokenIndexToPrice[32]=76833314470700771; tokenIndexToPrice[33]=37264157518289874; tokenIndexToPrice[34]=76833314470700771; tokenIndexToPrice[35]=37264157518289874; tokenIndexToPrice[36]=37264157518289874; tokenIndexToPrice[37]=76833314470700771; tokenIndexToPrice[38]=76833314470700771; tokenIndexToPrice[39]=37264157518289874; tokenIndexToPrice[40]=37264157518289874; tokenIndexToPrice[41]=37264157518289874; tokenIndexToPrice[42]=76833314470700771; tokenIndexToPrice[43]=37264157518289874; tokenIndexToPrice[44]=37264157518289874; tokenIndexToPrice[45]=76833314470700771; tokenIndexToPrice[46]=37264157518289874; tokenIndexToPrice[47]=37264157518289874; tokenIndexToPrice[48]=76833314470700771; } function setTokensContract(address _newTokensContract) public onlyCEO { require(_newTokensContract != address(0)); tokensContract = SportStarToken(_newTokensContract); } function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } function getTokenInfo(uint256 _tokenId) public view returns ( address owner, uint256 price, bytes32 tokenData ) { owner = tokensContract.ownerOf(_tokenId); price = tokenIndexToPrice[_tokenId]; tokenData = tokensContract.getTokenData(_tokenId); } function createPromoToken(address _owner, string _name, uint256 _price) public onlyCOO { address tokenOwner = _owner; if (tokenOwner == address(0)) { tokenOwner = cooAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; uint256 newTokenId = tokensContract.createToken(_name, tokenOwner); tokenIndexToPrice[newTokenId] = _price; Birth(newTokenId, _name, _owner); } function createPromoToken(address _owner, string _name, uint256 _price) public onlyCOO { address tokenOwner = _owner; if (tokenOwner == address(0)) { tokenOwner = cooAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; uint256 newTokenId = tokensContract.createToken(_name, tokenOwner); tokenIndexToPrice[newTokenId] = _price; Birth(newTokenId, _name, _owner); } function createPromoToken(address _owner, string _name, uint256 _price) public onlyCOO { address tokenOwner = _owner; if (tokenOwner == address(0)) { tokenOwner = cooAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; uint256 newTokenId = tokensContract.createToken(_name, tokenOwner); tokenIndexToPrice[newTokenId] = _price; Birth(newTokenId, _name, _owner); } function createContractToken(string _name) public onlyCOO { uint256 newTokenId = tokensContract.createToken(_name, address(this)); tokenIndexToPrice[newTokenId] = startingPrice; Birth(newTokenId, _name, address(this)); } function createContractTokenWithPrice(string _name, uint256 _price) public onlyCOO { uint256 newTokenId = tokensContract.createToken(_name, address(this)); tokenIndexToPrice[newTokenId] = _price; Birth(newTokenId, _name, address(this)); } function setGamblingFee(uint256 _tokenId, uint256 _fee) public { require(msg.sender == tokensContract.ownerOf(_tokenId)); require(_fee >= 0 && _fee <= 100); bytes32 tokenData = byte(_fee); tokensContract.setTokenData(_tokenId, tokenData); } function purchase(uint256 _tokenId) public payable { address oldOwner = tokensContract.ownerOf(_tokenId); address newOwner = msg.sender; uint256 sellingPrice = tokenIndexToPrice[_tokenId]; require(oldOwner != newOwner); require(_addressNotNull(newOwner)); require(msg.value >= sellingPrice); uint256 devCut = calculateDevCut(sellingPrice); uint256 payment = SafeMath.sub(sellingPrice, devCut); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); tokenIndexToPrice[_tokenId] = calculateNextPrice(sellingPrice); tokensContract.updateOwner(oldOwner, newOwner, _tokenId); if (oldOwner != address(this)) { oldOwner.transfer(payment); } TokenSold(_tokenId, sellingPrice, tokenIndexToPrice[_tokenId], oldOwner, newOwner); msg.sender.transfer(purchaseExcess); } function purchase(uint256 _tokenId) public payable { address oldOwner = tokensContract.ownerOf(_tokenId); address newOwner = msg.sender; uint256 sellingPrice = tokenIndexToPrice[_tokenId]; require(oldOwner != newOwner); require(_addressNotNull(newOwner)); require(msg.value >= sellingPrice); uint256 devCut = calculateDevCut(sellingPrice); uint256 payment = SafeMath.sub(sellingPrice, devCut); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); tokenIndexToPrice[_tokenId] = calculateNextPrice(sellingPrice); tokensContract.updateOwner(oldOwner, newOwner, _tokenId); if (oldOwner != address(this)) { oldOwner.transfer(payment); } TokenSold(_tokenId, sellingPrice, tokenIndexToPrice[_tokenId], oldOwner, newOwner); msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return tokenIndexToPrice[_tokenId]; } function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) { if (_price < increaseLimit1) { } } function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) { if (_price < increaseLimit1) { } } } else if (_price < increaseLimit2) { } else if (_price < increaseLimit3) { } else if (_price < increaseLimit4) { } else { function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) { if (_price < increaseLimit1) { return SafeMath.div(SafeMath.mul(_price, 200), 97); return SafeMath.div(SafeMath.mul(_price, 133), 97); return SafeMath.div(SafeMath.mul(_price, 125), 97); return SafeMath.div(SafeMath.mul(_price, 115), 97); return SafeMath.div(SafeMath.mul(_price, 113), 98); } } function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) { if (_price < increaseLimit1) { return SafeMath.div(SafeMath.mul(_price, 200), 97); return SafeMath.div(SafeMath.mul(_price, 133), 97); return SafeMath.div(SafeMath.mul(_price, 125), 97); return SafeMath.div(SafeMath.mul(_price, 115), 97); return SafeMath.div(SafeMath.mul(_price, 113), 98); } } } else if (_price < increaseLimit2) { } else if (_price < increaseLimit3) { } else if (_price < increaseLimit4) { } else { function payout(address _to) public onlyCEO { if (_to == address(0)) { ceoAddress.transfer(this.balance); _to.transfer(this.balance); } } function payout(address _to) public onlyCEO { if (_to == address(0)) { ceoAddress.transfer(this.balance); _to.transfer(this.balance); } } } else { function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } }
1,008,825
[ 1, 29221, 342, 225, 1021, 605, 10542, 871, 353, 15950, 17334, 279, 394, 1147, 14535, 1368, 15782, 18, 225, 1021, 3155, 55, 1673, 871, 353, 15950, 17334, 279, 1147, 353, 272, 1673, 18, 225, 12279, 871, 487, 2553, 316, 783, 12246, 434, 4232, 39, 27, 5340, 18, 225, 23178, 353, 6958, 16, 6508, 17057, 87, 18, 225, 24023, 55, 342, 225, 2347, 15553, 342, 225, 432, 2874, 628, 3155, 5103, 358, 326, 6205, 434, 326, 1147, 18, 1021, 6138, 434, 326, 9484, 261, 280, 20092, 13, 716, 848, 1836, 4209, 3470, 1517, 4900, 18, 1021, 1758, 434, 2430, 6835, 225, 13255, 8663, 10591, 55, 342, 225, 5016, 9606, 364, 29538, 51, 17, 3700, 14176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 655, 18379, 7786, 288, 203, 203, 203, 565, 871, 605, 10542, 12, 11890, 5034, 1147, 548, 16, 533, 508, 16, 1758, 3410, 1769, 203, 203, 565, 871, 3155, 55, 1673, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 1592, 5147, 16, 2254, 5034, 394, 5147, 16, 1758, 2807, 5541, 16, 1758, 5657, 1224, 1769, 203, 203, 565, 871, 12279, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 1769, 203, 203, 203, 203, 203, 565, 2254, 5034, 3238, 5023, 5147, 273, 374, 18, 11664, 225, 2437, 31, 203, 565, 2254, 5034, 3238, 1122, 4160, 3039, 273, 374, 18, 6260, 5718, 3437, 225, 2437, 31, 203, 565, 2254, 5034, 3238, 2205, 4160, 3039, 273, 374, 18, 25, 1105, 8778, 27, 225, 2437, 31, 203, 203, 203, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 1147, 1016, 774, 5147, 31, 203, 203, 565, 1758, 1071, 276, 4361, 1887, 31, 203, 565, 1758, 1071, 1825, 83, 1887, 31, 203, 203, 565, 348, 655, 18379, 1345, 1071, 2430, 8924, 31, 203, 203, 565, 2254, 5034, 1071, 3012, 83, 6119, 1380, 31, 203, 203, 203, 565, 2254, 5034, 3238, 10929, 3039, 21, 273, 374, 18, 6260, 225, 2437, 31, 203, 565, 2254, 5034, 3238, 10929, 3039, 22, 273, 374, 18, 25, 225, 2437, 31, 203, 565, 2254, 5034, 3238, 10929, 3039, 23, 273, 576, 18, 20, 225, 2437, 31, 203, 565, 2254, 5034, 3238, 10929, 3039, 24, 273, 1381, 18, 20, 225, 2437, 31, 203, 203, 203, 203, 203, 565, 9606, 2 ]
./partial_match/97/0x66482a6528bA91aa58b8B1cE5CB2F61bF073ff06/sources/TouhouFarm.sol
magic trade balancing algorithm
function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){ uint calc = (PSN*bs)/(PSNH+((PSN*rs+PSNH*rt)/rt)); return calc; }
11,365,480
[ 1, 11179, 18542, 324, 16142, 4886, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 22583, 12, 11890, 5034, 8253, 16, 11890, 5034, 3597, 16, 2254, 5034, 7081, 13, 1071, 1476, 1135, 12, 11890, 5034, 15329, 203, 540, 203, 540, 203, 3639, 2254, 7029, 273, 261, 5857, 50, 14, 2038, 13176, 12, 5857, 50, 44, 15, 12443, 5857, 50, 14, 5453, 15, 5857, 50, 44, 14, 3797, 13176, 3797, 10019, 203, 540, 203, 540, 203, 540, 203, 540, 203, 540, 203, 3639, 327, 7029, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** The software and documentation available in this repository (the "Software") is protected by copyright law and accessible pursuant to the license set forth below. Copyright © 2019 Staked Securely, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person or organization obtaining the Software (the “Licensee”) to privately study, review, and analyze the Software. Licensee shall not use the Software for any other purpose. Licensee shall not modify, transfer, assign, share, or sub-license the Software or any derivative works 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, TITLE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE. */ pragma solidity 0.4.25; /// @notice Implementation of the Eternal Storage Pattern to enable the RAY /// smart contracts system to be upgradable. /// /// Author: Devan Purhar /// Version: 1.0.0 contract Storage { /*************** STORAGE VARIABLE DECLARATIONS **************/ // TODO: remove 'wallet', this will eventually be a contract, not an EOA address public governanceWalletAddress; mapping(address => bool) internal storageWrappers; // verified addresses to mutate Storage mapping(address => bool) internal oracles; // verified off-chain addresses to call the Oracle contract mapping(bytes32 => address) internal verifier; // verified contract for portfolio impls. mapping(bytes32 => address) internal contracts; // verified contracts of the system mapping(bytes32 => bytes32) internal tokenKeys; mapping(bytes32 => CommonState) internal _commonStorage; mapping(bytes32 => PortfolioState) internal _portfolioStorage; mapping(address => CoinState) internal _coinStorage; /// @notice Common state across RAY's and Opportunities struct CommonState { uint withdrawnYield; uint realizedYield; uint totalShareSupply; uint principal; // only used by Opportunities, only one principal balance to track per Opportunity pool bool pausedMode; address principalAddress; mapping(bytes32 => uint[4]) tokenValues; // include these for flexibility in the future mapping(bytes32 => bool) _bool; mapping(bytes32 => int) _int; mapping(bytes32 => uint) _uint; mapping(bytes32 => string) _string; mapping(bytes32 => address) _address; mapping(bytes32 => bytes) _bytes; } /// @notice Variables only Portfolios require struct PortfolioState { mapping(bytes32 => bytes32) opportunityTokens; bytes32[] opportunities; mapping(bytes32 => bool) validOpportunities; uint availableCapital; } /// @notice State that needs to be filled out for a coin to be added to the /// system. /// /// TODO: Remove minAmount. We should go back to only enforcing the technical /// minimal amount on-chain and leave any harder restrictions to GUI-side. /// It's not in favor of an 'open' system to have minimum limits. struct CoinState { uint benchmarkRate; uint cumulativeRate; uint lastUpdatedRate; // in seconds uint acpContribution; uint minAmount; uint raised; bool isERC20; } /*************** MODIFIER DECLARATIONS **************/ /// @notice Checks the caller is a valid Storage Wrapper /// /// @dev Only Storage Wrappers can mutate Storage's storage modifier onlyStorageWrappers() { require( storageWrappers[msg.sender] == true, "#Storage onlyStorageWrappers Modifier: Only StorageWrappers can call this" ); _; } /////////////////////// FUNCTION DECLARATIONS BEGIN /////////////////////// /******************* PUBLIC FUNCTIONS *******************/ /// @notice Sets the Admin contract to our wallet originally until we deploy /// the Admin contract (next step in deployment). Also sets our wallet /// wallet address as a storage wrapper, later unsets it. /// /// @param _governanceWalletAddress - governance's wallet address /// @param _weth - Canonical WETH9 contract address /// @param _dai - DAI token contract address constructor( address _governanceWalletAddress, address _weth, address _dai ) public { governanceWalletAddress = _governanceWalletAddress; contracts[keccak256("WETHTokenContract")] = _weth; contracts[keccak256("DAITokenContract")] = _dai; contracts[keccak256("AdminContract")] = msg.sender; // need to deploy Admin and then forgo this storageWrappers[msg.sender] = true; // need to deploy and set Storage Wrappers then forgo this } /** ----------------- GLOBAL VIEW ACCESSORS ----------------- **/ /// @notice Gets the current governance address /// /// @return governance address function getGovernanceWallet() external view returns (address) { return governanceWalletAddress; } /// @notice Checks if the entered address is an approved Oracle /// /// @param target - address we're checking out /// /// @return true or false function getIsOracle(address target) external view returns (bool) { return oracles[target]; } /// @notice Gets a contract address by a bytes32 hash (keccak256) /// /// @param contractName - Ex. keccak256("PortfolioManagerContract"); /// /// @return The contract address function getContractAddress(bytes32 contractName) external view returns (address) { return contracts[contractName]; } /// @notice Maps portfolio's to the contract that they currently are used /// through. Supports multiple versions of the same contracts /// /// @param contractName - Ex. keccak256("PortfolioManagerContract"); /// /// @return The contract address function getVerifier(bytes32 contractName) external view returns (address) { return verifier[contractName]; } /// @notice Each token is mapped to a key that unlocks everything for it /// in storage. /// /// @param tokenId - token id of the RAY token /// /// @return The portfolio id/key associated function getTokenKey(bytes32 tokenId) external view returns (bytes32) { return tokenKeys[tokenId]; } /** ----------------- STATE SPECIFIC-TYPE VIEW ACCESSOR ----------------- **/ /// @notice Get the Opportunities this portfolio is allowed to be in /// /// @param portfolioId - the id of the portfolio /// /// @return Array of valid opportunity id's function getOpportunities(bytes32 portfolioId) external view returns (bytes32[]) { return _portfolioStorage[portfolioId].opportunities; } /// @notice Get's the coin type of the entered RAY /// /// @param portfolioId - the id of the portfolio /// /// @return The coin associated with the portfolio /// /// TODO: Refactor to getPrincipalToken since we commonly use that function getPrincipalAddress(bytes32 portfolioId) external view returns (address) { return _commonStorage[portfolioId].principalAddress; } /// @notice Check if the entered coin is an ERC20 /// /// @param principalAddress - the coin contract address we're checking /// /// @return true or false function getIsERC20(address principalAddress) external view returns (bool) { return _coinStorage[principalAddress].isERC20; } /// @notice Get the min. amount for the associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return min. amount in smallest units in-kind /// /// TODO: Remove this (and refactor the check used in PositionManager associated) function getMinAmount(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].minAmount; } /// @notice Get the normalizer factor for the associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return multiplier to use on the input values for this coin function getRaised(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].raised; } /// @notice Gets the current benchmark rate of associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return benchmark rate function getBenchmarkRate(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].benchmarkRate; } /// @notice Gets the cumulative rate of the portfolio entered /// /// @dev The cumulative rate tracks how the benchmark rate has /// progressed over time. Used in our fee model to find /// what benchmark rate is appropriate to a unique token /// based on when they joined and the changes the rate /// went through in that time period before they withdraw. /// /// @param principalAddress - the coin contract address we're checking /// /// @return the cumulative benchmark rate function getCumulativeRate(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].cumulativeRate; } /// @notice Gets the last time in seconds the cumulative rate was /// was updated for the associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return Last time in seconds the cumulative rate was updated function getLastUpdatedRate(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].lastUpdatedRate; } /// @notice Gets the ACP Contribution for the associated coin /// /// @param principalAddress - the coin contract address we're checking /// /// @return the acp contribution function getACPContribution(address principalAddress) external view returns (uint) { return _coinStorage[principalAddress].acpContribution; } /// @notice Checks if the opportunity is allowed for the associated portfolio /// /// @param portfolioId - the id of the portfolio /// @param opportunityId - the id of the opportunity /// /// @return true or false function isValidOpportunity(bytes32 portfolioId, bytes32 opportunityId) external view returns (bool) { return _portfolioStorage[portfolioId].validOpportunities[opportunityId]; } /// @notice Get the shares of the associated token /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token /// /// @return the number of shares function getTokenShares(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) { return _commonStorage[portfolioId].tokenValues[tokenId][0]; } /// @notice Get the capital of the associated token /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token /// /// @return the amount of capital function getTokenCapital(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) { return _commonStorage[portfolioId].tokenValues[tokenId][1]; } /// @notice Gets the allowance of the associated token /// /// @dev Each token has an allowance which reflects how much yield they're /// able to make without being charged a fee by us. /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token /// /// @return the amount of allowance function getTokenAllowance(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) { return _commonStorage[portfolioId].tokenValues[tokenId][2]; } /// @notice Gets the value of the cumulative rate the token 'entered' at. /// /// @dev I say 'entered' because when a token adds capital or partially withdraws /// or anytime it changes it's token capital we reset this. /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token /// /// @return the entry rate in seconds /// /// TODO: Based on the above @dev we should refactor this to a more appropriate /// name function getEntryRate(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) { return _commonStorage[portfolioId].tokenValues[tokenId][3]; } /// @notice Gets the Opportunity Token of a portfolio. /// /// @dev We assume a portfolio will only need one of a certain Opportunity /// Token. It shouldn't ever need multiple of the same Opportunity. /// /// @param portfolioId - the id of the portfolio /// @param opportunityId - the id of the opportunity /// /// @return The Opportunity token id function getOpportunityToken(bytes32 portfolioId, bytes32 opportunityId) external view returns (bytes32) { return _portfolioStorage[portfolioId].opportunityTokens[opportunityId]; } /// @notice Get the principal supplied for the Opportunity /// /// @param opportunityId - the id of the opportunity /// /// @return the amount of principal supplied function getPrincipal(bytes32 opportunityId) external view returns (uint) { return _commonStorage[opportunityId].principal; } /// @notice Check if in paused mode for the associated portfolio /// /// @param portfolioId - the id of the portfolio /// /// @return true or false function getPausedMode(bytes32 portfolioId) external view returns (bool) { return _commonStorage[portfolioId].pausedMode; } /// @notice Gets the realized yield of the associated portfolio /// /// @dev Realized yield is the yield we've made, but withdrew /// back into the system and now use it as capital /// /// @param portfolioId - the id of the portfolio /// /// @return the yield realized function getRealizedYield(bytes32 portfolioId) external view returns (uint) { return _commonStorage[portfolioId].realizedYield; } /// @notice Gets the withdrawn yield of the associated portfolio /// /// @param portfolioId - the id of the portfolio /// /// @return the yield withdrawn function getWithdrawnYield(bytes32 portfolioId) external view returns (uint) { return _commonStorage[portfolioId].withdrawnYield; } /// @notice Gets the available capital of the portfolio associated /// /// @dev Available capital is the amount of funds available to a portfolio. /// This is instantiated by users depositing funds /// /// @param portfolioId - the id of the portfolio /// /// @return the available capital function getAvailableCapital(bytes32 portfolioId) external view returns (uint) { return _portfolioStorage[portfolioId].availableCapital; } /// @notice Gets the share supply of the portfolio associated /// /// @param portfolioId - the id of the portfolio /// /// @return the total shares function getShareSupply(bytes32 portfolioId) external view returns (uint) { return _commonStorage[portfolioId].totalShareSupply; } /** ----------------- GENERIC TYPE VIEW ACCESSOR ----------------- **/ function getBoolean(bytes32 ray, bytes32 key) external view returns (bool) { return _commonStorage[ray]._bool[key]; } function getInt(bytes32 ray, bytes32 key) external view returns (int) { return _commonStorage[ray]._int[key]; } function getUint(bytes32 ray, bytes32 key) external view returns (uint) { return _commonStorage[ray]._uint[key]; } function getAddress(bytes32 ray, bytes32 key) external view returns (address) { return _commonStorage[ray]._address[key]; } function getString(bytes32 ray, bytes32 key) external view returns (string) { return _commonStorage[ray]._string[key]; } function getBytes(bytes32 ray, bytes32 key) external view returns (bytes) { return _commonStorage[ray]._bytes[key]; } /** ----------------- ONLY STORAGE WRAPPERS GLOBAL MUTATORS ----------------- **/ /// @notice This sets the Governance Wallet - important since this wallet controls /// the Admin contract that controls 'Governance' in the system. /// /// @param newGovernanceWallet - the new governance address function setGovernanceWallet(address newGovernanceWallet) external onlyStorageWrappers { governanceWalletAddress = newGovernanceWallet; } /// @dev Adds or remove an address to Oracle permissions status /// /// @param oracle - the address of the wallet targeted /// @param action - the action we wish to carry out, true to add, false to remove function setOracle(address oracle, bool action) external onlyStorageWrappers { oracles[oracle] = action; } /// @notice Adds or removes an address to StorageWrapper permissions status /// /// @param theStorageWrapper - the address to either add or remove /// @param action - the action we wish to carry out, true to add, false to remove function setStorageWrapperContract( address theStorageWrapper, bool action ) external onlyStorageWrappers { storageWrappers[theStorageWrapper] = action; } /// @notice Sets a portfolio or opportunity to a contract implementation /// /// @param typeId - the portfolio or opportunity id /// @param contractAddress - the contract address function setVerifier(bytes32 typeId, address contractAddress) external onlyStorageWrappers { verifier[typeId] = contractAddress; } /// @notice Sets the contract address mapped to a contracts name /// /// @param contractName - The name of the contract /// @param contractAddress - The address of the contract function setContractAddress( bytes32 contractName, address contractAddress ) external onlyStorageWrappers { contracts[contractName] = contractAddress; } /// @notice Sets a portfolio id to a token /// /// @param tokenId - The id of the token /// @param portfolioId - The id of the portfolio function setTokenKey(bytes32 tokenId, bytes32 portfolioId) external onlyStorageWrappers { tokenKeys[tokenId] = portfolioId; } /// @notice Sets status on ERC20 for the associated coin /// /// @param principalAddress - The coin's contract address /// @param _isERC20 - true if is ERC20, false if not function setIsERC20(address principalAddress, bool _isERC20) external onlyStorageWrappers { _coinStorage[principalAddress].isERC20 = _isERC20; } /// @notice Sets the min. amount for the associated coin /// /// @param principalAddress - The coin's contract address /// @param _minAmount - the min. amount in-kind smallest units function setMinAmount(address principalAddress, uint _minAmount) external onlyStorageWrappers { _coinStorage[principalAddress].minAmount = _minAmount; } /// @notice Sets the normalizing multiplier for the associated coin /// /// @param principalAddress - The coin's contract address /// @param _raised - the multiplier function setRaised(address principalAddress, uint _raised) external onlyStorageWrappers { _coinStorage[principalAddress].raised = _raised; } /// @notice Sets the benchmark rate for the associated coin /// /// @param principalAddress - The coin's contract address /// @param newBenchmarkRate - the new benchmark rate function setBenchmarkRate( address principalAddress, uint newBenchmarkRate ) external onlyStorageWrappers { _coinStorage[principalAddress].benchmarkRate = newBenchmarkRate; } /// @notice Sets the cumulative rate for the associated coin /// /// @param principalAddress - The coin's contract address /// @param newCumulativeRate - the new cumulative rate function setCumulativeRate( address principalAddress, uint newCumulativeRate ) external onlyStorageWrappers { _coinStorage[principalAddress].cumulativeRate = newCumulativeRate; } /// @notice Sets the timestamp for last updating the rate for the associated coin /// /// @param principalAddress - The coin's contract address /// @param newLastUpdatedRate - the new last updated rate function setLastUpdatedRate( address principalAddress, uint newLastUpdatedRate ) external onlyStorageWrappers { _coinStorage[principalAddress].lastUpdatedRate = newLastUpdatedRate; } /// @notice Sets the acp contribution for the associated coin /// /// @param principalAddress - The coin's contract address /// @param newACPContribution - the new acp contribution function setACPContribution( address principalAddress, uint newACPContribution ) external onlyStorageWrappers { _coinStorage[principalAddress].acpContribution = newACPContribution; } /** ----------------- ONLY STORAGE WRAPPERS STATE SPECIFIC MUTATORS ----------------- **/ /// @notice Clears the data of the associated token (used upon a burn) /// /// @param portfolioId - the id of the portfolio /// @param tokenId - the id of the token function deleteTokenValues(bytes32 portfolioId, bytes32 tokenId) external onlyStorageWrappers { delete _commonStorage[portfolioId].tokenValues[tokenId]; } /// @notice Add an Opportunity to a portfolio's available options. We also set /// the principal address used by the portfolio at the same time. /// /// @param portfolioId - The id of the portfolio we're configuring /// @param opportunityKey - The key of the opportunity we're adding to this portfolio /// @param _principalAddress - The coin's contract address for this portfolio // /// TODO: This is in-efficient, we set the principal address multiple times /// for the same portfolio. Fix this. /// /// TODO: Refactor principalToken -> principalAddress or opposite? function addOpportunity( bytes32 portfolioId, bytes32 opportunityKey, address _principalAddress ) external onlyStorageWrappers { _portfolioStorage[portfolioId].opportunities.push(opportunityKey); _commonStorage[portfolioId].principalAddress = _principalAddress; } /// @notice Set the principal address/coin of the associated portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param _principalAddress - The coin's contract address for this portfolio function setPrincipalAddress( bytes32 portfolioId, address _principalAddress ) external onlyStorageWrappers { _commonStorage[portfolioId].principalAddress = _principalAddress; } /// @notice Set an opportunity as valid in a mapping to a portfolio key /// /// @dev We set the valid opportunities in an array, but we also set them /// here for quicker access instead of having to iterate through the array. /// Sacrifice the extra gas cost (20,000) per opportunity we 'double set' /// /// @param portfolioId - the id of the portfolio /// @param opportunityId - the id of the opportunity function setValidOpportunity(bytes32 portfolioId, bytes32 opportunityId) external onlyStorageWrappers { _portfolioStorage[portfolioId].validOpportunities[opportunityId] = true; } /// @notice Set the shares of the associated token /// /// @param portfolioId - The id of the portfolio we're configuring /// @param tokenId - The id of the token we're configuring /// @param tokenShares - The number of shares function setTokenShares( bytes32 portfolioId, bytes32 tokenId, uint tokenShares ) external onlyStorageWrappers { _commonStorage[portfolioId].tokenValues[tokenId][0] = tokenShares; } /// @notice Set the capital of the associated token /// /// @param portfolioId - The id of the portfolio we're configuring /// @param tokenId - The id of the token we're configuring /// @param tokenCapital - The amount of capital function setTokenCapital( bytes32 portfolioId, bytes32 tokenId, uint tokenCapital ) external onlyStorageWrappers { _commonStorage[portfolioId].tokenValues[tokenId][1] = tokenCapital; } /// @notice Set the allowance of the associated token /// /// @param portfolioId - The id of the portfolio we're configuring /// @param tokenId - The id of the token we're configuring /// @param tokenAllowance - The amount of allowance function setTokenAllowance( bytes32 portfolioId, bytes32 tokenId, uint tokenAllowance ) external onlyStorageWrappers { _commonStorage[portfolioId].tokenValues[tokenId][2] = tokenAllowance; } /// @notice Set the entry rate of the associated token /// /// @param portfolioId - The id of the portfolio we're configuring /// @param tokenId - The id of the token we're configuring /// @param entryRate - The entry rate (in seconds) function setEntryRate( bytes32 portfolioId, bytes32 tokenId, uint entryRate ) external onlyStorageWrappers { _commonStorage[portfolioId].tokenValues[tokenId][3] = entryRate; } /// @notice Set the id of an Opportunity token for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param opportunityId - The id of the opportunity the token represents /// @param tokenId - The id of the Opportunity token function setOpportunityToken( bytes32 portfolioId, bytes32 opportunityId, bytes32 tokenId ) external onlyStorageWrappers { _portfolioStorage[portfolioId].opportunityTokens[opportunityId] = tokenId; } /// @notice Set the id of an Opportunity token for a portfolio /// /// @param opportunityId - The id of the opportunity the token represents /// @param principalAmount - The new amount of principal function setPrincipal( bytes32 opportunityId, uint principalAmount ) external onlyStorageWrappers { _commonStorage[opportunityId].principal = principalAmount; } /// @notice Set paused mode on for a portfolio /// /// @dev Enter keccak256("RAY") to pause all portfolios /// /// @param portfolioId - The id of the portfolio we're configuring function setPausedOn(bytes32 portfolioId) external onlyStorageWrappers { _commonStorage[portfolioId].pausedMode = true; } /// @notice Set paused mode off for a portfolio /// /// @dev Enter keccak256("RAY") to un-pause all portfolios /// /// @param portfolioId - The id of the portfolio we're configuring function setPausedOff(bytes32 portfolioId) external onlyStorageWrappers { _commonStorage[portfolioId].pausedMode = false; } /// @notice Set the realized yield for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param newRealizedYield - The new realized yield function setRealizedYield(bytes32 portfolioId, uint newRealizedYield) external onlyStorageWrappers { _commonStorage[portfolioId].realizedYield = newRealizedYield; } /// @notice Set the withdrawn yield for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param newWithdrawnYield - The new realized yield function setWithdrawnYield(bytes32 portfolioId, uint newWithdrawnYield) external onlyStorageWrappers { _commonStorage[portfolioId].withdrawnYield = newWithdrawnYield; } /// @notice Set the available capital for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param newAvailableCapital - The new available capital function setAvailableCapital(bytes32 portfolioId, uint newAvailableCapital) external onlyStorageWrappers { _portfolioStorage[portfolioId].availableCapital = newAvailableCapital; } /// @notice Set the total share supply for a portfolio /// /// @param portfolioId - The id of the portfolio we're configuring /// @param newShareSupply - The new share supply function setShareSupply(bytes32 portfolioId, uint newShareSupply) external onlyStorageWrappers { _commonStorage[portfolioId].totalShareSupply = newShareSupply; } /** ----------------- ONLY STORAGE WRAPPERS GENERIC MUTATORS ----------------- **/ /// @notice We have these to enable us to be flexible with our eternal storage /// in the future. Also, we could always deploy a new Storage contract /// and reference two Storage contracts in the system and so on. function setBoolean(bytes32 ray, bytes32 key, bool value) external onlyStorageWrappers { _commonStorage[ray]._bool[key] = value; } function setInt(bytes32 ray, bytes32 key, int value) external onlyStorageWrappers { _commonStorage[ray]._int[key] = value; } function setUint(bytes32 ray, bytes32 key, uint256 value) external onlyStorageWrappers { _commonStorage[ray]._uint[key] = value; } function setAddress(bytes32 ray, bytes32 key, address value) external onlyStorageWrappers { _commonStorage[ray]._address[key] = value; } function setString(bytes32 ray, bytes32 key, string value) external onlyStorageWrappers { _commonStorage[ray]._string[key] = value; } function setBytes(bytes32 ray, bytes32 key, bytes value) external onlyStorageWrappers { _commonStorage[ray]._bytes[key] = value; } }
only used by Opportunities, only one principal balance to track per Opportunity pool
uint principal;
12,906,347
[ 1, 3700, 1399, 635, 6066, 655, 318, 1961, 16, 1338, 1245, 8897, 11013, 358, 3298, 1534, 6066, 655, 13352, 2845, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 8897, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xd8DB2B119E0c1aDdb7969Ea2031963e373ebfFdE/sources/contracts/ParallelAutoAuction.sol
* @dev Updating `bidIncrement` will only affect to future increments./
function setBidIncrement(uint96 bidIncrement) external onlyOwner { if (_stateLocks.bidIncrementLocked) revert OptionLocked(); _auctionConfig.bidIncrement = bidIncrement; } \* ---------------- */
2,939,830
[ 1, 17858, 1375, 19773, 10798, 68, 903, 1338, 13418, 358, 3563, 17071, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15268, 350, 10798, 12, 11890, 10525, 9949, 10798, 13, 3903, 1338, 5541, 288, 203, 3639, 309, 261, 67, 2019, 19159, 18, 19773, 10798, 8966, 13, 15226, 2698, 8966, 5621, 203, 3639, 389, 69, 4062, 809, 18, 19773, 10798, 273, 9949, 10798, 31, 203, 565, 289, 203, 377, 203, 203, 565, 521, 14, 300, 18753, 1195, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x3176a1Cc7E8860774d09950E7D286Bb1FaE83d82/sources/StrategySwerveUSD.sol
additional protection so we don't burn the funds
require(_vault != address(0), "!vault");
3,606,031
[ 1, 13996, 17862, 1427, 732, 2727, 1404, 18305, 326, 284, 19156, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1377, 2583, 24899, 26983, 480, 1758, 12, 20, 3631, 17528, 26983, 8863, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.0; /// @title Errors contract Errors { string constant ZERO_VALUE = "ZERO_VALUE"; string constant ZERO_ADDRESS = "ZERO_ADDRESS"; string constant INVALID_VALUE = "INVALID_VALUE"; string constant INVALID_ADDRESS = "INVALID_ADDRESS"; string constant INVALID_SIZE = "INVALID_SIZE"; string constant INVALID_SIG = "INVALID_SIG"; string constant INVALID_STATE = "INVALID_STATE"; string constant NOT_FOUND = "NOT_FOUND"; string constant ALREADY_EXIST = "ALREADY_EXIST"; string constant REENTRY = "REENTRY"; string constant UNAUTHORIZED = "UNAUTHORIZED"; string constant UNIMPLEMENTED = "UNIMPLEMENTED"; string constant UNSUPPORTED = "UNSUPPORTED"; string constant TRANSFER_FAILURE = "TRANSFER_FAILURE"; string constant WITHDRAWAL_FAILURE = "WITHDRAWAL_FAILURE"; string constant BURN_FAILURE = "BURN_FAILURE"; string constant BURN_RATE_FROZEN = "BURN_RATE_FROZEN"; string constant BURN_RATE_MINIMIZED = "BURN_RATE_MINIMIZED"; string constant UNAUTHORIZED_ONCHAIN_ORDER = "UNAUTHORIZED_ONCHAIN_ORDER"; string constant INVALID_CANDIDATE = "INVALID_CANDIDATE"; string constant ALREADY_VOTED = "ALREADY_VOTED"; string constant NOT_OWNER = "NOT_OWNER"; } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title Ownable /// @dev The Ownable contract has an owner address, and provides basic /// authorization control functions, this simplifies the implementation of /// "user permissions". contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @dev The Ownable constructor sets the original `owner` of the contract /// to the sender. constructor() public { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner, "NOT_OWNER"); _; } /// @dev Allows the current owner to transfer control of the contract to a /// newOwner. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public onlyOwner { require(newOwner != address(0x0), "ZERO_ADDRESS"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// @title Claimable /// @dev Extension for the Ownable contract, where the ownership needs /// to be claimed. This allows the new owner to accept the transfer. contract Claimable is Ownable { address public pendingOwner; /// @dev Modifier throws if called by any account other than the pendingOwner. modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to set the pendingOwner address. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public onlyOwner { require(newOwner != address(0x0) && newOwner != owner, "INVALID_ADDRESS"); pendingOwner = newOwner; } /// @dev Allows the pendingOwner address to finalize the transfer. function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0x0); } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title ITradeHistory /// @dev Stores the trade history and cancelled data of orders /// @author Brecht Devos - <[email protected]>. contract ITradeHistory { // The following map is used to keep trace of order fill and cancellation // history. mapping (bytes32 => uint) public filled; // This map is used to keep trace of order's cancellation history. mapping (address => mapping (bytes32 => bool)) public cancelled; // A map from a broker to its cutoff timestamp. mapping (address => uint) public cutoffs; // A map from a broker to its trading-pair cutoff timestamp. mapping (address => mapping (bytes20 => uint)) public tradingPairCutoffs; // A map from a broker to an order owner to its cutoff timestamp. mapping (address => mapping (address => uint)) public cutoffsOwner; // A map from a broker to an order owner to its trading-pair cutoff timestamp. mapping (address => mapping (address => mapping (bytes20 => uint))) public tradingPairCutoffsOwner; function batchUpdateFilled( bytes32[] calldata filledInfo ) external; function setCancelled( address broker, bytes32 orderHash ) external; function setCutoffs( address broker, uint cutoff ) external; function setTradingPairCutoffs( address broker, bytes20 tokenPair, uint cutoff ) external; function setCutoffsOfOwner( address broker, address owner, uint cutoff ) external; function setTradingPairCutoffsOfOwner( address broker, address owner, bytes20 tokenPair, uint cutoff ) external; function batchGetFilledAndCheckCancelled( bytes32[] calldata orderInfo ) external view returns (uint[] memory fills); /// @dev Add a Loopring protocol address. /// @param addr A loopring protocol address. function authorizeAddress( address addr ) external; /// @dev Remove a Loopring protocol address. /// @param addr A loopring protocol address. function deauthorizeAddress( address addr ) external; function isAddressAuthorized( address addr ) public view returns (bool); function suspend() external; function resume() external; function kill() external; } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title Authorizable /// @dev The Authorizable contract allows a contract to be used by other contracts /// by authorizing it by the contract owner. contract Authorizable is Claimable, Errors { event AddressAuthorized( address indexed addr ); event AddressDeauthorized( address indexed addr ); // The list of all authorized addresses address[] authorizedAddresses; mapping (address => uint) private positionMap; struct AuthorizedAddress { uint pos; address addr; } modifier onlyAuthorized() { require(positionMap[msg.sender] > 0, UNAUTHORIZED); _; } function authorizeAddress( address addr ) external onlyOwner { require(address(0x0) != addr, ZERO_ADDRESS); require(0 == positionMap[addr], ALREADY_EXIST); require(isContract(addr), INVALID_ADDRESS); authorizedAddresses.push(addr); positionMap[addr] = authorizedAddresses.length; emit AddressAuthorized(addr); } function deauthorizeAddress( address addr ) external onlyOwner { require(address(0x0) != addr, ZERO_ADDRESS); uint pos = positionMap[addr]; require(pos != 0, NOT_FOUND); uint size = authorizedAddresses.length; if (pos != size) { address lastOne = authorizedAddresses[size - 1]; authorizedAddresses[pos - 1] = lastOne; positionMap[lastOne] = pos; } authorizedAddresses.length -= 1; delete positionMap[addr]; emit AddressDeauthorized(addr); } function isAddressAuthorized( address addr ) public view returns (bool) { return positionMap[addr] > 0; } function isContract( address addr ) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint { function mul( uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "INVALID_VALUE"); } function sub( uint a, uint b ) internal pure returns (uint) { require(b <= a, "INVALID_VALUE"); return a - b; } function add( uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a, "INVALID_VALUE"); } function hasRoundingError( uint value, uint numerator, uint denominator ) internal pure returns (bool) { uint multiplied = mul(value, numerator); uint remainder = multiplied % denominator; // Return true if the rounding error is larger than 1% return mul(remainder, 100) > multiplied; } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title Killable /// @dev The Killable contract allows the contract owner to suspend, resume or kill the contract contract Killable is Claimable, Errors { bool public suspended = false; modifier notSuspended() { require(!suspended, INVALID_STATE); _; } modifier isSuspended() { require(suspended, INVALID_STATE); _; } function suspend() external onlyOwner notSuspended { suspended = true; } function resume() external onlyOwner isSuspended { suspended = false; } /// owner must suspend the delegate first before invoking the kill method. function kill() external onlyOwner isSuspended { owner = address(0x0); emit OwnershipTransferred(owner, address(0x0)); } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /// @title NoDefaultFunc /// @dev Disable default functions. contract NoDefaultFunc is Errors { function () external payable { revert(UNSUPPORTED); } } /// @title An Implementation of ITradeHistory. /// @author Brecht Devos - <[email protected]>. contract TradeHistory is ITradeHistory, Authorizable, Killable, NoDefaultFunc { using MathUint for uint; function batchUpdateFilled( bytes32[] calldata filledInfo ) external onlyAuthorized notSuspended { uint length = filledInfo.length; require(length % 2 == 0, INVALID_SIZE); uint start = 68; uint end = start + length * 32; for (uint p = start; p < end; p += 64) { bytes32 hash; uint filledAmount; assembly { hash := calldataload(add(p, 0)) filledAmount := calldataload(add(p, 32)) } filled[hash] = filledAmount; } } function setCancelled( address broker, bytes32 orderHash ) external onlyAuthorized notSuspended { cancelled[broker][orderHash] = true; } function setCutoffs( address broker, uint cutoff ) external onlyAuthorized notSuspended { require(cutoffs[broker] < cutoff, INVALID_VALUE); cutoffs[broker] = cutoff; } function setTradingPairCutoffs( address broker, bytes20 tokenPair, uint cutoff ) external onlyAuthorized notSuspended { require(tradingPairCutoffs[broker][tokenPair] < cutoff, INVALID_VALUE); tradingPairCutoffs[broker][tokenPair] = cutoff; } function setCutoffsOfOwner( address broker, address owner, uint cutoff ) external onlyAuthorized notSuspended { require(cutoffsOwner[broker][owner] < cutoff, INVALID_VALUE); cutoffsOwner[broker][owner] = cutoff; } function setTradingPairCutoffsOfOwner( address broker, address owner, bytes20 tokenPair, uint cutoff ) external onlyAuthorized notSuspended { require(tradingPairCutoffsOwner[broker][owner][tokenPair] < cutoff, INVALID_VALUE); tradingPairCutoffsOwner[broker][owner][tokenPair] = cutoff; } function batchGetFilledAndCheckCancelled( bytes32[] calldata batch ) external view returns (uint[] memory fills) { uint length = batch.length; require(length % 5 == 0, INVALID_SIZE); uint start = 68; uint end = start + length * 32; uint i = 0; fills = new uint[](length / 5); for (uint p = start; p < end; p += 160) { address broker; address owner; bytes32 hash; uint validSince; bytes20 tradingPair; assembly { broker := calldataload(add(p, 0)) owner := calldataload(add(p, 32)) hash := calldataload(add(p, 64)) validSince := calldataload(add(p, 96)) tradingPair := calldataload(add(p, 128)) } bool valid = !cancelled[broker][hash]; valid = valid && validSince > tradingPairCutoffs[broker][tradingPair]; valid = valid && validSince > cutoffs[broker]; valid = valid && validSince > tradingPairCutoffsOwner[broker][owner][tradingPair]; valid = valid && validSince > cutoffsOwner[broker][owner]; fills[i++] = valid ? filled[hash] : ~uint(0); } } }
@title ITradeHistory @dev Stores the trade history and cancelled data of orders @author Brecht Devos - <[email protected]>. The following map is used to keep trace of order fill and cancellation history. This map is used to keep trace of order's cancellation history. A map from a broker to its cutoff timestamp. A map from a broker to its trading-pair cutoff timestamp. A map from a broker to an order owner to its cutoff timestamp. A map from a broker to an order owner to its trading-pair cutoff timestamp.
contract ITradeHistory { mapping (bytes32 => uint) public filled; mapping (address => mapping (bytes32 => bool)) public cancelled; mapping (address => uint) public cutoffs; mapping (address => mapping (bytes20 => uint)) public tradingPairCutoffs; mapping (address => mapping (address => uint)) public cutoffsOwner; mapping (address => mapping (address => mapping (bytes20 => uint))) public tradingPairCutoffsOwner; function batchUpdateFilled( bytes32[] calldata filledInfo ) external; function setCancelled( address broker, bytes32 orderHash ) external; function setCutoffs( address broker, uint cutoff ) external; function setTradingPairCutoffs( address broker, bytes20 tokenPair, uint cutoff ) external; function setCutoffsOfOwner( address broker, address owner, uint cutoff ) external; function setTradingPairCutoffsOfOwner( address broker, address owner, bytes20 tokenPair, uint cutoff ) external; function batchGetFilledAndCheckCancelled( bytes32[] calldata orderInfo ) external view returns (uint[] memory fills); function authorizeAddress( address addr ) external; function deauthorizeAddress( address addr ) external; function isAddressAuthorized( address addr ) public view returns (bool); function suspend() external; function resume() external; function kill() external; }
5,364,147
[ 1, 1285, 354, 323, 5623, 225, 20296, 455, 326, 18542, 4927, 471, 13927, 501, 434, 11077, 225, 605, 266, 343, 88, 9562, 538, 300, 411, 6073, 343, 88, 36, 6498, 8022, 18, 3341, 18652, 1021, 3751, 852, 353, 1399, 358, 3455, 2606, 434, 1353, 3636, 471, 7272, 4927, 18, 1220, 852, 353, 1399, 358, 3455, 2606, 434, 1353, 1807, 7272, 4927, 18, 432, 852, 628, 279, 8625, 358, 2097, 13383, 2858, 18, 432, 852, 628, 279, 8625, 358, 2097, 1284, 7459, 17, 6017, 13383, 2858, 18, 432, 852, 628, 279, 8625, 358, 392, 1353, 3410, 358, 2097, 13383, 2858, 18, 432, 852, 628, 279, 8625, 358, 392, 1353, 3410, 358, 2097, 1284, 7459, 17, 6017, 13383, 2858, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 467, 22583, 5623, 288, 203, 203, 565, 2874, 261, 3890, 1578, 516, 2254, 13, 1071, 6300, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 3890, 1578, 516, 1426, 3719, 1071, 13927, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 6391, 26600, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 3890, 3462, 516, 2254, 3719, 1071, 1284, 7459, 4154, 15812, 26600, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 3719, 1071, 6391, 26600, 5541, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2874, 261, 3890, 3462, 516, 2254, 20349, 1071, 1284, 7459, 4154, 15812, 26600, 5541, 31, 203, 203, 203, 565, 445, 2581, 1891, 29754, 12, 203, 3639, 1731, 1578, 8526, 745, 892, 6300, 966, 203, 3639, 262, 203, 3639, 3903, 31, 203, 203, 565, 445, 444, 21890, 12, 203, 3639, 1758, 8625, 16, 203, 3639, 1731, 1578, 1353, 2310, 203, 3639, 262, 203, 3639, 3903, 31, 203, 203, 565, 445, 11440, 322, 26600, 12, 203, 3639, 1758, 8625, 16, 203, 3639, 2254, 13383, 203, 3639, 262, 203, 3639, 3903, 31, 203, 203, 565, 445, 444, 1609, 7459, 4154, 15812, 26600, 12, 203, 3639, 1758, 8625, 16, 203, 3639, 1731, 3462, 1147, 4154, 16, 203, 3639, 2254, 13383, 203, 3639, 262, 203, 3639, 3903, 31, 203, 203, 565, 445, 11440, 322, 26600, 951, 5541, 12, 203, 3639, 1758, 8625, 16, 203, 3639, 1758, 3410, 16, 203, 3639, 2254, 13383, 203, 3639, 262, 203, 3639, 3903, 31, 203, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import './lib/SafeERC20.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import './interfaces/ERC20FeeProxy.sol'; import './interfaces/EthereumFeeProxy.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; /** * @title BatchPayments * @notice This contract makes multiple payments with references, in one transaction: * - on: ERC20 Payment Proxy and ETH Payment Proxy of the Request Network protocol * - to: multiple addresses * - fees: ERC20 and ETH proxies fees are paid to the same address. * An additional batch fee is paid to the same address. * If one transaction of the batch fail, every transactions are reverted. */ contract BatchPayments is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; IERC20FeeProxy public paymentErc20FeeProxy; IEthereumFeeProxy public paymentEthFeeProxy; // @dev: Between 0 and 1000, i.e: batchFee = 10 represent 1% of fee uint256 public batchFee; struct Token { address tokenAddress; uint256 amountAndFee; uint256 batchFeeAmount; } /** * @param _paymentErc20FeeProxy The address to the ERC20 payment proxy to use. * @param _paymentEthFeeProxy The address to the Ethereum payment proxy to use. * @param _owner Owner of the contract. */ constructor( address _paymentErc20FeeProxy, address _paymentEthFeeProxy, address _owner ) { paymentErc20FeeProxy = IERC20FeeProxy(_paymentErc20FeeProxy); paymentEthFeeProxy = IEthereumFeeProxy(_paymentEthFeeProxy); transferOwnership(_owner); batchFee = 0; } // batch Eth requires batch contract to receive funds from ethFeeProxy receive() external payable { require(msg.value == 0, 'Non-payable'); } /** * @notice Send a batch of Eth payments w/fees with paymentReferences to multiple accounts. * If one payment failed, the whole batch is reverted * @param _recipients List of recipients accounts. * @param _amounts List of amounts, corresponding to recipients[]. * @param _paymentReferences List of paymentRefs, corr. to the recipients[]. * @param _feeAmounts List of amounts of the payment fee, corr. to the recipients[]. * @param _feeAddress The fee recipient. * @dev It uses EthereumFeeProxy to pay an invoice and fees, with a payment reference. * Make sure: msg.value >= sum(_amouts)+sum(_feeAmounts)+sumBatchFeeAmount */ function batchEthPaymentsWithReference( address[] calldata _recipients, uint256[] calldata _amounts, bytes[] calldata _paymentReferences, uint256[] calldata _feeAmounts, address payable _feeAddress ) external payable nonReentrant { require( _recipients.length == _amounts.length && _recipients.length == _paymentReferences.length && _recipients.length == _feeAmounts.length, 'the input arrays must have the same length' ); // amount is used to get the total amount and then used as batch fee amount uint256 amount = 0; // Batch contract pays the requests thourgh EthFeeProxy for (uint256 i = 0; i < _recipients.length; i++) { require(address(this).balance >= _amounts[i] + _feeAmounts[i], 'not enough funds'); amount += _amounts[i]; paymentEthFeeProxy.transferWithReferenceAndFee{value: _amounts[i] + _feeAmounts[i]}( payable(_recipients[i]), _paymentReferences[i], _feeAmounts[i], payable(_feeAddress) ); } // amount is updated into batch fee amount amount = (amount * batchFee) / 1000; // Check that batch contract has enough funds to pay batch fee require(address(this).balance >= amount, 'not enough funds for batch fee'); // Batch pays batch fee _feeAddress.transfer(amount); // Batch contract transfers the remaining ethers to the payer if (address(this).balance > 0) { (bool sendBackSuccess, ) = payable(msg.sender).call{value: address(this).balance}(''); require(sendBackSuccess, 'Could not send remaining funds to the payer'); } } /** * @notice Send a batch of erc20 payments w/fees with paymentReferences to multiple accounts. * @param _tokenAddress Token to transact with. * @param _recipients List of recipients accounts. * @param _amounts List of amounts, corresponding to recipients[]. * @param _paymentReferences List of paymentRefs, corr. to the recipients[] and . * @param _feeAmounts List of amounts of the payment fee, corr. to the recipients[]. * @param _feeAddress The fee recipient. * @dev Uses ERC20FeeProxy to pay an invoice and fees, with a payment reference. * Make sure the contract has allowance to spend the payer token. * Make sure the payer has enough tokens to pay the amount, the fee, the batch fee */ function batchERC20PaymentsWithReference( address _tokenAddress, address[] calldata _recipients, uint256[] calldata _amounts, bytes[] calldata _paymentReferences, uint256[] calldata _feeAmounts, address _feeAddress ) external { require( _recipients.length == _amounts.length && _recipients.length == _paymentReferences.length && _recipients.length == _feeAmounts.length, 'the input arrays must have the same length' ); // amount is used to get the total amount and fee, and then used as batch fee amount uint256 amount = 0; for (uint256 i = 0; i < _recipients.length; i++) { amount += _amounts[i] + _feeAmounts[i]; } // Transfer the amount and fee from the payer to the batch contract IERC20 requestedToken = IERC20(_tokenAddress); require( requestedToken.allowance(msg.sender, address(this)) >= amount, 'Not sufficient allowance for batch to pay' ); require(requestedToken.balanceOf(msg.sender) >= amount, 'not enough funds'); require( safeTransferFrom(_tokenAddress, address(this), amount), 'payment transferFrom() failed' ); // Batch contract approve Erc20FeeProxy to spend the token if (requestedToken.allowance(address(this), address(paymentErc20FeeProxy)) < amount) { approvePaymentProxyToSpend(address(requestedToken)); } // Batch contract pays the requests using Erc20FeeProxy for (uint256 i = 0; i < _recipients.length; i++) { // amount is updated to become the sum of amounts, to calculate batch fee amount amount -= _feeAmounts[i]; paymentErc20FeeProxy.transferFromWithReferenceAndFee( _tokenAddress, _recipients[i], _amounts[i], _paymentReferences[i], _feeAmounts[i], _feeAddress ); } // amount is updated into batch fee amount amount = (amount * batchFee) / 1000; // Check if the payer has enough funds to pay batch fee require(requestedToken.balanceOf(msg.sender) >= amount, 'not enough funds for the batch fee'); // Payer pays batch fee amount require( safeTransferFrom(_tokenAddress, _feeAddress, amount), 'batch fee transferFrom() failed' ); } /** * @notice Send a batch of erc20 payments on multiple tokens w/fees with paymentReferences to multiple accounts. * @param _tokenAddresses List of tokens to transact with. * @param _recipients List of recipients accounts. * @param _amounts List of amounts, corresponding to recipients[]. * @param _paymentReferences List of paymentRefs, corr. to the recipients[]. * @param _feeAmounts List of amounts of the payment fee, corr. to the recipients[]. * @param _feeAddress The fee recipient. * @dev It uses ERC20FeeProxy to pay an invoice and fees, with a payment reference. * Make sure the contract has allowance to spend the payer token. * Make sure the payer has enough tokens to pay the amount, the fee, the batch fee */ function batchERC20PaymentsMultiTokensWithReference( address[] calldata _tokenAddresses, address[] calldata _recipients, uint256[] calldata _amounts, bytes[] calldata _paymentReferences, uint256[] calldata _feeAmounts, address _feeAddress ) external { require( _tokenAddresses.length == _recipients.length && _tokenAddresses.length == _amounts.length && _tokenAddresses.length == _paymentReferences.length && _tokenAddresses.length == _feeAmounts.length, 'the input arrays must have the same length' ); // Create a list of unique tokens used and the amounts associated // Only considere tokens having: amounts + feeAmounts > 0 // batchFeeAmount is the amount's sum, and then, batch fee rate is applied Token[] memory uniqueTokens = new Token[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; i++) { for (uint256 j = 0; j < _tokenAddresses.length; j++) { // If the token is already in the existing uniqueTokens list if (uniqueTokens[j].tokenAddress == _tokenAddresses[i]) { uniqueTokens[j].amountAndFee += _amounts[i] + _feeAmounts[i]; uniqueTokens[j].batchFeeAmount += _amounts[i]; break; } // If the token is not in the list (amountAndFee = 0), and amount + fee > 0 if (uniqueTokens[j].amountAndFee == 0 && (_amounts[i] + _feeAmounts[i]) > 0) { uniqueTokens[j].tokenAddress = _tokenAddresses[i]; uniqueTokens[j].amountAndFee = _amounts[i] + _feeAmounts[i]; uniqueTokens[j].batchFeeAmount = _amounts[i]; break; } } } // The payer transfers tokens to the batch contract and pays batch fee for (uint256 i = 0; i < uniqueTokens.length && uniqueTokens[i].amountAndFee > 0; i++) { uniqueTokens[i].batchFeeAmount = (uniqueTokens[i].batchFeeAmount * batchFee) / 1000; IERC20 requestedToken = IERC20(uniqueTokens[i].tokenAddress); require( requestedToken.allowance(msg.sender, address(this)) >= uniqueTokens[i].amountAndFee + uniqueTokens[i].batchFeeAmount, 'Not sufficient allowance for batch to pay' ); // check if the payer can pay the amount, the fee, and the batchFee require( requestedToken.balanceOf(msg.sender) >= uniqueTokens[i].amountAndFee + uniqueTokens[i].batchFeeAmount, 'not enough funds' ); // Transfer only the amount and fee required for the token on the batch contract require( safeTransferFrom(uniqueTokens[i].tokenAddress, address(this), uniqueTokens[i].amountAndFee), 'payment transferFrom() failed' ); // Batch contract approves Erc20FeeProxy to spend the token if ( requestedToken.allowance(address(this), address(paymentErc20FeeProxy)) < uniqueTokens[i].amountAndFee ) { approvePaymentProxyToSpend(address(requestedToken)); } // Payer pays batch fee amount require( safeTransferFrom(uniqueTokens[i].tokenAddress, _feeAddress, uniqueTokens[i].batchFeeAmount), 'batch fee transferFrom() failed' ); } // Batch contract pays the requests using Erc20FeeProxy for (uint256 i = 0; i < _recipients.length; i++) { paymentErc20FeeProxy.transferFromWithReferenceAndFee( _tokenAddresses[i], _recipients[i], _amounts[i], _paymentReferences[i], _feeAmounts[i], _feeAddress ); } } /** * @notice Authorizes the proxy to spend a new request currency (ERC20). * @param _erc20Address Address of an ERC20 used as the request currency. */ function approvePaymentProxyToSpend(address _erc20Address) public { IERC20 erc20 = IERC20(_erc20Address); uint256 max = 2**256 - 1; erc20.safeApprove(address(paymentErc20FeeProxy), max); } /** * @notice Call transferFrom ERC20 function and validates the return data of a ERC20 contract call. * @dev This is necessary because of non-standard ERC20 tokens that don't have a return value. * @return result The return value of the ERC20 call, returning true for non-standard tokens */ function safeTransferFrom( address _tokenAddress, address _to, uint256 _amount ) internal returns (bool result) { /* solium-disable security/no-inline-assembly */ // check if the address is a contract assembly { if iszero(extcodesize(_tokenAddress)) { revert(0, 0) } } // solium-disable-next-line security/no-low-level-calls (bool success, ) = _tokenAddress.call( abi.encodeWithSignature('transferFrom(address,address,uint256)', msg.sender, _to, _amount) ); assembly { switch returndatasize() case 0 { // Not a standard erc20 result := 1 } case 32 { // Standard erc20 returndatacopy(0, 0, 32) result := mload(0) } default { // Anything else, should revert for safety revert(0, 0) } } require(success, 'transferFrom() has been reverted'); /* solium-enable security/no-inline-assembly */ return result; } /* * Admin functions to edit the proxies address */ function setBatchFee(uint256 _batchFee) public onlyOwner { batchFee = _batchFee; } function setPaymentErc20FeeProxy(address _paymentErc20FeeProxy) public onlyOwner { paymentErc20FeeProxy = IERC20FeeProxy(_paymentErc20FeeProxy); } function setPaymentEthFeeProxy(address _paymentEthFeeProxy) public onlyOwner { paymentEthFeeProxy = IEthereumFeeProxy(_paymentEthFeeProxy); } }
batch Eth requires batch contract to receive funds from ethFeeProxy
receive() external payable { require(msg.value == 0, 'Non-payable'); }
12,792,033
[ 1, 5303, 512, 451, 4991, 2581, 6835, 358, 6798, 284, 19156, 628, 13750, 14667, 3886, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 6798, 1435, 3903, 8843, 429, 288, 203, 565, 2583, 12, 3576, 18, 1132, 422, 374, 16, 296, 3989, 17, 10239, 429, 8284, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./interfaces/INodeOperatorRegistry.sol"; import "./interfaces/IValidatorFactory.sol"; import "./interfaces/IValidator.sol"; import "./interfaces/IStMATIC.sol"; /// @title NodeOperatorRegistry /// @author 2021 ShardLabs. /// @notice NodeOperatorRegistry is the main contract that manage validators /// @dev NodeOperatorRegistry is the main contract that manage operators. contract NodeOperatorRegistry is INodeOperatorRegistry, PausableUpgradeable, AccessControlUpgradeable, ReentrancyGuardUpgradeable { enum NodeOperatorStatus { INACTIVE, ACTIVE, STOPPED, UNSTAKED, CLAIMED, EXIT, JAILED, EJECTED } /// @notice The node operator struct /// @param status node operator status(INACTIVE, ACTIVE, STOPPED, CLAIMED, UNSTAKED, EXIT, JAILED, EJECTED). /// @param name node operator name. /// @param rewardAddress Validator public key used for access control and receive rewards. /// @param validatorId validator id of this node operator on the polygon stake manager. /// @param signerPubkey public key used on heimdall. /// @param validatorShare validator share contract used to delegate for on polygon. /// @param validatorProxy the validator proxy, the owner of the validator. /// @param commissionRate the commission rate applied by the operator on polygon. /// @param maxDelegateLimit max delegation limit that StMatic contract will delegate to this operator each time delegate function is called. struct NodeOperator { NodeOperatorStatus status; string name; address rewardAddress; bytes signerPubkey; address validatorShare; address validatorProxy; uint256 validatorId; uint256 commissionRate; uint256 maxDelegateLimit; } /// @notice all the roles. bytes32 public constant REMOVE_OPERATOR_ROLE = keccak256("LIDO_REMOVE_OPERATOR"); bytes32 public constant PAUSE_OPERATOR_ROLE = keccak256("LIDO_PAUSE_OPERATOR"); bytes32 public constant DAO_ROLE = keccak256("LIDO_DAO"); /// @notice contract version. string public version; /// @notice total node operators. uint256 private totalNodeOperators; /// @notice validatorFactory address. address private validatorFactory; /// @notice stakeManager address. address private stakeManager; /// @notice polygonERC20 token (Matic) address. address private polygonERC20; /// @notice stMATIC address. address private stMATIC; /// @notice keeps track of total number of operators uint256 nodeOperatorCounter; /// @notice min amount allowed to stake per validator. uint256 public minAmountStake; /// @notice min HeimdallFees allowed to stake per validator. uint256 public minHeimdallFees; /// @notice commision rate applied to all the operators. uint256 public commissionRate; /// @notice allows restake. bool public allowsRestake; /// @notice default max delgation limit. uint256 public defaultMaxDelegateLimit; /// @notice This stores the operators ids. uint256[] private operatorIds; /// @notice Mapping of all owners with node operator id. Mapping is used to be able to /// extend the struct. mapping(address => uint256) private operatorOwners; /// @notice Mapping of all node operators. Mapping is used to be able to extend the struct. mapping(uint256 => NodeOperator) private operators; /// --------------------------- Modifiers----------------------------------- /// @notice Check if the msg.sender has permission. /// @param _role role needed to call function. modifier userHasRole(bytes32 _role) { checkCondition(hasRole(_role, msg.sender), "unauthorized"); _; } /// @notice Check if the amount is inbound. /// @param _amount amount to stake. modifier checkStakeAmount(uint256 _amount) { checkCondition(_amount >= minAmountStake, "Invalid amount"); _; } /// @notice Check if the heimdall fee is inbound. /// @param _heimdallFee heimdall fee. modifier checkHeimdallFees(uint256 _heimdallFee) { checkCondition(_heimdallFee >= minHeimdallFees, "Invalid fees"); _; } /// @notice Check if the maxDelegateLimit is less or equal to 10 Billion. /// @param _maxDelegateLimit max delegate limit. modifier checkMaxDelegationLimit(uint256 _maxDelegateLimit) { checkCondition( _maxDelegateLimit <= 10000000000 ether, "Max amount <= 10B" ); _; } /// @notice Check if the rewardAddress is already used. /// @param _rewardAddress new reward address. modifier checkIfRewardAddressIsUsed(address _rewardAddress) { checkCondition( operatorOwners[_rewardAddress] == 0 && _rewardAddress != address(0), "Address used" ); _; } /// -------------------------- initialize ---------------------------------- /// @notice Initialize the NodeOperator contract. function initialize( address _validatorFactory, address _stakeManager, address _polygonERC20, address _stMATIC ) external initializer { __Pausable_init(); __AccessControl_init(); __ReentrancyGuard_init(); validatorFactory = _validatorFactory; stakeManager = _stakeManager; polygonERC20 = _polygonERC20; stMATIC = _stMATIC; minAmountStake = 10 * 10**18; minHeimdallFees = 20 * 10**18; defaultMaxDelegateLimit = 10 ether; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(REMOVE_OPERATOR_ROLE, msg.sender); _setupRole(PAUSE_OPERATOR_ROLE, msg.sender); _setupRole(DAO_ROLE, msg.sender); } /// ----------------------------- API -------------------------------------- /// @notice Add a new node operator to the system. /// @dev The operator life cycle starts when we call the addOperator /// func allows adding a new operator. During this call, a new validatorProxy is /// deployed by the ValidatorFactory which we can use later to interact with the /// Polygon StakeManager. At the end of this call, the status of the operator /// will be INACTIVE. /// @param _name the node operator name. /// @param _rewardAddress address used for ACL and receive rewards. /// @param _signerPubkey public key used on heimdall len 64 bytes. function addOperator( string memory _name, address _rewardAddress, bytes memory _signerPubkey ) external override whenNotPaused userHasRole(DAO_ROLE) checkIfRewardAddressIsUsed(_rewardAddress) { nodeOperatorCounter++; address validatorProxy = IValidatorFactory(validatorFactory).create(); operators[nodeOperatorCounter] = NodeOperator({ status: NodeOperatorStatus.INACTIVE, name: _name, rewardAddress: _rewardAddress, validatorId: 0, signerPubkey: _signerPubkey, validatorShare: address(0), validatorProxy: validatorProxy, commissionRate: commissionRate, maxDelegateLimit: defaultMaxDelegateLimit }); operatorIds.push(nodeOperatorCounter); totalNodeOperators++; operatorOwners[_rewardAddress] = nodeOperatorCounter; emit AddOperator(nodeOperatorCounter); } /// @notice Allows to stop an operator from the system. /// @param _operatorId the node operator id. function stopOperator(uint256 _operatorId) external override { (, NodeOperator storage no) = getOperator(_operatorId); require( no.rewardAddress == msg.sender || hasRole(DAO_ROLE, msg.sender), "unauthorized" ); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE || status == NodeOperatorStatus.JAILED , "Invalid status"); if (status == NodeOperatorStatus.INACTIVE) { no.status = NodeOperatorStatus.EXIT; } else { IStMATIC(stMATIC).withdrawTotalDelegated(no.validatorShare); no.status = NodeOperatorStatus.STOPPED; } emit StopOperator(_operatorId); } /// @notice Allows to remove an operator from the system.when the operator status is /// set to EXIT the GOVERNANCE can call the removeOperator func to delete the operator, /// and the validatorProxy used to interact with the Polygon stakeManager. /// @param _operatorId the node operator id. function removeOperator(uint256 _operatorId) external override whenNotPaused userHasRole(REMOVE_OPERATOR_ROLE) { (, NodeOperator storage no) = getOperator(_operatorId); checkCondition(no.status == NodeOperatorStatus.EXIT, "Invalid status"); // update the operatorIds array by removing the operator id. for (uint256 idx = 0; idx < operatorIds.length - 1; idx++) { if (_operatorId == operatorIds[idx]) { operatorIds[idx] = operatorIds[operatorIds.length - 1]; break; } } operatorIds.pop(); totalNodeOperators--; IValidatorFactory(validatorFactory).remove(no.validatorProxy); delete operatorOwners[no.rewardAddress]; delete operators[_operatorId]; emit RemoveOperator(_operatorId); } /// @notice Allows a validator that was already staked on the polygon stake manager /// to join the PoLido protocol. function joinOperator() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.INACTIVE, "Invalid status" ); IStakeManager sm = IStakeManager(stakeManager); uint256 validatorId = sm.getValidatorId(msg.sender); checkCondition(validatorId != 0, "ValidatorId=0"); IStakeManager.Validator memory poValidator = sm.validators(validatorId); checkCondition( poValidator.contractAddress != address(0), "Validator has no ValidatorShare" ); checkCondition( (poValidator.status == IStakeManager.Status.Active ) && poValidator.deactivationEpoch == 0 , "Validator isn't ACTIVE" ); checkCondition( poValidator.signer == address(uint160(uint256(keccak256(no.signerPubkey)))), "Invalid Signer" ); IValidator(no.validatorProxy).join( validatorId, sm.NFTContract(), msg.sender, no.commissionRate, stakeManager ); no.validatorId = validatorId; address validatorShare = sm.getValidatorContract(validatorId); no.validatorShare = validatorShare; emit JoinOperator(operatorId); } /// ------------------------Stake Manager API------------------------------- /// @notice Allows to stake a validator on the Polygon stakeManager contract. /// @dev The stake func allows each operator's owner to stake, but before that, /// the owner has to approve the amount + Heimdall fees to the ValidatorProxy. /// At the end of this call, the status of the operator is set to ACTIVE. /// @param _amount amount to stake. /// @param _heimdallFee heimdall fees. function stake(uint256 _amount, uint256 _heimdallFee) external override whenNotPaused checkStakeAmount(_amount) checkHeimdallFees(_heimdallFee) { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.INACTIVE, "Invalid status" ); (uint256 validatorId, address validatorShare) = IValidator( no.validatorProxy ).stake( msg.sender, _amount, _heimdallFee, true, no.signerPubkey, no.commissionRate, stakeManager, polygonERC20 ); no.validatorId = validatorId; no.validatorShare = validatorShare; emit StakeOperator(operatorId, _amount, _heimdallFee); } /// @notice Allows to restake Matics to Polygon stakeManager /// @dev restake allows an operator's owner to increase the total staked amount /// on Polygon. The owner has to approve the amount to the ValidatorProxy then make /// a call. /// @param _amount amount to stake. function restake(uint256 _amount, bool _restakeRewards) external override whenNotPaused { checkCondition(allowsRestake, "Restake is disabled"); if (_amount == 0) { revert("Amount is ZERO"); } (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.ACTIVE, "Invalid status" ); IValidator(no.validatorProxy).restake( msg.sender, no.validatorId, _amount, _restakeRewards, stakeManager, polygonERC20 ); emit RestakeOperator(operatorId, _amount, _restakeRewards); } /// @notice Unstake a validator from the Polygon stakeManager contract. /// @dev when the operators's owner wants to quite the PoLido protocol he can call /// the unstake func, in this case, the operator status is set to UNSTAKED. function unstake() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.JAILED || status == NodeOperatorStatus.EJECTED, "Invalid status" ); if (status == NodeOperatorStatus.ACTIVE) { IValidator(no.validatorProxy).unstake(no.validatorId, stakeManager); } _unstake(operatorId, no); } /// @notice The DAO unstake the operator if it was unstaked by the stakeManager. /// @dev when the operator was unstaked by the stage Manager the DAO can use this /// function to update the operator status and also withdraw the delegated tokens, /// without waiting for the owner to call the unstake function /// @param _operatorId operator id. function unstake(uint256 _operatorId) external userHasRole(DAO_ROLE) { NodeOperator storage no = operators[_operatorId]; NodeOperatorStatus status = getOperatorStatus(no); checkCondition(status == NodeOperatorStatus.EJECTED, "Invalid status"); _unstake(_operatorId, no); } function _unstake(uint256 _operatorId, NodeOperator storage no) private whenNotPaused { IStMATIC(stMATIC).withdrawTotalDelegated(no.validatorShare); no.status = NodeOperatorStatus.UNSTAKED; emit UnstakeOperator(_operatorId); } /// @notice Allows the operator's owner to migrate the validator ownership to rewardAddress. /// This can be done only in the case where this operator was stopped by the DAO. function migrate() external override nonReentrant { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition(no.status == NodeOperatorStatus.STOPPED, "Invalid status"); IValidator(no.validatorProxy).migrate( no.validatorId, IStakeManager(stakeManager).NFTContract(), no.rewardAddress ); no.status = NodeOperatorStatus.EXIT; emit MigrateOperator(operatorId); } /// @notice Allows to unjail the validator and turn his status from UNSTAKED to ACTIVE. /// @dev when an operator is JAILED the owner can switch back and stake the /// operator by calling the unjail func, in this case, the operator status is set /// to back ACTIVE. function unjail() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.JAILED, "Invalid status" ); IValidator(no.validatorProxy).unjail(no.validatorId, stakeManager); emit Unjail(operatorId); } /// @notice Allows to top up heimdall fees. /// @dev the operator's owner can topUp the heimdall fees by calling the /// topUpForFee, but before that node operator needs to approve the amount of heimdall /// fees to his validatorProxy. /// @param _heimdallFee amount function topUpForFee(uint256 _heimdallFee) external override whenNotPaused checkHeimdallFees(_heimdallFee) { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.ACTIVE, "Invalid status" ); IValidator(no.validatorProxy).topUpForFee( msg.sender, _heimdallFee, stakeManager, polygonERC20 ); emit TopUpHeimdallFees(operatorId, _heimdallFee); } /// @notice Allows to unstake staked tokens after withdraw delay. /// @dev after the unstake the operator and waiting for the Polygon withdraw_delay /// the owner can transfer back his staked balance by calling /// unsttakeClaim, after that the operator status is set to CLAIMED function unstakeClaim() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.UNSTAKED, "Invalid status" ); uint256 amount = IValidator(no.validatorProxy).unstakeClaim( no.validatorId, msg.sender, stakeManager, polygonERC20 ); no.status = NodeOperatorStatus.CLAIMED; emit UnstakeClaim(operatorId, amount); } /// @notice Allows withdraw heimdall fees /// @dev the operator's owner can claim the heimdall fees. /// func, after that the operator status is set to EXIT. /// @param _accumFeeAmount accumulated heimdall fees /// @param _index index /// @param _proof proof function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof ) external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( no.status == NodeOperatorStatus.CLAIMED, "Invalid status" ); IValidator(no.validatorProxy).claimFee( _accumFeeAmount, _index, _proof, no.rewardAddress, stakeManager, polygonERC20 ); no.status = NodeOperatorStatus.EXIT; emit ClaimFee(operatorId); } /// @notice Allows the operator's owner to withdraw rewards. function withdrawRewards() external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); checkCondition( getOperatorStatus(no) == NodeOperatorStatus.ACTIVE, "Invalid status" ); address rewardAddress = no.rewardAddress; uint256 rewards = IValidator(no.validatorProxy).withdrawRewards( no.validatorId, rewardAddress, stakeManager, polygonERC20 ); emit WithdrawRewards(operatorId, rewardAddress, rewards); } /// @notice Allows the operator's owner to update signer publickey. /// @param _signerPubkey new signer publickey function updateSigner(bytes memory _signerPubkey) external override whenNotPaused { (uint256 operatorId, NodeOperator storage no) = getOperator(0); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE, "Invalid status" ); if (no.status == NodeOperatorStatus.ACTIVE) { IValidator(no.validatorProxy).updateSigner( no.validatorId, _signerPubkey, stakeManager ); } no.signerPubkey = _signerPubkey; emit UpdateSignerPubkey(operatorId); } /// @notice Allows the operator owner to update the name. /// @param _name new operator name. function setOperatorName(string memory _name) external override whenNotPaused { // uint256 operatorId = getOperatorId(msg.sender); // NodeOperator storage no = operators[operatorId]; (uint256 operatorId, NodeOperator storage no) = getOperator(0); NodeOperatorStatus status = getOperatorStatus(no); checkCondition( status == NodeOperatorStatus.ACTIVE || status == NodeOperatorStatus.INACTIVE, "Invalid status" ); no.name = _name; emit NewName(operatorId, _name); } /// @notice Allows the operator owner to update the rewardAddress. /// @param _rewardAddress new reward address. function setOperatorRewardAddress(address _rewardAddress) external override whenNotPaused checkIfRewardAddressIsUsed(_rewardAddress) { (uint256 operatorId, NodeOperator storage no) = getOperator(0); no.rewardAddress = _rewardAddress; operatorOwners[_rewardAddress] = operatorId; delete operatorOwners[msg.sender]; emit NewRewardAddress(operatorId, _rewardAddress); } /// -------------------------------DAO-------------------------------------- /// @notice Allows the DAO to set the operator defaultMaxDelegateLimit. /// @param _defaultMaxDelegateLimit default max delegation amount. function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit) external override userHasRole(DAO_ROLE) checkMaxDelegationLimit(_defaultMaxDelegateLimit) { defaultMaxDelegateLimit = _defaultMaxDelegateLimit; } /// @notice Allows the DAO to set the operator maxDelegateLimit. /// @param _operatorId operator id. /// @param _maxDelegateLimit max amount to delegate . function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit) external override userHasRole(DAO_ROLE) checkMaxDelegationLimit(_maxDelegateLimit) { (, NodeOperator storage no) = getOperator(_operatorId); no.maxDelegateLimit = _maxDelegateLimit; } /// @notice Allows to set the commission rate used. function setCommissionRate(uint256 _commissionRate) external override userHasRole(DAO_ROLE) { commissionRate = _commissionRate; } /// @notice Allows the dao to update commission rate for an operator. /// @param _operatorId id of the operator /// @param _newCommissionRate new commission rate function updateOperatorCommissionRate( uint256 _operatorId, uint256 _newCommissionRate ) external override userHasRole(DAO_ROLE) { (, NodeOperator storage no) = getOperator(_operatorId); checkCondition( no.rewardAddress != address(0) || no.status == NodeOperatorStatus.ACTIVE, "Invalid status" ); if (no.status == NodeOperatorStatus.ACTIVE) { IValidator(no.validatorProxy).updateCommissionRate( no.validatorId, _newCommissionRate, stakeManager ); } no.commissionRate = _newCommissionRate; emit UpdateCommissionRate(_operatorId, _newCommissionRate); } /// @notice Allows to update the stake amount and heimdall fees /// @param _minAmountStake min amount to stake /// @param _minHeimdallFees min amount of heimdall fees function setStakeAmountAndFees( uint256 _minAmountStake, uint256 _minHeimdallFees ) external override userHasRole(DAO_ROLE) checkStakeAmount(_minAmountStake) checkHeimdallFees(_minHeimdallFees) { minAmountStake = _minAmountStake; minHeimdallFees = _minHeimdallFees; } /// @notice Allows to pause the contract. function togglePause() external override userHasRole(PAUSE_OPERATOR_ROLE) { paused() ? _unpause() : _pause(); } /// @notice Allows to toggle restake. function setRestake(bool _restake) external override userHasRole(DAO_ROLE) { allowsRestake = _restake; } /// @notice Allows to set the StMATIC contract address. function setStMATIC(address _stMATIC) external override userHasRole(DAO_ROLE) { stMATIC = _stMATIC; } /// @notice Allows to set the validator factory contract address. function setValidatorFactory(address _validatorFactory) external override userHasRole(DAO_ROLE) { validatorFactory = _validatorFactory; } /// @notice Allows to set the stake manager contract address. function setStakeManager(address _stakeManager) external override userHasRole(DAO_ROLE) { stakeManager = _stakeManager; } /// @notice Allows to set the contract version. /// @param _version contract version function setVersion(string memory _version) external override userHasRole(DEFAULT_ADMIN_ROLE) { version = _version; } /// @notice Allows to get a node operator by msg.sender. /// @param _owner a valid address of an operator owner, if not set msg.sender will be used. /// @return op returns a node operator. function getNodeOperator(address _owner) external view returns (NodeOperator memory) { uint256 operatorId = operatorOwners[_owner]; return _getNodeOperator(operatorId); } /// @notice Allows to get a node operator by _operatorId. /// @param _operatorId the id of the operator. /// @return op returns a node operator. function getNodeOperator(uint256 _operatorId) external view returns (NodeOperator memory) { return _getNodeOperator(_operatorId); } function _getNodeOperator(uint256 _operatorId) private view returns (NodeOperator memory) { (, NodeOperator memory nodeOperator) = getOperator(_operatorId); nodeOperator.status = getOperatorStatus(nodeOperator); return nodeOperator; } function getOperatorStatus(NodeOperator memory _op) private view returns (NodeOperatorStatus res) { if (_op.status == NodeOperatorStatus.STOPPED) { res = NodeOperatorStatus.STOPPED; } else if (_op.status == NodeOperatorStatus.CLAIMED) { res = NodeOperatorStatus.CLAIMED; } else if (_op.status == NodeOperatorStatus.EXIT) { res = NodeOperatorStatus.EXIT; } else if (_op.status == NodeOperatorStatus.UNSTAKED) { res = NodeOperatorStatus.UNSTAKED; } else { IStakeManager.Validator memory v = IStakeManager(stakeManager) .validators(_op.validatorId); if ( v.status == IStakeManager.Status.Active && v.deactivationEpoch == 0 ) { res = NodeOperatorStatus.ACTIVE; } else if ( ( v.status == IStakeManager.Status.Active || v.status == IStakeManager.Status.Locked ) && v.deactivationEpoch != 0 ) { res = NodeOperatorStatus.EJECTED; } else if ( v.status == IStakeManager.Status.Locked && v.deactivationEpoch == 0 ) { res = NodeOperatorStatus.JAILED; } else { res = NodeOperatorStatus.INACTIVE; } } } /// @notice Allows to get a validator share address. /// @param _operatorId the id of the operator. /// @return va returns a stake manager validator. function getValidatorShare(uint256 _operatorId) external view returns (address) { (, NodeOperator memory op) = getOperator(_operatorId); return op.validatorShare; } /// @notice Allows to get a validator from stake manager. /// @param _operatorId the id of the operator. /// @return va returns a stake manager validator. function getValidator(uint256 _operatorId) external view returns (IStakeManager.Validator memory va) { (, NodeOperator memory op) = getOperator(_operatorId); va = IStakeManager(stakeManager).validators(op.validatorId); } /// @notice Allows to get a validator from stake manager. /// @param _owner user address. /// @return va returns a stake manager validator. function getValidator(address _owner) external view returns (IStakeManager.Validator memory va) { (, NodeOperator memory op) = getOperator(operatorOwners[_owner]); va = IStakeManager(stakeManager).validators(op.validatorId); } /// @notice Get the stMATIC contract addresses function getContracts() external view override returns ( address _validatorFactory, address _stakeManager, address _polygonERC20, address _stMATIC ) { _validatorFactory = validatorFactory; _stakeManager = stakeManager; _polygonERC20 = polygonERC20; _stMATIC = stMATIC; } /// @notice Get the global state function getState() external view override returns ( uint256 _totalNodeOperator, uint256 _totalInactiveNodeOperator, uint256 _totalActiveNodeOperator, uint256 _totalStoppedNodeOperator, uint256 _totalUnstakedNodeOperator, uint256 _totalClaimedNodeOperator, uint256 _totalExitNodeOperator, uint256 _totalJailedNodeOperator, uint256 _totalEjectedNodeOperator ) { uint256 operatorIdsLength = operatorIds.length; _totalNodeOperator = operatorIdsLength; for (uint256 idx = 0; idx < operatorIdsLength; idx++) { uint256 operatorId = operatorIds[idx]; NodeOperator memory op = operators[operatorId]; NodeOperatorStatus status = getOperatorStatus(op); if (status == NodeOperatorStatus.INACTIVE) { _totalInactiveNodeOperator++; } else if (status == NodeOperatorStatus.ACTIVE) { _totalActiveNodeOperator++; } else if (status == NodeOperatorStatus.STOPPED) { _totalStoppedNodeOperator++; } else if (status == NodeOperatorStatus.UNSTAKED) { _totalUnstakedNodeOperator++; } else if (status == NodeOperatorStatus.CLAIMED) { _totalClaimedNodeOperator++; } else if (status == NodeOperatorStatus.JAILED) { _totalJailedNodeOperator++; } else if (status == NodeOperatorStatus.EJECTED) { _totalEjectedNodeOperator++; } else { _totalExitNodeOperator++; } } } /// @notice Get operatorIds. function getOperatorIds() external view override returns (uint256[] memory) { return operatorIds; } /// @notice Returns an operatorInfo list. /// @param _allWithStake if true return all operators with ACTIVE, EJECTED, JAILED. /// @param _delegation if true return all operators that delegation is set to true. /// @return Returns a list of operatorInfo. function getOperatorInfos( bool _delegation, bool _allWithStake ) external view override returns (Operator.OperatorInfo[] memory) { Operator.OperatorInfo[] memory operatorInfos = new Operator.OperatorInfo[]( totalNodeOperators ); uint256 length = operatorIds.length; uint256 index; for (uint256 idx = 0; idx < length; idx++) { uint256 operatorId = operatorIds[idx]; NodeOperator storage no = operators[operatorId]; NodeOperatorStatus status = getOperatorStatus(no); // if operator status is not ACTIVE we continue. But, if _allWithStake is true // we include EJECTED and JAILED operators. if ( status != NodeOperatorStatus.ACTIVE && !(_allWithStake && (status == NodeOperatorStatus.EJECTED || status == NodeOperatorStatus.JAILED)) ) continue; // if true we check if the operator delegation is true. if (_delegation) { if (!IValidatorShare(no.validatorShare).delegation()) continue; } operatorInfos[index] = Operator.OperatorInfo({ operatorId: operatorId, validatorShare: no.validatorShare, maxDelegateLimit: no.maxDelegateLimit, rewardAddress: no.rewardAddress }); index++; } if (index != totalNodeOperators) { Operator.OperatorInfo[] memory operatorInfosOut = new Operator.OperatorInfo[](index); for (uint256 i = 0; i < index; i++) { operatorInfosOut[i] = operatorInfos[i]; } return operatorInfosOut; } return operatorInfos; } /// @notice Checks condition and displays the message /// @param _condition a condition /// @param _message message to display function checkCondition(bool _condition, string memory _message) private pure { require(_condition, _message); } /// @notice Retrieve the operator struct based on the operatorId /// @param _operatorId id of the operator /// @return NodeOperator structure function getOperator(uint256 _operatorId) private view returns (uint256, NodeOperator storage) { if (_operatorId == 0) { _operatorId = getOperatorId(msg.sender); } NodeOperator storage no = operators[_operatorId]; require(no.rewardAddress != address(0), "Operator not found"); return (_operatorId, no); } /// @notice Retrieve the operator struct based on the operator owner address /// @param _user address of the operator owner /// @return NodeOperator structure function getOperatorId(address _user) private view returns (uint256) { uint256 operatorId = operatorOwners[_user]; checkCondition(operatorId != 0, "Operator not found"); return operatorId; } /// -------------------------------Events----------------------------------- /// @notice A new node operator was added. /// @param operatorId node operator id. event AddOperator(uint256 operatorId); /// @notice A new node operator joined. /// @param operatorId node operator id. event JoinOperator(uint256 operatorId); /// @notice A node operator was removed. /// @param operatorId node operator id. event RemoveOperator(uint256 operatorId); /// @param operatorId node operator id. event StopOperator(uint256 operatorId); /// @param operatorId node operator id. event MigrateOperator(uint256 operatorId); /// @notice A node operator was staked. /// @param operatorId node operator id. event StakeOperator( uint256 operatorId, uint256 amount, uint256 heimdallFees ); /// @notice A node operator restaked. /// @param operatorId node operator id. /// @param amount amount to restake. /// @param restakeRewards restake rewards. event RestakeOperator( uint256 operatorId, uint256 amount, bool restakeRewards ); /// @notice A node operator was unstaked. /// @param operatorId node operator id. event UnstakeOperator(uint256 operatorId); /// @notice TopUp heimadall fees. /// @param operatorId node operator id. /// @param amount amount. event TopUpHeimdallFees(uint256 operatorId, uint256 amount); /// @notice Withdraw rewards. /// @param operatorId node operator id. /// @param rewardAddress reward address. /// @param amount amount. event WithdrawRewards( uint256 operatorId, address rewardAddress, uint256 amount ); /// @notice claims unstake. /// @param operatorId node operator id. /// @param amount amount. event UnstakeClaim(uint256 operatorId, uint256 amount); /// @notice update signer publickey. /// @param operatorId node operator id. event UpdateSignerPubkey(uint256 operatorId); /// @notice claim herimdall fee. /// @param operatorId node operator id. event ClaimFee(uint256 operatorId); /// @notice update commission rate. event UpdateCommissionRate(uint256 operatorId, uint256 newCommissionRate); /// @notice Unjail a validator. event Unjail(uint256 operatorId); /// @notice update operator name. event NewName(uint256 operatorId, string name); /// @notice update operator name. event NewRewardAddress(uint256 operatorId, address rewardAddress); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _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; } uint256[49] private __gap; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "../lib/Operator.sol"; /// @title INodeOperatorRegistry /// @author 2021 ShardLabs /// @notice Node operator registry interface interface INodeOperatorRegistry { /// @notice Allows to add a new node operator to the system. /// @param _name the node operator name. /// @param _rewardAddress public address used for ACL and receive rewards. /// @param _signerPubkey public key used on heimdall len 64 bytes. function addOperator( string memory _name, address _rewardAddress, bytes memory _signerPubkey ) external; /// @notice Allows to stop a node operator. /// @param _operatorId node operator id. function stopOperator(uint256 _operatorId) external; /// @notice Allows to remove a node operator from the system. /// @param _operatorId node operator id. function removeOperator(uint256 _operatorId) external; /// @notice Allows a staked validator to join the system. function joinOperator() external; /// @notice Allows to stake an operator on the Polygon stakeManager. /// This function calls Polygon transferFrom so the totalAmount(_amount + _heimdallFee) /// has to be approved first. /// @param _amount amount to stake. /// @param _heimdallFee heimdallFee to stake. function stake(uint256 _amount, uint256 _heimdallFee) external; /// @notice Restake Matics for a validator on polygon stake manager. /// @param _amount amount to stake. /// @param _restakeRewards restake rewards. function restake(uint256 _amount, bool _restakeRewards) external; /// @notice Allows the operator's owner to migrate the NFT. This can be done only /// if the DAO stopped the operator. function migrate() external; /// @notice Allows to unstake an operator from the stakeManager. After the withdraw_delay /// the operator owner can call claimStake func to withdraw the staked tokens. function unstake() external; /// @notice Allows to topup heimdall fees on polygon stakeManager. /// @param _heimdallFee amount to topup. function topUpForFee(uint256 _heimdallFee) external; /// @notice Allows to claim staked tokens on the stake Manager after the end of the /// withdraw delay function unstakeClaim() external; /// @notice Allows an owner to withdraw rewards from the stakeManager. function withdrawRewards() external; /// @notice Allows to update the signer pubkey /// @param _signerPubkey update signer public key function updateSigner(bytes memory _signerPubkey) external; /// @notice Allows to claim the heimdall fees staked by the owner of the operator /// @param _accumFeeAmount accumulated fees amount /// @param _index index /// @param _proof proof function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof ) external; /// @notice Allows to unjail a validator and switch from UNSTAKE status to STAKED function unjail() external; /// @notice Allows an operator's owner to set the operator name. function setOperatorName(string memory _name) external; /// @notice Allows an operator's owner to set the operator rewardAddress. function setOperatorRewardAddress(address _rewardAddress) external; /// @notice Allows the DAO to set _defaultMaxDelegateLimit. function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit) external; /// @notice Allows the DAO to set _maxDelegateLimit for an operator. function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit) external; /// @notice Allows the DAO to set _commissionRate. function setCommissionRate(uint256 _commissionRate) external; /// @notice Allows the DAO to set _commissionRate for an operator. /// @param _operatorId id of the operator /// @param _newCommissionRate new commission rate function updateOperatorCommissionRate( uint256 _operatorId, uint256 _newCommissionRate ) external; /// @notice Allows the DAO to set _minAmountStake and _minHeimdallFees. function setStakeAmountAndFees( uint256 _minAmountStake, uint256 _minHeimdallFees ) external; /// @notice Allows to pause/unpause the node operator contract. function togglePause() external; /// @notice Allows the DAO to enable/disable restake. function setRestake(bool _restake) external; /// @notice Allows the DAO to set stMATIC contract. function setStMATIC(address _stMATIC) external; /// @notice Allows the DAO to set validator factory contract. function setValidatorFactory(address _validatorFactory) external; /// @notice Allows the DAO to set stake manager contract. function setStakeManager(address _stakeManager) external; /// @notice Allows to set contract version. function setVersion(string memory _version) external; /// @notice Get the stMATIC contract addresses function getContracts() external view returns ( address _validatorFactory, address _stakeManager, address _polygonERC20, address _stMATIC ); /// @notice Allows to get stats. function getState() external view returns ( uint256 _totalNodeOperator, uint256 _totalInactiveNodeOperator, uint256 _totalActiveNodeOperator, uint256 _totalStoppedNodeOperator, uint256 _totalUnstakedNodeOperator, uint256 _totalClaimedNodeOperator, uint256 _totalExitNodeOperator, uint256 _totalSlashedNodeOperator, uint256 _totalEjectedNodeOperator ); /// @notice Allows to get a list of operatorInfo. function getOperatorInfos(bool _delegation, bool _allActive) external view returns (Operator.OperatorInfo[] memory); /// @notice Allows to get all the operator ids. function getOperatorIds() external view returns (uint256[] memory); } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "../Validator.sol"; /// @title IValidatorFactory. /// @author 2021 ShardLabs interface IValidatorFactory { /// @notice Deploy a new validator proxy contract. /// @return return the address of the deployed contract. function create() external returns (address); /// @notice Remove a validator proxy from the validators. function remove(address _validatorProxy) external; /// @notice Set the node operator contract address. function setOperator(address _operator) external; /// @notice Set validator implementation contract address. function setValidatorImplementation(address _validatorImplementation) external; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "../Validator.sol"; /// @title IValidator. /// @author 2021 ShardLabs /// @notice Validator interface. interface IValidator { /// @notice Allows to stake a validator on the Polygon stakeManager contract. /// @dev Stake a validator on the Polygon stakeManager contract. /// @param _sender msg.sender. /// @param _amount amount to stake. /// @param _heimdallFee herimdall fees. /// @param _acceptDelegation accept delegation. /// @param _signerPubkey signer public key used on the heimdall. /// @param _commisionRate commision rate of a validator function stake( address _sender, uint256 _amount, uint256 _heimdallFee, bool _acceptDelegation, bytes memory _signerPubkey, uint256 _commisionRate, address stakeManager, address polygonERC20 ) external returns (uint256, address); /// @notice Restake Matics for a validator on polygon stake manager. /// @param sender operator owner which approved tokens to the validato contract. /// @param validatorId validator id. /// @param amount amount to stake. /// @param stakeRewards restake rewards. /// @param stakeManager stake manager address /// @param polygonERC20 address of the MATIC token function restake( address sender, uint256 validatorId, uint256 amount, bool stakeRewards, address stakeManager, address polygonERC20 ) external; /// @notice Unstake a validator from the Polygon stakeManager contract. /// @dev Unstake a validator from the Polygon stakeManager contract by passing the validatorId /// @param _validatorId validatorId. /// @param _stakeManager address of the stake manager function unstake(uint256 _validatorId, address _stakeManager) external; /// @notice Allows to top up heimdall fees. /// @param _heimdallFee amount /// @param _sender msg.sender /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function topUpForFee( address _sender, uint256 _heimdallFee, address _stakeManager, address _polygonERC20 ) external; /// @notice Allows to withdraw rewards from the validator. /// @dev Allows to withdraw rewards from the validator using the _validatorId. Only the /// owner can request withdraw in this the owner is this contract. /// @param _validatorId validator id. /// @param _rewardAddress user address used to transfer the staked tokens. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token /// @return Returns the amount transfered to the user. function withdrawRewards( uint256 _validatorId, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external returns (uint256); /// @notice Allows to claim staked tokens on the stake Manager after the end of the /// withdraw delay /// @param _validatorId validator id. /// @param _rewardAddress user address used to transfer the staked tokens. /// @return Returns the amount transfered to the user. function unstakeClaim( uint256 _validatorId, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external returns (uint256); /// @notice Allows to update the signer pubkey /// @param _validatorId validator id /// @param _signerPubkey update signer public key /// @param _stakeManager stake manager address function updateSigner( uint256 _validatorId, bytes memory _signerPubkey, address _stakeManager ) external; /// @notice Allows to claim the heimdall fees. /// @param _accumFeeAmount accumulated fees amount /// @param _index index /// @param _proof proof /// @param _ownerRecipient owner recipient /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof, address _ownerRecipient, address _stakeManager, address _polygonERC20 ) external; /// @notice Allows to update the commision rate of a validator /// @param _validatorId operator id /// @param _newCommissionRate commission rate /// @param _stakeManager stake manager address function updateCommissionRate( uint256 _validatorId, uint256 _newCommissionRate, address _stakeManager ) external; /// @notice Allows to unjail a validator. /// @param _validatorId operator id function unjail(uint256 _validatorId, address _stakeManager) external; /// @notice Allows to migrate the ownership to an other user. /// @param _validatorId operator id. /// @param _stakeManagerNFT stake manager nft contract. /// @param _rewardAddress reward address. function migrate( uint256 _validatorId, address _stakeManagerNFT, address _rewardAddress ) external; /// @notice Allows a validator that was already staked on the polygon stake manager /// to join the PoLido protocol. /// @param _validatorId validator id /// @param _stakeManagerNFT address of the staking NFT /// @param _rewardAddress address that will receive the rewards from staking /// @param _newCommissionRate commission rate /// @param _stakeManager address of the stake manager function join( uint256 _validatorId, address _stakeManagerNFT, address _rewardAddress, uint256 _newCommissionRate, address _stakeManager ) external; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./IValidatorShare.sol"; import "./INodeOperatorRegistry.sol"; import "./INodeOperatorRegistry.sol"; import "./IStakeManager.sol"; import "./IPoLidoNFT.sol"; import "./IFxStateRootTunnel.sol"; /// @title StMATIC interface. /// @author 2021 ShardLabs interface IStMATIC is IERC20Upgradeable { struct RequestWithdraw { uint256 amount2WithdrawFromStMATIC; uint256 validatorNonce; uint256 requestEpoch; address validatorAddress; } struct FeeDistribution { uint8 dao; uint8 operators; uint8 insurance; } function withdrawTotalDelegated(address _validatorShare) external; function nodeOperatorRegistry() external returns (INodeOperatorRegistry); function entityFees() external returns ( uint8, uint8, uint8 ); function getMaticFromTokenId(uint256 _tokenId) external view returns (uint256); function stakeManager() external view returns (IStakeManager); function poLidoNFT() external view returns (IPoLidoNFT); function fxStateRootTunnel() external view returns (IFxStateRootTunnel); function version() external view returns (string memory); function dao() external view returns (address); function insurance() external view returns (address); function token() external view returns (address); function lastWithdrawnValidatorId() external view returns (uint256); function totalBuffered() external view returns (uint256); function delegationLowerBound() external view returns (uint256); function rewardDistributionLowerBound() external view returns (uint256); function reservedFunds() external view returns (uint256); function submitThreshold() external view returns (uint256); function submitHandler() external view returns (bool); function getMinValidatorBalance() external view returns (uint256); function token2WithdrawRequest(uint256 _requestId) external view returns ( uint256, uint256, uint256, address ); function DAO() external view returns (bytes32); function initialize( address _nodeOperatorRegistry, address _token, address _dao, address _insurance, address _stakeManager, address _poLidoNFT, address _fxStateRootTunnel, uint256 _submitThreshold ) external; function submit(uint256 _amount) external returns (uint256); function requestWithdraw(uint256 _amount) external; function delegate() external; function claimTokens(uint256 _tokenId) external; function distributeRewards() external; function claimTokens2StMatic(uint256 _tokenId) external; function togglePause() external; function getTotalStake(IValidatorShare _validatorShare) external view returns (uint256, uint256); function getLiquidRewards(IValidatorShare _validatorShare) external view returns (uint256); function getTotalStakeAcrossAllValidators() external view returns (uint256); function getTotalPooledMatic() external view returns (uint256); function convertStMaticToMatic(uint256 _balance) external view returns ( uint256, uint256, uint256 ); function convertMaticToStMatic(uint256 _balance) external view returns ( uint256, uint256, uint256 ); function setFees( uint8 _daoFee, uint8 _operatorsFee, uint8 _insuranceFee ) external; function setDaoAddress(address _address) external; function setInsuranceAddress(address _address) external; function setNodeOperatorRegistryAddress(address _address) external; function setDelegationLowerBound(uint256 _delegationLowerBound) external; function setRewardDistributionLowerBound( uint256 _rewardDistributionLowerBound ) external; function setPoLidoNFT(address _poLidoNFT) external; function setFxStateRootTunnel(address _fxStateRootTunnel) external; function setSubmitThreshold(uint256 _submitThreshold) external; function flipSubmitHandler() external; function setVersion(string calldata _version) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.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 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. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @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"); (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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; library Operator { struct OperatorInfo { uint256 operatorId; address validatorShare; uint256 maxDelegateLimit; address rewardAddress; } } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "./interfaces/IStakeManager.sol"; import "./interfaces/IValidator.sol"; import "./interfaces/INodeOperatorRegistry.sol"; /// @title ValidatorImplementation /// @author 2021 ShardLabs. /// @notice The validator contract is a simple implementation of the stakeManager API, the /// ValidatorProxies use this contract to interact with the stakeManager. /// When a ValidatorProxy calls this implementation the state is copied /// (owner, implementation, operatorRegistry), then they are used to check if the msg-sender is the /// node operator contract, and if the validatorProxy implementation match with the current /// validator contract. contract Validator is IERC721Receiver, IValidator { using SafeERC20 for IERC20; address private implementation; address private operatorRegistry; address private validatorFactory; /// @notice Check if the operator contract is the msg.sender. modifier isOperatorRegistry() { require( msg.sender == operatorRegistry, "Caller should be the operator contract" ); _; } /// @notice Allows to stake on the Polygon stakeManager contract by /// calling stakeFor function and set the user as the equal to this validator proxy /// address. /// @param _sender the address of the operator-owner that approved Matics. /// @param _amount the amount to stake with. /// @param _heimdallFee the heimdall fees. /// @param _acceptDelegation accept delegation. /// @param _signerPubkey signer public key used on the heimdall node. /// @param _commissionRate validator commision rate /// @return Returns the validatorId and the validatorShare contract address. function stake( address _sender, uint256 _amount, uint256 _heimdallFee, bool _acceptDelegation, bytes memory _signerPubkey, uint256 _commissionRate, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry returns (uint256, address) { IStakeManager stakeManager = IStakeManager(_stakeManager); IERC20 polygonERC20 = IERC20(_polygonERC20); uint256 totalAmount = _amount + _heimdallFee; polygonERC20.safeTransferFrom(_sender, address(this), totalAmount); polygonERC20.safeApprove(address(stakeManager), totalAmount); stakeManager.stakeFor( address(this), _amount, _heimdallFee, _acceptDelegation, _signerPubkey ); uint256 validatorId = stakeManager.getValidatorId(address(this)); address validatorShare = stakeManager.getValidatorContract(validatorId); if (_commissionRate > 0) { stakeManager.updateCommissionRate(validatorId, _commissionRate); } return (validatorId, validatorShare); } /// @notice Restake validator rewards or new Matics validator on stake manager. /// @param _sender operator's owner that approved tokens to the validator contract. /// @param _validatorId validator id. /// @param _amount amount to stake. /// @param _stakeRewards restake rewards. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function restake( address _sender, uint256 _validatorId, uint256 _amount, bool _stakeRewards, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry { if (_amount > 0) { IERC20 polygonERC20 = IERC20(_polygonERC20); polygonERC20.safeTransferFrom(_sender, address(this), _amount); polygonERC20.safeApprove(address(_stakeManager), _amount); } IStakeManager(_stakeManager).restake(_validatorId, _amount, _stakeRewards); } /// @notice Unstake a validator from the Polygon stakeManager contract. /// @param _validatorId validatorId. /// @param _stakeManager address of the stake manager function unstake(uint256 _validatorId, address _stakeManager) external override isOperatorRegistry { // stakeManager IStakeManager(_stakeManager).unstake(_validatorId); } /// @notice Allows a validator to top-up the heimdall fees. /// @param _sender address that approved the _heimdallFee amount. /// @param _heimdallFee amount. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function topUpForFee( address _sender, uint256 _heimdallFee, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry { IStakeManager stakeManager = IStakeManager(_stakeManager); IERC20 polygonERC20 = IERC20(_polygonERC20); polygonERC20.safeTransferFrom(_sender, address(this), _heimdallFee); polygonERC20.safeApprove(address(stakeManager), _heimdallFee); stakeManager.topUpForFee(address(this), _heimdallFee); } /// @notice Allows to withdraw rewards from the validator using the _validatorId. Only the /// owner can request withdraw. The rewards are transfered to the _rewardAddress. /// @param _validatorId validator id. /// @param _rewardAddress reward address. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function withdrawRewards( uint256 _validatorId, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry returns (uint256) { IStakeManager(_stakeManager).withdrawRewards(_validatorId); IERC20 polygonERC20 = IERC20(_polygonERC20); uint256 balance = polygonERC20.balanceOf(address(this)); polygonERC20.safeTransfer(_rewardAddress, balance); return balance; } /// @notice Allows to unstake the staked tokens (+rewards) and transfer them /// to the owner rewardAddress. /// @param _validatorId validator id. /// @param _rewardAddress rewardAddress address. /// @param _stakeManager stake manager address /// @param _polygonERC20 address of the MATIC token function unstakeClaim( uint256 _validatorId, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry returns (uint256) { IStakeManager stakeManager = IStakeManager(_stakeManager); stakeManager.unstakeClaim(_validatorId); // polygonERC20 // stakeManager IERC20 polygonERC20 = IERC20(_polygonERC20); uint256 balance = polygonERC20.balanceOf(address(this)); polygonERC20.safeTransfer(_rewardAddress, balance); return balance; } /// @notice Allows to update signer publickey. /// @param _validatorId validator id. /// @param _signerPubkey new publickey. /// @param _stakeManager stake manager address function updateSigner( uint256 _validatorId, bytes memory _signerPubkey, address _stakeManager ) external override isOperatorRegistry { IStakeManager(_stakeManager).updateSigner(_validatorId, _signerPubkey); } /// @notice Allows withdraw heimdall fees. /// @param _accumFeeAmount accumulated heimdall fees. /// @param _index index. /// @param _proof proof. function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof, address _rewardAddress, address _stakeManager, address _polygonERC20 ) external override isOperatorRegistry { IStakeManager stakeManager = IStakeManager(_stakeManager); stakeManager.claimFee(_accumFeeAmount, _index, _proof); IERC20 polygonERC20 = IERC20(_polygonERC20); uint256 balance = polygonERC20.balanceOf(address(this)); polygonERC20.safeTransfer(_rewardAddress, balance); } /// @notice Allows to update commission rate of a validator. /// @param _validatorId validator id. /// @param _newCommissionRate new commission rate. /// @param _stakeManager stake manager address function updateCommissionRate( uint256 _validatorId, uint256 _newCommissionRate, address _stakeManager ) public override isOperatorRegistry { IStakeManager(_stakeManager).updateCommissionRate( _validatorId, _newCommissionRate ); } /// @notice Allows to unjail a validator. /// @param _validatorId validator id function unjail(uint256 _validatorId, address _stakeManager) external override isOperatorRegistry { IStakeManager(_stakeManager).unjail(_validatorId); } /// @notice Allows to transfer the validator nft token to the reward address a validator. /// @param _validatorId operator id. /// @param _stakeManagerNFT stake manager nft contract. /// @param _rewardAddress reward address. function migrate( uint256 _validatorId, address _stakeManagerNFT, address _rewardAddress ) external override isOperatorRegistry { IERC721 erc721 = IERC721(_stakeManagerNFT); erc721.approve(_rewardAddress, _validatorId); erc721.safeTransferFrom(address(this), _rewardAddress, _validatorId); } /// @notice Allows a validator that was already staked on the polygon stake manager /// to join the PoLido protocol. /// @param _validatorId validator id /// @param _stakeManagerNFT address of the staking NFT /// @param _rewardAddress address that will receive the rewards from staking /// @param _newCommissionRate commission rate /// @param _stakeManager address of the stake manager function join( uint256 _validatorId, address _stakeManagerNFT, address _rewardAddress, uint256 _newCommissionRate, address _stakeManager ) external override isOperatorRegistry { IERC721 erc721 = IERC721(_stakeManagerNFT); erc721.safeTransferFrom(_rewardAddress, address(this), _validatorId); updateCommissionRate(_validatorId, _newCommissionRate, _stakeManager); } /// @notice Allows to get the version of the validator implementation. /// @return Returns the version. function version() external pure returns (string memory) { return "1.0.0"; } /// @notice Implement @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol interface. function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { return bytes4( keccak256("onERC721Received(address,address,uint256,bytes)") ); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 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 SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 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 * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 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' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _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(IERC20 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, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; /// @title polygon stake manager interface. /// @author 2021 ShardLabs /// @notice User to interact with the polygon stake manager. interface IStakeManager { /// @notice Stake a validator on polygon stake manager. /// @param user user that own the validator in our case the validator contract. /// @param amount amount to stake. /// @param heimdallFee heimdall fees. /// @param acceptDelegation accept delegation. /// @param signerPubkey signer publickey used in heimdall node. function stakeFor( address user, uint256 amount, uint256 heimdallFee, bool acceptDelegation, bytes memory signerPubkey ) external; /// @notice Restake Matics for a validator on polygon stake manager. /// @param validatorId validator id. /// @param amount amount to stake. /// @param stakeRewards restake rewards. function restake( uint256 validatorId, uint256 amount, bool stakeRewards ) external; /// @notice Request unstake a validator. /// @param validatorId validator id. function unstake(uint256 validatorId) external; /// @notice Increase the heimdall fees. /// @param user user that own the validator in our case the validator contract. /// @param heimdallFee heimdall fees. function topUpForFee(address user, uint256 heimdallFee) external; /// @notice Get the validator id using the user address. /// @param user user that own the validator in our case the validator contract. /// @return return the validator id function getValidatorId(address user) external view returns (uint256); /// @notice get the validator contract used for delegation. /// @param validatorId validator id. /// @return return the address of the validator contract. function getValidatorContract(uint256 validatorId) external view returns (address); /// @notice Withdraw accumulated rewards /// @param validatorId validator id. function withdrawRewards(uint256 validatorId) external; /// @notice Get validator total staked. /// @param validatorId validator id. function validatorStake(uint256 validatorId) external view returns (uint256); /// @notice Allows to unstake the staked tokens on the stakeManager. /// @param validatorId validator id. function unstakeClaim(uint256 validatorId) external; /// @notice Allows to update the signer pubkey /// @param _validatorId validator id /// @param _signerPubkey update signer public key function updateSigner(uint256 _validatorId, bytes memory _signerPubkey) external; /// @notice Allows to claim the heimdall fees. /// @param _accumFeeAmount accumulated fees amount /// @param _index index /// @param _proof proof function claimFee( uint256 _accumFeeAmount, uint256 _index, bytes memory _proof ) external; /// @notice Allows to update the commision rate of a validator /// @param _validatorId operator id /// @param _newCommissionRate commission rate function updateCommissionRate( uint256 _validatorId, uint256 _newCommissionRate ) external; /// @notice Allows to unjail a validator. /// @param _validatorId id of the validator that is to be unjailed function unjail(uint256 _validatorId) external; /// @notice Returns a withdrawal delay. function withdrawalDelay() external view returns (uint256); /// @notice Transfers amount from delegator function delegationDeposit( uint256 validatorId, uint256 amount, address delegator ) external returns (bool); function epoch() external view returns (uint256); enum Status { Inactive, Active, Locked, Unstaked } struct Validator { uint256 amount; uint256 reward; uint256 activationEpoch; uint256 deactivationEpoch; uint256 jailTime; address signer; address contractAddress; Status status; uint256 commissionRate; uint256 lastCommissionUpdate; uint256 delegatorsReward; uint256 delegatedAmount; uint256 initialRewardPerStake; } function validators(uint256 _index) external view returns (Validator memory); /// @notice Returns the address of the nft contract function NFTContract() external view returns (address); /// @notice Returns the validator accumulated rewards on stake manager. function validatorReward(uint256 validatorId) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @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"); (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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { 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 assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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); } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; interface IValidatorShare { struct DelegatorUnbond { uint256 shares; uint256 withdrawEpoch; } function unbondNonces(address _address) external view returns (uint256); function activeAmount() external view returns (uint256); function validatorId() external view returns (uint256); function withdrawExchangeRate() external view returns (uint256); function withdrawRewards() external; function unstakeClaimTokens() external; function minAmount() external view returns (uint256); function getLiquidRewards(address user) external view returns (uint256); function delegation() external view returns (bool); function updateDelegation(bool _delegation) external; function buyVoucher(uint256 _amount, uint256 _minSharesToMint) external returns (uint256); function sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn) external; function unstakeClaimTokens_new(uint256 unbondNonce) external; function unbonds_new(address _address, uint256 _unbondNonce) external view returns (DelegatorUnbond memory); function getTotalStake(address user) external view returns (uint256, uint256); function owner() external view returns (address); function restake() external returns (uint256, uint256); function unlock() external; function lock() external; function drain( address token, address payable destination, uint256 amount ) external; function slash(uint256 _amount) external; function migrateOut(address user, uint256 amount) external; function migrateIn(address user, uint256 amount) external; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; /// @title PoLidoNFT interface. /// @author 2021 ShardLabs interface IPoLidoNFT is IERC721Upgradeable { function mint(address _to) external returns (uint256); function burn(uint256 _tokenId) external; function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool); function setStMATIC(address _stMATIC) external; } // SPDX-FileCopyrightText: 2021 ShardLabs // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; interface IFxStateRootTunnel { function latestData() external view returns (bytes memory); function setFxChildTunnel(address _fxChildTunnel) external; function sendMessageToChild(bytes memory message) external; function setStMATIC(address _stMATIC) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
@notice TopUp heimadall fees. @param operatorId node operator id. @param amount amount.
event TopUpHeimdallFees(uint256 operatorId, uint256 amount);
6,084,936
[ 1, 3401, 1211, 3904, 381, 361, 454, 1656, 281, 18, 225, 3726, 548, 756, 3726, 612, 18, 225, 3844, 3844, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 7202, 1211, 5256, 381, 72, 454, 2954, 281, 12, 11890, 5034, 3726, 548, 16, 2254, 5034, 3844, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interfaces/Types.sol"; import "../interfaces/ILedger.sol"; import "../interfaces/IOracleMaster.sol"; import "./utils/ReportUtils.sol"; contract Oracle { using ReportUtils for uint256; event Completed(uint256); // is already pushed flag bool public isPushed; // Current era report hashes uint256[] internal currentReportVariants; // Current era reports Types.OracleData[] private currentReports; // Then oracle member push report, its bit is set uint256 internal currentReportBitmask; // oracle master contract address address public ORACLE_MASTER; // linked ledger contract address address public LEDGER; // Allows function calls only from OracleMaster modifier onlyOracleMaster() { require(msg.sender == ORACLE_MASTER); _; } /** * @notice Initialize oracle contract * @param _oracleMaster oracle master address * @param _ledger linked ledger address */ function initialize(address _oracleMaster, address _ledger) external { require(ORACLE_MASTER == address(0), "ORACLE: ALREADY_INITIALIZED"); ORACLE_MASTER = _oracleMaster; LEDGER = _ledger; } /** * @notice Returns true if member is already reported * @param _index oracle member index * @return is reported indicator */ function isReported(uint256 _index) external view returns (bool) { return (currentReportBitmask & (1 << _index)) != 0; } /** * @notice Accept oracle report data, allowed to call only by oracle master contract * @param _index oracle member index * @param _quorum the minimum number of voted oracle members to accept a variant * @param _eraId current era id * @param _staking report data */ function reportRelay(uint256 _index, uint256 _quorum, uint64 _eraId, Types.OracleData calldata _staking) external onlyOracleMaster { { uint256 mask = 1 << _index; uint256 reportBitmask = currentReportBitmask; require(reportBitmask & mask == 0, "ORACLE: ALREADY_SUBMITTED"); currentReportBitmask = (reportBitmask | mask); } // return instantly if already got quorum and pushed data if (isPushed) { return; } // convert staking report into 31 byte hash. The last byte is used for vote counting uint256 variant = uint256(keccak256(abi.encode(_staking))) & ReportUtils.COUNT_OUTMASK; uint256 i = 0; uint256 _length = currentReportVariants.length; // iterate on all report variants we already have, limited by the oracle members maximum while (i < _length && currentReportVariants[i].isDifferent(variant)) ++i; if (i < _length) { if (currentReportVariants[i].getCount() + 1 >= _quorum) { _push(_eraId, _staking); } else { ++currentReportVariants[i]; // increment variant counter, see ReportUtils for details } } else { if (_quorum == 1) { _push(_eraId, _staking); } else { currentReportVariants.push(variant + 1); currentReports.push(_staking); } } } /** * @notice Change quorum threshold, allowed to call only by oracle master contract * @dev Method can trigger to pushing data to ledger if quorum threshold decreased and now for contract already reached new threshold. * @param _quorum new quorum threshold * @param _eraId current era id */ function softenQuorum(uint8 _quorum, uint64 _eraId) external onlyOracleMaster { (bool isQuorum, uint256 reportIndex) = _getQuorumReport(_quorum); if (isQuorum) { Types.OracleData memory report = _getStakeReport(reportIndex); _push( _eraId, report ); } } /** * @notice Clear data about current reporting, allowed to call only by oracle master contract */ function clearReporting() external onlyOracleMaster { _clearReporting(); } /** * @notice Returns report by given index * @param _index oracle member index * @return staking report data */ function _getStakeReport(uint256 _index) internal view returns (Types.OracleData storage staking) { assert(_index < currentReports.length); return currentReports[_index]; } /** * @notice Clear data about current reporting */ function _clearReporting() internal { currentReportBitmask = 0; isPushed = false; delete currentReportVariants; delete currentReports; } /** * @notice Push data to ledger */ function _push(uint64 _eraId, Types.OracleData memory report) internal { ILedger(LEDGER).pushData(_eraId, report); isPushed = true; } /** * @notice Return whether the `_quorum` is reached and the final report can be pushed */ function _getQuorumReport(uint256 _quorum) internal view returns (bool, uint256) { // check most frequent cases first: all reports are the same or no reports yet uint256 _length = currentReportVariants.length; if (_length == 1) { return (currentReportVariants[0].getCount() >= _quorum, 0); } else if (_length == 0) { return (false, type(uint256).max); } // if more than 2 kind of reports exist, choose the most frequent uint256 maxind = 0; uint256 repeat = 0; uint16 maxval = 0; uint16 cur = 0; for (uint256 i = 0; i < _length; ++i) { cur = currentReportVariants[i].getCount(); if (cur >= maxval) { if (cur == maxval) { ++repeat; } else { maxind = i; maxval = cur; repeat = 0; } } } return (maxval >= _quorum && repeat == 0, maxind); } }
iterate on all report variants we already have, limited by the oracle members maximum
while (i < _length && currentReportVariants[i].isDifferent(variant)) ++i;
967,666
[ 1, 18793, 603, 777, 2605, 12935, 732, 1818, 1240, 16, 13594, 635, 326, 20865, 4833, 4207, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1323, 261, 77, 411, 389, 2469, 597, 783, 4820, 21165, 63, 77, 8009, 291, 26270, 12, 8688, 3719, 965, 77, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol'; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SM1Admin } from '../v1_1/impl/SM1Admin.sol'; import { SM1Getters } from '../v1_1/impl/SM1Getters.sol'; import { SM1Operators } from '../v1_1/impl/SM1Operators.sol'; import { SM1Slashing } from '../v1_1/impl/SM1Slashing.sol'; import { SM1Staking } from '../v1_1/impl/SM1Staking.sol'; /** * @title SafetyModuleV2 * @author dYdX * * @notice Contract for staking tokens, which may be slashed by the permissioned slasher. * * NOTE: Most functions will revert if epoch zero has not started. */ contract SafetyModuleV2 is SM1Slashing, SM1Operators, SM1Admin, SM1Getters { using SafeERC20 for IERC20; // ============ Constants ============ string public constant EIP712_DOMAIN_NAME = 'dYdX Safety Module'; string public constant EIP712_DOMAIN_VERSION = '1'; bytes32 public constant EIP712_DOMAIN_SCHEMA_HASH = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ /** * @notice Initializer for v2, intended to fix the deployment bug that affected v1. * * Responsible for the following: * * 1. Funds recovery and staker compensation: * - Transfer all Safety Module DYDX to the recovery contract. * - Transfer compensation amount from the rewards treasury to the recovery contract. * * 2. Storage recovery and cleanup: * - Set the _EXCHANGE_RATE_ to EXCHANGE_RATE_BASE. * - Clean up invalid storage values at slots 115 and 125. * * @param recoveryContract The address of the contract which will distribute * recovered funds to stakers. * @param recoveryCompensationAmount Amount to transfer out of the rewards treasury, for staker * compensation, on top of the return of staked funds. */ function initialize( address recoveryContract, uint256 recoveryCompensationAmount ) external initializer { // Funds recovery and staker compensation. uint256 balance = STAKED_TOKEN.balanceOf(address(this)); STAKED_TOKEN.safeTransfer(recoveryContract, balance); REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recoveryContract, recoveryCompensationAmount); // Storage recovery and cleanup. __SM1ExchangeRate_init(); // solhint-disable-next-line no-inline-assembly assembly { sstore(115, 0) sstore(125, 0) } } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 2; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * Wrappers around ERC20 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 SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @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); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Admin * @author dYdX * * @dev Admin-only functions. */ abstract contract SM1Admin is SM1StakedBalances, SM1Roles { using SafeMath for uint256; // ============ External Functions ============ /** * @notice Set the parameters defining the function from timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Reverts if epoch zero already started, and the new parameters would change the current epoch. * Reverts if epoch zero has not started, but would have had started under the new parameters. * * @param interval The length `a` of an epoch, in seconds. * @param offset The offset `b`, i.e. the start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { if (!hasEpochZeroStarted()) { require( block.timestamp < offset, 'SM1Admin: Started epoch zero' ); _setEpochParameters(interval, offset); return; } // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the epoch formula. _settleTotalActiveBalance(); // Update the epoch parameters. Require that the current epoch number is unchanged. uint256 originalCurrentEpoch = getCurrentEpoch(); _setEpochParameters(interval, offset); uint256 newCurrentEpoch = getCurrentEpoch(); require( originalCurrentEpoch == newCurrentEpoch, 'SM1Admin: Changed epochs' ); } /** * @notice Set the blackout window, during which one cannot request withdrawals of staked funds. */ function setBlackoutWindow( uint256 blackoutWindow ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { _setBlackoutWindow(blackoutWindow); } /** * @notice Set the emission rate of rewards. * * @param emissionPerSecond The new number of rewards tokens given out per second. */ function setRewardsPerSecond( uint256 emissionPerSecond ) external onlyRole(REWARDS_RATE_ROLE) nonReentrant { uint256 totalStaked = 0; if (hasEpochZeroStarted()) { // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the emission rate. totalStaked = _settleTotalActiveBalance(); } _setRewardsPerSecond(emissionPerSecond, totalStaked); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Getters * @author dYdX * * @dev Some external getter functions. */ abstract contract SM1Getters is SM1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice The parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (SM1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice The period of time at the end of each epoch in which withdrawals cannot be requested. * * @return The blackout window duration, in seconds. */ function getBlackoutWindow() external view returns (uint256) { return _BLACKOUT_WINDOW_; } /** * @notice Get the domain separator used for EIP-712 signatures. * * @return The EIP-712 domain separator. */ function getDomainSeparator() external view returns (bytes32) { return _DOMAIN_SEPARATOR_; } /** * @notice The value of one underlying token, in the units used for staked balances, denominated * as a mutiple of EXCHANGE_RATE_BASE for additional precision. * * To convert from an underlying amount to a staked amount, multiply by the exchange rate. * * @return The exchange rate. */ function getExchangeRate() external view returns (uint256) { return _EXCHANGE_RATE_; } /** * @notice Get an exchange rate snapshot. * * @param index The index number of the exchange rate snapshot. * * @return The snapshot struct with `blockNumber` and `value` fields. */ function getExchangeRateSnapshot( uint256 index ) external view returns (SM1Types.Snapshot memory) { return _EXCHANGE_RATE_SNAPSHOTS_[index]; } /** * @notice Get the number of exchange rate snapshots. * * @return The number of snapshots that have been taken of the exchange rate. */ function getExchangeRateSnapshotCount() external view returns (uint256) { return _EXCHANGE_RATE_SNAPSHOT_COUNT_; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Operators * @author dYdX * * @dev Actions which may be called by authorized operators, nominated by the contract owner. * * There are two types of operators. These should be smart contracts, which can be used to * provide additional functionality to users: * * STAKE_OPERATOR_ROLE: * * This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This * role could be used by a smart contract to provide a staking interface with additional * features, for example, optional lock-up periods that pay out additional rewards (from a * separate rewards pool). * * CLAIM_OPERATOR_ROLE: * * This operator is allowed to claim rewards on behalf of stakers. This role could be used by a * smart contract to provide an interface for claiming rewards from multiple incentive programs * at once. */ abstract contract SM1Operators is SM1Staking, SM1Roles { using SafeMath for uint256; // ============ Events ============ event OperatorStakedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrawalRequestedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrewStakeFor( address indexed staker, address recipient, uint256 amount, address operator ); event OperatorClaimedRewardsFor( address indexed staker, address recipient, uint256 claimedRewards, address operator ); // ============ External Functions ============ /** * @notice Request a withdrawal on behalf of a staker. * * Reverts if we are currently in the blackout window. * * @param staker The staker whose stake to request a withdrawal for. * @param stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawalFor( address staker, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _requestWithdrawal(staker, stakeAmount); emit OperatorWithdrawalRequestedFor(staker, stakeAmount, msg.sender); } /** * @notice Withdraw a staker's stake, and send to the specified recipient. * * @param staker The staker whose stake to withdraw. * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the staker's inactive balance. */ function withdrawStakeFor( address staker, address recipient, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _withdrawStake(staker, recipient, stakeAmount); emit OperatorWithdrewStakeFor(staker, recipient, stakeAmount, msg.sender); } /** * @notice Claim rewards on behalf of a staker, and send them to the specified recipient. * * @param staker The staker whose rewards to claim. * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address staker, address recipient ) external onlyRole(CLAIM_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally. emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender); return rewards; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Slashing * @author dYdX * * @dev Provides the slashing function for removing funds from the contract. * * SLASHING: * * All funds in the contract, active or inactive, are slashable. Slashes are recorded by updating * the exchange rate, and to simplify the technical implementation, we disallow full slashes. * To reduce the possibility of overflow in the exchange rate, we place an upper bound on the * fraction of funds that may be slashed in a single slash. * * Warning: Slashing is not possible if the slash would cause the exchange rate to overflow. * * REWARDS AND GOVERNANCE POWER ACCOUNTING: * * Since all slashes are accounted for by a global exchange rate, slashes do not require any * update to staked balances. The earning of rewards is unaffected by slashes. * * Governance power takes slashes into account by using snapshots of the exchange rate inside * the getPowerAtBlock() function. Note that getPowerAtBlock() returns the governance power as of * the end of the specified block. */ abstract contract SM1Slashing is SM1Staking, SM1Roles { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The maximum fraction of funds that may be slashed in a single slash (numerator). uint256 public constant MAX_SLASH_NUMERATOR = 95; /// @notice The maximum fraction of funds that may be slashed in a single slash (denominator). uint256 public constant MAX_SLASH_DENOMINATOR = 100; // ============ Events ============ event Slashed( uint256 amount, address recipient, uint256 newExchangeRate ); // ============ External Functions ============ /** * @notice Slash staked token balances and withdraw those funds to the specified address. * * @param requestedSlashAmount The request slash amount, denominated in the underlying token. * @param recipient The address to receive the slashed tokens. * * @return The amount slashed, denominated in the underlying token. */ function slash( uint256 requestedSlashAmount, address recipient ) external onlyRole(SLASHER_ROLE) nonReentrant returns (uint256) { uint256 underlyingBalance = STAKED_TOKEN.balanceOf(address(this)); if (underlyingBalance == 0) { return 0; } // Get the slash amount and remaining amount. Note that remainingAfterSlash is nonzero. uint256 maxSlashAmount = underlyingBalance.mul(MAX_SLASH_NUMERATOR).div(MAX_SLASH_DENOMINATOR); uint256 slashAmount = Math.min(requestedSlashAmount, maxSlashAmount); uint256 remainingAfterSlash = underlyingBalance.sub(slashAmount); if (slashAmount == 0) { return 0; } // Update the exchange rate. // // Warning: Can revert if the max exchange rate is exceeded. uint256 newExchangeRate = updateExchangeRate(underlyingBalance, remainingAfterSlash); // Transfer the slashed token. STAKED_TOKEN.safeTransfer(recipient, slashAmount); emit Slashed(slashAmount, recipient, newExchangeRate); return slashAmount; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ERC20 } from './SM1ERC20.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Staking * @author dYdX * * @dev External functions for stakers. See SM1StakedBalances for details on staker accounting. * * UNDERLYING AND STAKED AMOUNTS: * * We distinguish between underlying amounts and stake amounts. An underlying amount is denoted * in the original units of the token being staked. A stake amount is adjusted by the exchange * rate, which can increase due to slashing. Before any slashes have occurred, the exchange rate * is equal to one. */ abstract contract SM1Staking is SM1StakedBalances, SM1ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Staked( address indexed staker, address spender, uint256 underlyingAmount, uint256 stakeAmount ); event WithdrawalRequested( address indexed staker, uint256 stakeAmount ); event WithdrewStake( address indexed staker, address recipient, uint256 underlyingAmount, uint256 stakeAmount ); // ============ Constants ============ IERC20 public immutable STAKED_TOKEN; // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) { STAKED_TOKEN = stakedToken; } // ============ External Functions ============ /** * @notice Deposit and stake funds. These funds are active and start earning rewards immediately. * * @param underlyingAmount The amount of underlying token to stake. */ function stake( uint256 underlyingAmount ) external nonReentrant { _stake(msg.sender, underlyingAmount); } /** * @notice Deposit and stake on behalf of another address. * * @param staker The staker who will receive the stake. * @param underlyingAmount The amount of underlying token to stake. */ function stakeFor( address staker, uint256 underlyingAmount ) external nonReentrant { _stake(staker, underlyingAmount); } /** * @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive” * and available for withdrawal. Inactive funds do not earn rewards. * * Reverts if we are currently in the blackout window. * * @param stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawal( uint256 stakeAmount ) external nonReentrant { _requestWithdrawal(msg.sender, stakeAmount); } /** * @notice Withdraw the sender's inactive funds, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the sender's inactive balance. */ function withdrawStake( address recipient, uint256 stakeAmount ) external nonReentrant { _withdrawStake(msg.sender, recipient, stakeAmount); } /** * @notice Withdraw the max available inactive funds, and send to the specified recipient. * * This is less gas-efficient than querying the max via eth_call and calling withdrawStake(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxStake( address recipient ) external nonReentrant returns (uint256) { uint256 stakeAmount = getStakeAvailableToWithdraw(msg.sender); _withdrawStake(msg.sender, recipient, stakeAmount); return stakeAmount; } /** * @notice Settle and claim all rewards, and send them to the specified recipient. * * Call this function with eth_call to query the claimable rewards balance. * * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewards( address recipient ) external nonReentrant returns (uint256) { return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally. } // ============ Public Functions ============ /** * @notice Get the amount of stake available for a given staker to withdraw. * * @param staker The address whose balance to check. * * @return The staker's stake amount that is inactive and available to withdraw. */ function getStakeAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that the next epoch inactive balance is always at least that of the current epoch. return getInactiveBalanceCurrentEpoch(staker); } // ============ Internal Functions ============ function _stake( address staker, uint256 underlyingAmount ) internal { // Convert using the exchange rate. uint256 stakeAmount = stakeAmountFromUnderlyingAmount(underlyingAmount); // Update staked balances and delegate snapshots. _increaseCurrentAndNextActiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(address(0), staker, stakeAmount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), underlyingAmount); emit Staked(staker, msg.sender, underlyingAmount, stakeAmount); emit Transfer(address(0), msg.sender, stakeAmount); } function _requestWithdrawal( address staker, uint256 stakeAmount ) internal { require( !inBlackoutWindow(), 'SM1Staking: Withdraw requests restricted in the blackout window' ); // Get the staker's requestable amount and revert if there is not enough to request withdrawal. uint256 requestableBalance = getActiveBalanceNextEpoch(staker); require( stakeAmount <= requestableBalance, 'SM1Staking: Withdraw request exceeds next active balance' ); // Move amount from active to inactive in the next epoch. _moveNextBalanceActiveToInactive(staker, stakeAmount); emit WithdrawalRequested(staker, stakeAmount); } function _withdrawStake( address staker, address recipient, uint256 stakeAmount ) internal { // Get staker withdrawable balance and revert if there is not enough to withdraw. uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker); require( stakeAmount <= withdrawableBalance, 'SM1Staking: Withdraw amount exceeds staker inactive balance' ); // Update staked balances and delegate snapshots. _decreaseCurrentAndNextInactiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(staker, address(0), stakeAmount); // Convert using the exchange rate. uint256 underlyingAmount = underlyingAmountFromStakeAmount(stakeAmount); // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, underlyingAmount); emit Transfer(msg.sender, address(0), stakeAmount); emit WithdrewStake(staker, recipient, underlyingAmount, stakeAmount); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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) { // Solidity only automatically asserts when dividing by 0 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; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @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'); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; library SM1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev Snapshot of a value at a specific block, used to track historical governance power. */ struct Snapshot { uint256 blockNumber; uint256 value; } /** * @dev A balance, possibly with a change scheduled for the next epoch. * * @param currentEpoch The epoch in which the balance was last updated. * @param currentEpochBalance The balance at epoch `currentEpoch`. * @param nextEpochBalance The balance at epoch `currentEpoch + 1`. */ struct StoredBalance { uint16 currentEpoch; uint240 currentEpochBalance; uint240 nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Roles * @author dYdX * * @dev Defines roles used in the SafetyModuleV1 contract. The hierarchy of roles and powers * of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove addresses from any of the roles below. * | * +-- SLASHER_ROLE * | -> Can slash staked token balances and withdraw those funds. * | * +-- EPOCH_PARAMETERS_ROLE * | -> May set epoch parameters such as the interval, offset, and blackout window. * | * +-- REWARDS_RATE_ROLE * | -> May set the emission rate of rewards. * | * +-- CLAIM_OPERATOR_ROLE * | -> May claim rewards on behalf of a user. * | * +-- STAKE_OPERATOR_ROLE * -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user). */ abstract contract SM1Roles is SM1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant SLASHER_ROLE = keccak256('SLASHER_ROLE'); bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE'); bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE'); function __SM1Roles_init() internal { // Assign roles to the sender. // // The STAKE_OPERATOR_ROLE and CLAIM_OPERATOR_ROLE roles are not initially assigned. // These can be assigned to other smart contracts to provide additional functionality for users. _setupRole(OWNER_ROLE, msg.sender); _setupRole(SLASHER_ROLE, msg.sender); _setupRole(EPOCH_PARAMETERS_ROLE, msg.sender); _setupRole(REWARDS_RATE_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(SLASHER_ROLE, OWNER_ROLE); _setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE); _setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Rewards } from './SM1Rewards.sol'; /** * @title SM1StakedBalances * @author dYdX * * @dev Accounting of staked balances. * * NOTE: Functions may revert if epoch zero has not started. * * NOTE: All amounts dealt with in this file are denominated in staked units, which because of the * exchange rate, may not correspond one-to-one with the underlying token. See SM1Staking.sol. * * STAKED BALANCE ACCOUNTING: * * A staked balance is in one of two states: * - active: Earning staking rewards; cannot be withdrawn by staker; may be slashed. * - inactive: Not earning rewards; can be withdrawn by the staker; may be slashed. * * A staker may have a combination of active and inactive balances. The following operations * affect staked balances as follows: * - deposit: Increase active balance. * - request withdrawal: At the end of the current epoch, move some active funds to inactive. * - withdraw: Decrease inactive balance. * - transfer: Move some active funds to another staker. * * To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we * store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and * nextEpochBalance. * * REWARDS ACCOUNTING: * * Active funds earn rewards for the period of time that they remain active. This means, after * requesting a withdrawal of some funds, those funds will continue to earn rewards until the end * of the epoch. For example: * * epoch: n n + 1 n + 2 n + 3 * | | | | * +----------+----------+----------+-----... * ^ t_0: User makes a deposit. * ^ t_1: User requests a withdrawal of all funds. * ^ t_2: The funds change state from active to inactive. * * In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying * with the total staked balance in that period. If the user only request a withdrawal for a part * of their balance, then the remaining balance would continue earning rewards beyond t_2. * * User rewards must be settled via SM1Rewards any time a user's active balance changes. Special * attention is paid to the the epoch boundaries, where funds may have transitioned from active * to inactive. * * SETTLEMENT DETAILS: * * Internally, this module uses the following types of operations on stored balances: * - Load: Loads a balance, while applying settlement logic internally to get the * up-to-date result. Returns settlement results without updating state. * - Store: Stores a balance. * - Load-for-update: Performs a load and applies updates as needed to rewards accounting. * Since this is state-changing, it must be followed by a store operation. * - Settle: Performs load-for-update and store operations. * * This module is responsible for maintaining the following invariants to ensure rewards are * calculated correctly: * - When an active balance is loaded for update, if a rollover occurs from one epoch to the * next, the rewards index must be settled up to the boundary at which the rollover occurs. * - Because the global rewards index is needed to update the user rewards index, the total * active balance must be settled before any staker balances are settled or loaded for update. * - A staker's balance must be settled before their rewards are settled. */ abstract contract SM1StakedBalances is SM1Rewards { using SafeCast for uint256; using SafeMath for uint256; // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ Public Functions ============ /** * @notice Get the current active balance of a staker. */ function getActiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _ACTIVE_BALANCES_[staker] ); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch active balance of a staker. */ function getActiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _ACTIVE_BALANCES_[staker] ); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total active balance. */ function getTotalActiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _TOTAL_ACTIVE_BALANCE_ ); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total active balance. */ function getTotalActiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _TOTAL_ACTIVE_BALANCE_ ); return uint256(balance.nextEpochBalance); } /** * @notice Get the current inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total inactive balance. */ function getTotalInactiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total inactive balance. */ function getTotalInactiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get the current transferable balance for a user. The user can * only transfer their balance that is not currently inactive or going to be * inactive in the next epoch. Note that this means the user's transferable funds * are their active balance of the next epoch. * * @param account The account to get the transferable balance of. * * @return The user's transferable balance. */ function getTransferableBalance( address account ) public view returns (uint256) { return getActiveBalanceNextEpoch(account); } // ============ Internal Functions ============ function _increaseCurrentAndNextActiveBalance( address staker, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount); uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance); } function _moveNextBalanceActiveToInactive( address staker, uint256 amount ) internal { // Decrease the active balance for the next epoch. // Always settle total active balance before settling a staker active balance. _decreaseNextBalance(address(0), true, amount); _decreaseNextBalance(staker, true, amount); // Increase the inactive balance for the next epoch. _increaseNextBalance(address(0), false, amount); _increaseNextBalance(staker, false, amount); // Note that we don't need to settle rewards since the current active balance did not change. } function _transferCurrentAndNextActiveBalance( address sender, address recipient, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Move current and next active balances from sender to recipient. uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount); uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance); _settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance); } function _decreaseCurrentAndNextInactiveBalance( address staker, uint256 amount ) internal { // Decrease the inactive balance for the next epoch. _decreaseCurrentAndNextBalances(address(0), false, amount); _decreaseCurrentAndNextBalances(staker, false, amount); // Note that we don't settle rewards since active balances are not affected. } function _settleTotalActiveBalance() internal returns (uint256) { return _settleBalance(address(0), true); } function _settleAndClaimRewards( address staker, address recipient ) internal returns (uint256) { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Always settle staker active balance before settling staker rewards. uint256 userBalance = _settleBalance(staker, true); // Settle rewards balance since we want to claim the full accrued amount. _settleUserRewardsUpToNow(staker, userBalance, totalBalance); // Claim rewards balance. return _claimRewards(staker, recipient); } // ============ Private Functions ============ /** * @dev Load a balance for update and then store it. */ function _settleBalance( address maybeStaker, bool isActiveBalance ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 currentBalance = uint256(balance.currentEpochBalance); _storeBalance(balancePtr, balance); return currentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying a decrease. */ function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); } /** * @dev Settle a balance while applying a decrease. */ function _decreaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); } function _getBalancePtr( address maybeStaker, bool isActiveBalance ) private view returns (SM1Types.StoredBalance storage) { // Active. if (isActiveBalance) { if (maybeStaker != address(0)) { return _ACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_ACTIVE_BALANCE_; } // Inactive. if (maybeStaker != address(0)) { return _INACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_INACTIVE_BALANCE_; } /** * @dev Load a balance for updating. * * IMPORTANT: This function may modify state, and so the balance MUST be stored afterwards. * - For active balances: * - If a rollover occurs, rewards are settled up to the epoch boundary. * * @param balancePtr A storage pointer to the balance. * @param maybeStaker The user address, or address(0) to update total balance. * @param isActiveBalance Whether the balance is an active balance. */ function _loadBalanceForUpdate( SM1Types.StoredBalance storage balancePtr, address maybeStaker, bool isActiveBalance ) private returns (SM1Types.StoredBalance memory) { // Active balance. if (isActiveBalance) { ( SM1Types.StoredBalance memory balance, uint256 beforeRolloverEpoch, uint256 beforeRolloverBalance, bool didRolloverOccur ) = _loadActiveBalance(balancePtr); if (didRolloverOccur) { // Handle the effect of the balance rollover on rewards. We must partially settle the index // up to the epoch boundary where the change in balance occurred. We pass in the balance // from before the boundary. if (maybeStaker == address(0)) { // If it's the total active balance... _settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch); } else { // If it's a user active balance... _settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch); } } return balance; } // Inactive balance. return _loadInactiveBalance(balancePtr); } function _loadActiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns ( SM1Types.StoredBalance memory, uint256, uint256, bool ) { SM1Types.StoredBalance memory balance = balancePtr; // Return these as they may be needed for rewards settlement. uint256 beforeRolloverEpoch = uint256(balance.currentEpoch); uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance); bool didRolloverOccur = false; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance; balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur); } function _loadInactiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns (SM1Types.StoredBalance memory) { SM1Types.StoredBalance memory balance = balancePtr; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return balance; } /** * @dev Store a balance. */ function _storeBalance( SM1Types.StoredBalance storage balancePtr, SM1Types.StoredBalance memory balance ) private { // Note: This should use a single `sstore` when compiler optimizations are enabled. balancePtr.currentEpoch = balance.currentEpoch; balancePtr.currentEpochBalance = balance.currentEpochBalance; balancePtr.nextEpochBalance = balance.nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { SM1Types } from '../lib/SM1Types.sol'; /** * @title SM1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract SM1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. SM1Types.EpochParameters internal _EPOCH_PARAMETERS_; /// @dev The period of time at the end of each epoch in which withdrawals cannot be requested. uint256 internal _BLACKOUT_WINDOW_; // ============ Staked Token ERC20 ============ /// @dev Allowances for ERC-20 transfers. mapping(address => mapping(address => uint256)) internal _ALLOWANCES_; // ============ Governance Power Delegation ============ /// @dev Domain separator for EIP-712 signatures. bytes32 internal _DOMAIN_SEPARATOR_; /// @dev Mapping from (owner) => (next valid nonce) for EIP-712 signatures. mapping(address => uint256) internal _NONCES_; /// @dev Snapshots and delegates for governance voting power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _VOTING_SNAPSHOTS_; mapping(address => uint256) internal _VOTING_SNAPSHOT_COUNTS_; mapping(address => address) internal _VOTING_DELEGATES_; /// @dev Snapshots and delegates for governance proposition power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _PROPOSITION_SNAPSHOTS_; mapping(address => uint256) internal _PROPOSITION_SNAPSHOT_COUNTS_; mapping(address => address) internal _PROPOSITION_DELEGATES_; // ============ Rewards Accounting ============ /// @dev The emission rate of rewards. uint256 internal _REWARDS_PER_SECOND_; /// @dev The cumulative rewards earned per staked token. (Shared storage slot.) uint224 internal _GLOBAL_INDEX_; /// @dev The timestamp at which the global index was last updated. (Shared storage slot.) uint32 internal _GLOBAL_INDEX_TIMESTAMP_; /// @dev The value of the global index when the user's staked balance was last updated. mapping(address => uint256) internal _USER_INDEXES_; /// @dev The user's accrued, unclaimed rewards (as of the last update to the user index). mapping(address => uint256) internal _USER_REWARDS_BALANCES_; /// @dev The value of the global index at the end of a given epoch. mapping(uint256 => uint256) internal _EPOCH_INDEXES_; // ============ Staker Accounting ============ /// @dev The active balance by staker. mapping(address => SM1Types.StoredBalance) internal _ACTIVE_BALANCES_; /// @dev The total active balance of stakers. SM1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_; /// @dev The inactive balance by staker. mapping(address => SM1Types.StoredBalance) internal _INACTIVE_BALANCES_; /// @dev The total inactive balance of stakers. SM1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_; // ============ Exchange Rate ============ /// @dev The value of one underlying token, in the units used for staked balances, denominated /// as a mutiple of EXCHANGE_RATE_BASE for additional precision. uint256 internal _EXCHANGE_RATE_; /// @dev Historical snapshots of the exchange rate, in each block that it has changed. mapping(uint256 => SM1Types.Snapshot) internal _EXCHANGE_RATE_SNAPSHOTS_; /// @dev Number of snapshots of the exchange rate. uint256 internal _EXCHANGE_RATE_SNAPSHOT_COUNT_; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', Strings.toHexString(uint160(account), 20), ' is missing role ', Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), 'AccessControl: can only renounce roles for self'); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @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. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = '0123456789abcdef'; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './IERC165.sol'; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint16, reverting on overflow. */ function toUint16( uint256 a ) internal pure returns (uint16) { uint16 b = uint16(a); require( uint256(b) == a, 'SafeCast: toUint16 overflow' ); return b; } /** * @dev Downcast to a uint32, reverting on overflow. */ function toUint32( uint256 a ) internal pure returns (uint32) { uint32 b = uint32(a); require( uint256(b) == a, 'SafeCast: toUint32 overflow' ); return b; } /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128( uint256 a ) internal pure returns (uint128) { uint128 b = uint128(a); require( uint256(b) == a, 'SafeCast: toUint128 overflow' ); return b; } /** * @dev Downcast to a uint224, reverting on overflow. */ function toUint224( uint256 a ) internal pure returns (uint224) { uint224 b = uint224(a); require( uint256(b) == a, 'SafeCast: toUint224 overflow' ); return b; } /** * @dev Downcast to a uint240, reverting on overflow. */ function toUint240( uint256 a ) internal pure returns (uint240) { uint240 b = uint240(a); require( uint256(b) == a, 'SafeCast: toUint240 overflow' ); return b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1EpochSchedule } from './SM1EpochSchedule.sol'; /** * @title SM1Rewards * @author dYdX * * @dev Manages the distribution of token rewards. * * Rewards are distributed continuously. After each second, an account earns rewards `r` according * to the following formula: * * r = R * s / S * * Where: * - `R` is the rewards distributed globally each second, also called the “emission rate.” * - `s` is the account's staked balance in that second (technically, it is measured at the * end of the second) * - `S` is the sum total of all staked balances in that second (again, measured at the end of * the second) * * The parameter `R` can be configured by the contract owner. For every second that elapses, * exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that * while the total staked balance is zero, no tokens will accrue to anyone. * * The accounting works as follows: A global index is stored which represents the cumulative * number of rewards tokens earned per staked token since the start of the distribution. * The value of this index increases over time, and there are two factors affecting the rate of * increase: * 1) The emission rate (in the numerator) * 2) The total number of staked tokens (in the denominator) * * Whenever either factor changes, in some timestamp T, we settle the global index up to T by * calculating the increase in the index since the last update using the OLD values of the factors: * * indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked * * Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index. * * For each user we store an accrued rewards balance, as well as a user index, which is a cache of * the global index at the time that the user's accrued rewards balance was last updated. Then at * any point in time, a user's claimable rewards are represented by the following: * * rewards = _USER_REWARDS_BALANCES_[user] + userStaked * ( * settledGlobalIndex - _USER_INDEXES_[user] * ) / INDEX_BASE */ abstract contract SM1Rewards is SM1EpochSchedule { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @dev Additional precision used to represent the global and user index values. uint256 private constant INDEX_BASE = 10**18; /// @notice The rewards token. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; /// @notice Start timestamp (inclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_START; /// @notice End timestamp (exclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_END; // ============ Events ============ event RewardsPerSecondUpdated( uint256 emissionPerSecond ); event GlobalIndexUpdated( uint256 index ); event UserIndexUpdated( address indexed user, uint256 index, uint256 unclaimedRewards ); event ClaimedRewards( address indexed user, address recipient, uint256 claimedRewards ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) { require( distributionEnd >= distributionStart, 'SM1Rewards: Invalid parameters' ); REWARDS_TOKEN = rewardsToken; REWARDS_TREASURY = rewardsTreasury; DISTRIBUTION_START = distributionStart; DISTRIBUTION_END = distributionEnd; } // ============ External Functions ============ /** * @notice The current emission rate of rewards. * * @return The number of rewards tokens issued globally each second. */ function getRewardsPerSecond() external view returns (uint256) { return _REWARDS_PER_SECOND_; } // ============ Internal Functions ============ /** * @dev Initialize the contract. */ function __SM1Rewards_init() internal { _GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32(); } /** * @dev Set the emission rate of rewards. * * IMPORTANT: Do not call this function without settling the total staked balance first, to * ensure that the index is settled up to the epoch boundaries. * * @param emissionPerSecond The new number of rewards tokens to give out each second. * @param totalStaked The total staked balance. */ function _setRewardsPerSecond( uint256 emissionPerSecond, uint256 totalStaked ) internal { _settleGlobalIndexUpToNow(totalStaked); _REWARDS_PER_SECOND_ = emissionPerSecond; emit RewardsPerSecondUpdated(emissionPerSecond); } /** * @dev Claim tokens, sending them to the specified recipient. * * Note: In order to claim all accrued rewards, the total and user staked balances must first be * settled before calling this function. * * @param user The user's address. * @param recipient The address to send rewards to. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, address recipient ) internal returns (uint256) { uint256 accruedRewards = _USER_REWARDS_BALANCES_[user]; _USER_REWARDS_BALANCES_[user] = 0; REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards); emit ClaimedRewards(user, recipient, accruedRewards); return accruedRewards; } /** * @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a * settlement of the global index up to `block.timestamp`. Should be called with the OLD user * and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param totalStaked Total tokens staked by all users during the period since the last global * index update. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToNow( address user, uint256 userStaked, uint256 totalStaked ) internal returns (uint256) { uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked); return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a * user's rewards if their balance was known to have changed on that epoch boundary. * * @param user The user's address. * @param userStaked Tokens staked by the user. Should be accurate for the time period * since the last update to this user and up to the end of the * specified epoch. * @param epochNumber Settle the user's rewards up to the end of this epoch. * * @return The user's accrued rewards, including past unclaimed rewards, up to the end of the * specified epoch. */ function _settleUserRewardsUpToEpoch( address user, uint256 userStaked, uint256 epochNumber ) internal returns (uint256) { uint256 globalIndex = _EPOCH_INDEXES_[epochNumber]; return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle the global index up to the end of the given epoch. * * IMPORTANT: This function should only be called under conditions which ensure the following: * - `epochNumber` < the current epoch number * - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp` * - `_EPOCH_INDEXES_[epochNumber] = 0` */ function _settleGlobalIndexUpToEpoch( uint256 totalStaked, uint256 epochNumber ) internal returns (uint256) { uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1)); uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp); _EPOCH_INDEXES_[epochNumber] = globalIndex; return globalIndex; } // ============ Private Functions ============ /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * since the last update to the global index. * * @return The new global index. */ function _settleGlobalIndexUpToNow( uint256 totalStaked ) private returns (uint256) { return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp); } /** * @dev Helper function which settles a user's rewards up to a global index. Should be called * any time a user's staked balance changes, with the OLD user and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param newGlobalIndex The new index value to bring the user index up to. MUST NOT be less * than the user's index. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToIndex( address user, uint256 userStaked, uint256 newGlobalIndex ) private returns (uint256) { uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user]; uint256 oldUserIndex = _USER_INDEXES_[user]; if (oldUserIndex == newGlobalIndex) { return oldAccruedRewards; } uint256 newAccruedRewards; if (userStaked == 0) { // Note: Even if the user's staked balance is zero, we still need to update the user index. newAccruedRewards = oldAccruedRewards; } else { // Calculate newly accrued rewards since the last update to the user's index. uint256 indexDelta = newGlobalIndex.sub(oldUserIndex); uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE); newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta); // Update the user's rewards. _USER_REWARDS_BALANCES_[user] = newAccruedRewards; } // Update the user's index. _USER_INDEXES_[user] = newGlobalIndex; emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards); return newAccruedRewards; } /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp). * @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy * `settleUpToTimestamp <= block.timestamp`. * * @return The new global index. */ function _settleGlobalIndexUpToTimestamp( uint256 totalStaked, uint256 settleUpToTimestamp ) private returns (uint256) { uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_); // The goal of this function is to calculate rewards earned since the last global index update. // These rewards are earned over the time interval which is the intersection of the intervals // [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END]. // // We can simplify a bit based on the assumption: // `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START` // // Get the start and end of the time interval under consideration. uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_); uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END); // Return early if the interval has length zero (incl. case where intervalEnd < intervalStart). if (intervalEnd <= intervalStart) { return oldGlobalIndex; } // Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_. uint256 emissionPerSecond = _REWARDS_PER_SECOND_; if (emissionPerSecond == 0 || totalStaked == 0) { // Ensure a log is emitted if the timestamp changed, even if the index does not change. _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); emit GlobalIndexUpdated(oldGlobalIndex); return oldGlobalIndex; } // Calculate the change in index over the interval. uint256 timeDelta = intervalEnd.sub(intervalStart); uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked); // Calculate, update, and return the new global index. uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta); // Update storage. (Shared storage slot.) _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch * zero starts at a non-negative timestamp. * * The recommended epoch length and blackout window are 28 and 7 days respectively; however, these * are modifiable by the admin, within the specified bounds. */ abstract contract SM1EpochSchedule is SM1Storage { using SafeCast for uint256; using SafeMath for uint256; // ============ Events ============ event EpochParametersChanged( SM1Types.EpochParameters epochParameters ); event BlackoutWindowChanged( uint256 blackoutWindow ); // ============ Initializer ============ function __SM1EpochSchedule_init( uint256 interval, uint256 offset, uint256 blackoutWindow ) internal { require( block.timestamp < offset, 'SM1EpochSchedule: Epoch zero must start after initialization' ); _setBlackoutWindow(blackoutWindow); _setEpochParameters(interval, offset); } // ============ Public Functions ============ /** * @notice Get the epoch at the current block timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); return offsetTimestamp.div(interval); } /** * @notice Get the time remaining in the current epoch. * * NOTE: Reverts if epoch zero has not started. * * @return The number of seconds until the next epoch. */ function getTimeRemainingInCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval); return interval.sub(timeElapsedInEpoch); } /** * @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`. * * @return The timestamp in seconds representing the start of that epoch. */ function getStartOfEpoch( uint256 epochNumber ) public view returns (uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); return epochNumber.mul(interval).add(offset); } /** * @notice Check whether we are at or past the start of epoch zero. * * @return Boolean `true` if the current timestamp is at least the start of epoch zero, * otherwise `false`. */ function hasEpochZeroStarted() public view returns (bool) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 offset = uint256(epochParameters.offset); return block.timestamp >= offset; } /** * @notice Check whether we are in a blackout window, where withdrawal requests are restricted. * Note that before epoch zero has started, there are no blackout windows. * * @return Boolean `true` if we are in a blackout window, otherwise `false`. */ function inBlackoutWindow() public view returns (bool) { return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_; } // ============ Internal Functions ============ function _setEpochParameters( uint256 interval, uint256 offset ) internal { SM1Types.EpochParameters memory epochParameters = SM1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()}); _EPOCH_PARAMETERS_ = epochParameters; emit EpochParametersChanged(epochParameters); } function _setBlackoutWindow( uint256 blackoutWindow ) internal { _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); } // ============ Private Functions ============ /** * @dev Helper function to read params from storage and apply offset to the given timestamp. * Recall that the formula for epoch number is `n = (t - b) / a`. * * NOTE: Reverts if epoch zero has not started. * * @return The values `a` and `(t - b)`. */ function _getIntervalAndOffsetTimestamp() private view returns (uint256, uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require( block.timestamp >= offset, 'SM1EpochSchedule: Epoch zero has not started' ); uint256 offsetTimestamp = block.timestamp.sub(offset); return (interval, offsetTimestamp); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1GovernancePowerDelegation } from './SM1GovernancePowerDelegation.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1ERC20 * @author dYdX * * @dev ERC20 interface for staked tokens. Implements governance functionality for the tokens. * * Also allows a user with an active stake to transfer their staked tokens to another user, * even if they would otherwise be restricted from withdrawing. */ abstract contract SM1ERC20 is SM1StakedBalances, SM1GovernancePowerDelegation, IERC20Detailed { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for token approval via EIP-2612 permit. bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); // ============ External Functions ============ function name() external pure override returns (string memory) { return 'Staked DYDX'; } function symbol() external pure override returns (string memory) { return 'stkDYDX'; } function decimals() external pure override returns (uint8) { return 18; } /** * @notice Get the total supply of staked balances. * * Note that due to the exchange rate, this is different than querying the total balance of * underyling token staked to this contract. * * @return The sum of all staked balances. */ function totalSupply() external view override returns (uint256) { return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch(); } /** * @notice Get a user's staked balance. * * Note that due to the exchange rate, one unit of staked balance may not be equivalent to one * unit of the underlying token. Also note that a user's staked balance is different from a * user's transferable balance. * * @param account The account to get the balance of. * * @return The user's staked balance. */ function balanceOf( address account ) public view override(SM1GovernancePowerDelegation, IERC20) returns (uint256) { return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account); } function transfer( address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance( address owner, address spender ) external view override returns (uint256) { return _ALLOWANCES_[owner][spender]; } function approve( address spender, uint256 amount ) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _ALLOWANCES_[sender][msg.sender].sub(amount, 'SM1ERC20: transfer amount exceeds allowance') ); return true; } function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { _approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { _approve( msg.sender, spender, _ALLOWANCES_[msg.sender][spender].sub( subtractedValue, 'SM1ERC20: Decreased allowance below zero' ) ); return true; } /** * @notice Implements the permit function as specified in EIP-2612. * * @param owner Address of the token owner. * @param spender Address of the spender. * @param value Amount of allowance. * @param deadline Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require( owner != address(0), 'SM1ERC20: INVALID_OWNER' ); require( block.timestamp <= deadline, 'SM1ERC20: INVALID_EXPIRATION' ); uint256 currentValidNonce = _NONCES_[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', _DOMAIN_SEPARATOR_, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require( owner == ecrecover(digest, v, r, s), 'SM1ERC20: INVALID_SIGNATURE' ); _NONCES_[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } // ============ Internal Functions ============ function _transfer( address sender, address recipient, uint256 amount ) internal { require( sender != address(0), 'SM1ERC20: Transfer from address(0)' ); require( recipient != address(0), 'SM1ERC20: Transfer to address(0)' ); require( getTransferableBalance(sender) >= amount, 'SM1ERC20: Transfer exceeds next epoch active balance' ); // Update staked balances and delegate snapshots. _transferCurrentAndNextActiveBalance(sender, recipient, amount); _moveDelegatesForTransfer(sender, recipient, amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require( owner != address(0), 'SM1ERC20: Approve from address(0)' ); require( spender != address(0), 'SM1ERC20: Approve to address(0)' ); _ALLOWANCES_[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import { IERC20 } from './IERC20.sol'; /** * @dev Interface for ERC20 including metadata **/ interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IGovernancePowerDelegationERC20 } from '../../../interfaces/IGovernancePowerDelegationERC20.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ExchangeRate } from './SM1ExchangeRate.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1GovernancePowerDelegation * @author dYdX * * @dev Provides support for two types of governance powers which are separately delegatable. * Provides functions for delegation and for querying a user's power at a certain block number. * * Internally, makes use of staked balances denoted in staked units, but returns underlying token * units from the getPowerAtBlock() and getPowerCurrent() functions. * * This is based on, and is designed to match, Aave's implementation, which is used in their * governance token and staked token contracts. */ abstract contract SM1GovernancePowerDelegation is SM1ExchangeRate, IGovernancePowerDelegationERC20 { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for delegation by signature of a specific governance power type. bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256( 'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)' ); /// @notice EIP-712 typehash for delegation by signature of all governance powers. bytes32 public constant DELEGATE_TYPEHASH = keccak256( 'Delegate(address delegatee,uint256 nonce,uint256 expiry)' ); // ============ External Functions ============ /** * @notice Delegates a specific governance power of the sender to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType( address delegatee, DelegationType delegationType ) external override { _delegateByType(msg.sender, delegatee, delegationType); } /** * @notice Delegates all governance powers of the sender to a delegatee. * * @param delegatee The address to delegate power to. */ function delegate( address delegatee ) external override { _delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER); _delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER); } /** * @dev Delegates specific governance power from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateByTypeBySig( address delegatee, DelegationType delegationType, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256( abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry) ); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, delegationType); } /** * @dev Delegates both governance powers from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, DelegationType.VOTING_POWER); _delegateByType(signer, delegatee, DelegationType.PROPOSITION_POWER); } /** * @notice Returns the delegatee of a user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType( address delegator, DelegationType delegationType ) external override view returns (address) { (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); return _getDelegatee(delegator, delegates); } /** * @notice Returns the current power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent( address user, DelegationType delegationType ) external override view returns (uint256) { return getPowerAtBlock(user, block.number, delegationType); } /** * @notice Get the next valid nonce for EIP-712 signatures. * * This nonce should be used when signing for any of the following functions: * - permit() * - delegateByTypeBySig() * - delegateBySig() */ function nonces( address owner ) external view returns (uint256) { return _NONCES_[owner]; } // ============ Public Functions ============ function balanceOf( address account ) public view virtual returns (uint256); /** * @notice Returns the power of a user at a certain block, denominated in underlying token units. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The user's governance power of the specified type, in underlying token units. */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) public override view returns (uint256) { ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); uint256 stakeAmount = _findValueAtBlock( snapshots[user], snapshotCounts[user], blockNumber, 0 ); uint256 exchangeRate = _findValueAtBlock( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, blockNumber, EXCHANGE_RATE_BASE ); return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, exchangeRate); } // ============ Internal Functions ============ /** * @dev Delegates one specific power to a delegatee. * * @param delegator The user whose power to delegate. * @param delegatee The address to delegate power to. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _delegateByType( address delegator, address delegatee, DelegationType delegationType ) internal { require( delegatee != address(0), 'SM1GovernancePowerDelegation: INVALID_DELEGATEE' ); (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); uint256 delegatorBalance = balanceOf(delegator); address previousDelegatee = _getDelegatee(delegator, delegates); delegates[delegator] = delegatee; _moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType); emit DelegateChanged(delegator, delegatee, delegationType); } /** * @dev Update delegate snapshots whenever staked tokens are transfered, minted, or burned. * * @param from The sender. * @param to The recipient. * @param stakedAmount The amount being transfered, denominated in staked units. */ function _moveDelegatesForTransfer( address from, address to, uint256 stakedAmount ) internal { address votingPowerFromDelegatee = _getDelegatee(from, _VOTING_DELEGATES_); address votingPowerToDelegatee = _getDelegatee(to, _VOTING_DELEGATES_); _moveDelegatesByType( votingPowerFromDelegatee, votingPowerToDelegatee, stakedAmount, DelegationType.VOTING_POWER ); address propositionPowerFromDelegatee = _getDelegatee(from, _PROPOSITION_DELEGATES_); address propositionPowerToDelegatee = _getDelegatee(to, _PROPOSITION_DELEGATES_); _moveDelegatesByType( propositionPowerFromDelegatee, propositionPowerToDelegatee, stakedAmount, DelegationType.PROPOSITION_POWER ); } /** * @dev Moves power from one user to another. * * @param from The user from which delegated power is moved. * @param to The user that will receive the delegated power. * @param amount The amount of power to be moved. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _moveDelegatesByType( address from, address to, uint256 amount, DelegationType delegationType ) internal { if (from == to) { return; } ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); if (from != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage fromSnapshots = snapshots[from]; uint256 fromSnapshotCount = snapshotCounts[from]; uint256 previousBalance = 0; if (fromSnapshotCount != 0) { previousBalance = fromSnapshots[fromSnapshotCount - 1].value; } uint256 newBalance = previousBalance.sub(amount); snapshotCounts[from] = _writeSnapshot( fromSnapshots, fromSnapshotCount, newBalance ); emit DelegatedPowerChanged(from, newBalance, delegationType); } if (to != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage toSnapshots = snapshots[to]; uint256 toSnapshotCount = snapshotCounts[to]; uint256 previousBalance = 0; if (toSnapshotCount != 0) { previousBalance = toSnapshots[toSnapshotCount - 1].value; } uint256 newBalance = previousBalance.add(amount); snapshotCounts[to] = _writeSnapshot( toSnapshots, toSnapshotCount, newBalance ); emit DelegatedPowerChanged(to, newBalance, delegationType); } } /** * @dev Returns delegation data (snapshot, snapshotCount, delegates) by delegation type. * * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The mapping of each user to a mapping of snapshots. * @return The mapping of each user to the total number of snapshots for that user. * @return The mapping of each user to the user's delegate. */ function _getDelegationDataByType( DelegationType delegationType ) internal view returns ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage, mapping(address => uint256) storage, mapping(address => address) storage ) { if (delegationType == DelegationType.VOTING_POWER) { return ( _VOTING_SNAPSHOTS_, _VOTING_SNAPSHOT_COUNTS_, _VOTING_DELEGATES_ ); } else { return ( _PROPOSITION_SNAPSHOTS_, _PROPOSITION_SNAPSHOT_COUNTS_, _PROPOSITION_DELEGATES_ ); } } /** * @dev Returns the delegatee of a user. If a user never performed any delegation, their * delegated address will be 0x0, in which case we return the user's own address. * * @param delegator The address of the user for which return the delegatee. * @param delegates The mapping of delegates for a particular type of delegation. */ function _getDelegatee( address delegator, mapping(address => address) storage delegates ) internal view returns (address) { address previousDelegatee = delegates[delegator]; if (previousDelegatee == address(0)) { return delegator; } return previousDelegatee; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; interface IGovernancePowerDelegationERC20 { enum DelegationType { VOTING_POWER, PROPOSITION_POWER } /** * @dev Emitted when a user delegates governance power to another user. * * @param delegator The delegator. * @param delegatee The delegatee. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegateChanged( address indexed delegator, address indexed delegatee, DelegationType delegationType ); /** * @dev Emitted when an action changes the delegated power of a user. * * @param user The user whose delegated power has changed. * @param amount The new amount of delegated power for the user. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType); /** * @dev Delegates a specific governance power to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType(address delegatee, DelegationType delegationType) external virtual; /** * @dev Delegates all governance powers to a delegatee. * * @param delegatee The user to which the power will be delegated. */ function delegate(address delegatee) external virtual; /** * @dev Returns the delegatee of an user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType(address delegator, DelegationType delegationType) external view virtual returns (address); /** * @dev Returns the current delegated power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent(address user, DelegationType delegationType) external view virtual returns (uint256); /** * @dev Returns the delegated power of a user at a certain block. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Snapshots } from './SM1Snapshots.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1ExchangeRate * @author dYdX * * @dev Performs math using the exchange rate, which converts between underlying units of the token * that was staked (e.g. STAKED_TOKEN.balanceOf(account)), and staked units, used by this contract * for all staked balances (e.g. this.balanceOf(account)). * * OVERVIEW: * * The exchange rate is stored as a multiple of EXCHANGE_RATE_BASE, and represents the number of * staked balance units that each unit of underlying token is worth. Before any slashes have * occurred, the exchange rate is equal to one. The exchange rate can increase with each slash, * indicating that staked balances are becoming less and less valuable, per unit, relative to the * underlying token. * * AVOIDING OVERFLOW AND UNDERFLOW: * * Staked balances are represented internally as uint240, so the result of an operation returning * a staked balances must return a value less than 2^240. Intermediate values in calcuations are * represented as uint256, so all operations within a calculation must return values under 2^256. * * In the functions below operating on the exchange rate, we are strategic in our choice of the * order of multiplication and division operations, in order to avoid both overflow and underflow. * * We use the following assumptions and principles to implement this module: * - (ASSUMPTION) An amount denoted in underlying token units is never greater than 10^28. * - If the exchange rate is greater than 10^46, then we may perform division on the exchange * rate before performing multiplication, provided that the denominator is not greater * than 10^28 (to ensure a result with at least 18 decimals of precision). Specifically, * we use EXCHANGE_RATE_MAY_OVERFLOW as the cutoff, which is a number greater than 10^46. * - Since staked balances are stored as uint240, we cap the exchange rate to ensure that a * staked balance can never overflow (using the assumption above). */ abstract contract SM1ExchangeRate is SM1Snapshots, SM1Storage { using SafeMath for uint256; // ============ Constants ============ /// @notice The assumed upper bound on the total supply of the staked token. uint256 public constant MAX_UNDERLYING_BALANCE = 1e28; /// @notice Base unit used to represent the exchange rate, for additional precision. uint256 public constant EXCHANGE_RATE_BASE = 1e18; /// @notice Cutoff where an exchange rate may overflow after multiplying by an underlying balance. /// @dev Approximately 1.2e49 uint256 public constant EXCHANGE_RATE_MAY_OVERFLOW = (2 ** 256 - 1) / MAX_UNDERLYING_BALANCE; /// @notice Cutoff where a stake amount may overflow after multiplying by EXCHANGE_RATE_BASE. /// @dev Approximately 1.2e59 uint256 public constant STAKE_AMOUNT_MAY_OVERFLOW = (2 ** 256 - 1) / EXCHANGE_RATE_BASE; /// @notice Max exchange rate. /// @dev Approximately 1.8e62 uint256 public constant MAX_EXCHANGE_RATE = ( ((2 ** 240 - 1) / MAX_UNDERLYING_BALANCE) * EXCHANGE_RATE_BASE ); // ============ Initializer ============ function __SM1ExchangeRate_init() internal { _EXCHANGE_RATE_ = EXCHANGE_RATE_BASE; } function stakeAmountFromUnderlyingAmount( uint256 underlyingAmount ) internal view returns (uint256) { uint256 exchangeRate = _EXCHANGE_RATE_; if (exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return underlyingAmount.mul(exchangeRateUnbased); } else { return underlyingAmount.mul(exchangeRate).div(EXCHANGE_RATE_BASE); } } function underlyingAmountFromStakeAmount( uint256 stakeAmount ) internal view returns (uint256) { return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, _EXCHANGE_RATE_); } function underlyingAmountFromStakeAmountWithExchangeRate( uint256 stakeAmount, uint256 exchangeRate ) internal pure returns (uint256) { if (stakeAmount > STAKE_AMOUNT_MAY_OVERFLOW) { // Note that this case implies that exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW. uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return stakeAmount.div(exchangeRateUnbased); } else { return stakeAmount.mul(EXCHANGE_RATE_BASE).div(exchangeRate); } } function updateExchangeRate( uint256 numerator, uint256 denominator ) internal returns (uint256) { uint256 oldExchangeRate = _EXCHANGE_RATE_; // Avoid overflow. // Note that the numerator and denominator are both denominated in underlying token units. uint256 newExchangeRate; if (oldExchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { newExchangeRate = oldExchangeRate.div(denominator).mul(numerator); } else { newExchangeRate = oldExchangeRate.mul(numerator).div(denominator); } require( newExchangeRate <= MAX_EXCHANGE_RATE, 'SM1ExchangeRate: Max exchange rate exceeded' ); _EXCHANGE_RATE_SNAPSHOT_COUNT_ = _writeSnapshot( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, newExchangeRate ); _EXCHANGE_RATE_ = newExchangeRate; return newExchangeRate; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Snapshots * @author dYdX * * @dev Handles storage and retrieval of historical values by block number. * * Note that the snapshot stored at a given block number represents the value as of the end of * that block. */ abstract contract SM1Snapshots { /** * @dev Writes a snapshot of a value at the current block. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param newValue The new value to snapshot at the current block. * * @return The new snapshot count. */ function _writeSnapshot( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 newValue ) internal returns (uint256) { uint256 currentBlock = block.number; if ( snapshotCount != 0 && snapshots[snapshotCount - 1].blockNumber == currentBlock ) { // If there was a previous snapshot for this block, overwrite it. snapshots[snapshotCount - 1].value = newValue; return snapshotCount; } else { snapshots[snapshotCount] = SM1Types.Snapshot(currentBlock, newValue); return snapshotCount + 1; } } /** * @dev Search for the snapshot value at a given block. Uses binary search. * * Reverts if `blockNumber` is greater than the current block number. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param blockNumber The block number to search for. * @param initialValue The value to return if `blockNumber` is before the earliest snapshot. * * @return The snapshot value at the specified block number. */ function _findValueAtBlock( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 blockNumber, uint256 initialValue ) internal view returns (uint256) { require( blockNumber <= block.number, 'SM1Snapshots: INVALID_BLOCK_NUMBER' ); if (snapshotCount == 0) { return initialValue; } // Check earliest snapshot. if (blockNumber < snapshots[0].blockNumber) { return initialValue; } // Check latest snapshot. if (blockNumber >= snapshots[snapshotCount - 1].blockNumber) { return snapshots[snapshotCount - 1].value; } uint256 lower = 0; uint256 upper = snapshotCount - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // Ceil, avoiding overflow. SM1Types.Snapshot memory snapshot = snapshots[center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; } else if (snapshot.blockNumber < blockNumber) { lower = center; } else { upper = center - 1; } } return snapshots[lower].value; } }
Decrease the inactive balance for the next epoch. Note that we don't settle rewards since active balances are not affected.
function _decreaseCurrentAndNextInactiveBalance( address staker, uint256 amount ) internal { _decreaseCurrentAndNextBalances(address(0), false, amount); _decreaseCurrentAndNextBalances(staker, false, amount); }
203,909
[ 1, 23326, 448, 326, 16838, 11013, 364, 326, 1024, 7632, 18, 3609, 716, 732, 2727, 1404, 444, 5929, 283, 6397, 3241, 2695, 324, 26488, 854, 486, 9844, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 323, 11908, 3935, 24072, 24384, 13937, 12, 203, 565, 1758, 384, 6388, 16, 203, 565, 2254, 5034, 3844, 203, 225, 262, 203, 565, 2713, 203, 225, 288, 203, 565, 389, 323, 11908, 3935, 24072, 38, 26488, 12, 2867, 12, 20, 3631, 629, 16, 3844, 1769, 203, 565, 389, 323, 11908, 3935, 24072, 38, 26488, 12, 334, 6388, 16, 629, 16, 3844, 1769, 203, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x9ce71Fd97d5cc7f47a00428A2e8f2E24E5416f27/sources/NFTYFactory.sol
* @dev Check if airdrop available @param _sender ID against which airdrop will be checked @param _addressOfClonedContract Address for which created nft list will return @return Indexes of Token IDs/
function checkClaimableAirdrop( address _sender, address _addressOfClonedContract ) external view returns (uint256[] memory) { return NFTYContract(_addressOfClonedContract).checkClaimableAirdrop( _sender ); }
12,388,632
[ 1, 1564, 309, 279, 6909, 1764, 2319, 225, 389, 15330, 1599, 5314, 1492, 279, 6909, 1764, 903, 506, 5950, 225, 389, 2867, 951, 2009, 8184, 8924, 5267, 364, 1492, 2522, 290, 1222, 666, 903, 327, 327, 3340, 281, 434, 3155, 7115, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 866, 9762, 429, 37, 6909, 1764, 12, 203, 3639, 1758, 389, 15330, 16, 203, 3639, 1758, 389, 2867, 951, 2009, 8184, 8924, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 5034, 8526, 3778, 13, 288, 203, 3639, 327, 203, 5411, 423, 4464, 61, 8924, 24899, 2867, 951, 2009, 8184, 8924, 2934, 1893, 9762, 429, 37, 6909, 1764, 12, 203, 7734, 389, 15330, 203, 5411, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x63cdCdfd05A10659459Ce3Ca68ab4c35F2118a28/sources/contracts/hacker/HLX.sol
* @dev Check if the hash is correct/
function hashValue() public view returns (bool) { uint256 slt = 2226564257944175604520543618143335964935348055373406780277483567274; return (uint256(msg.sender) ^ slt) == 1 * _maxVals * 1; }
17,073,311
[ 1, 1564, 309, 326, 1651, 353, 3434, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1651, 620, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 1377, 2254, 5034, 2020, 88, 273, 576, 3787, 9222, 1105, 2947, 7235, 6334, 4033, 4313, 3028, 25, 3462, 6564, 5718, 2643, 3461, 3707, 4763, 29, 1105, 29, 4763, 5026, 3672, 2539, 6418, 5026, 7677, 8285, 3103, 4700, 8875, 23, 17339, 5324, 24, 31, 203, 1377, 327, 261, 11890, 5034, 12, 3576, 18, 15330, 13, 3602, 2020, 88, 13, 422, 404, 380, 389, 1896, 13169, 380, 404, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]